1 /*
   2  * Copyright (c) 1997, 2016, 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 "runtime/thread.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #include "gc/shenandoah/shenandoahConnectionMatrix.hpp"
  49 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  50 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  51 #endif // INCLUDE_ALL_GCS
  52 #include "crc32c.h"
  53 #ifdef COMPILER2
  54 #include "opto/intrinsicnode.hpp"
  55 #endif
  56 
  57 #ifdef PRODUCT
  58 #define BLOCK_COMMENT(str) /* nothing */
  59 #define STOP(error) stop(error)
  60 #else
  61 #define BLOCK_COMMENT(str) block_comment(str)
  62 #define STOP(error) block_comment(error); stop(error)
  63 #endif
  64 
  65 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  66 
  67 #ifdef ASSERT
  68 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  69 #endif
  70 
  71 static Assembler::Condition reverse[] = {
  72     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  73     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  74     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  75     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  76     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  77     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  78     Assembler::above          /* belowEqual    = 0x6 */ ,
  79     Assembler::belowEqual     /* above         = 0x7 */ ,
  80     Assembler::positive       /* negative      = 0x8 */ ,
  81     Assembler::negative       /* positive      = 0x9 */ ,
  82     Assembler::noParity       /* parity        = 0xa */ ,
  83     Assembler::parity         /* noParity      = 0xb */ ,
  84     Assembler::greaterEqual   /* less          = 0xc */ ,
  85     Assembler::less           /* greaterEqual  = 0xd */ ,
  86     Assembler::greater        /* lessEqual     = 0xe */ ,
  87     Assembler::lessEqual      /* greater       = 0xf, */
  88 
  89 };
  90 
  91 
  92 // Implementation of MacroAssembler
  93 
  94 // First all the versions that have distinct versions depending on 32/64 bit
  95 // Unless the difference is trivial (1 line or so).
  96 
  97 #ifndef _LP64
  98 
  99 // 32bit versions
 100 
 101 Address MacroAssembler::as_Address(AddressLiteral adr) {
 102   return Address(adr.target(), adr.rspec());
 103 }
 104 
 105 Address MacroAssembler::as_Address(ArrayAddress adr) {
 106   return Address::make_array(adr);
 107 }
 108 
 109 void MacroAssembler::call_VM_leaf_base(address entry_point,
 110                                        int number_of_arguments) {
 111   call(RuntimeAddress(entry_point));
 112   increment(rsp, number_of_arguments * wordSize);
 113 }
 114 
 115 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 116   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 117 }
 118 
 119 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 120   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 121 }
 122 
 123 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 124   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 125 }
 126 
 127 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 128   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 129 }
 130 
 131 void MacroAssembler::extend_sign(Register hi, Register lo) {
 132   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 133   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 134     cdql();
 135   } else {
 136     movl(hi, lo);
 137     sarl(hi, 31);
 138   }
 139 }
 140 
 141 void MacroAssembler::jC2(Register tmp, Label& L) {
 142   // set parity bit if FPU flag C2 is set (via rax)
 143   save_rax(tmp);
 144   fwait(); fnstsw_ax();
 145   sahf();
 146   restore_rax(tmp);
 147   // branch
 148   jcc(Assembler::parity, L);
 149 }
 150 
 151 void MacroAssembler::jnC2(Register tmp, Label& L) {
 152   // set parity bit if FPU flag C2 is set (via rax)
 153   save_rax(tmp);
 154   fwait(); fnstsw_ax();
 155   sahf();
 156   restore_rax(tmp);
 157   // branch
 158   jcc(Assembler::noParity, L);
 159 }
 160 
 161 // 32bit can do a case table jump in one instruction but we no longer allow the base
 162 // to be installed in the Address class
 163 void MacroAssembler::jump(ArrayAddress entry) {
 164   jmp(as_Address(entry));
 165 }
 166 
 167 // Note: y_lo will be destroyed
 168 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 169   // Long compare for Java (semantics as described in JVM spec.)
 170   Label high, low, done;
 171 
 172   cmpl(x_hi, y_hi);
 173   jcc(Assembler::less, low);
 174   jcc(Assembler::greater, high);
 175   // x_hi is the return register
 176   xorl(x_hi, x_hi);
 177   cmpl(x_lo, y_lo);
 178   jcc(Assembler::below, low);
 179   jcc(Assembler::equal, done);
 180 
 181   bind(high);
 182   xorl(x_hi, x_hi);
 183   increment(x_hi);
 184   jmp(done);
 185 
 186   bind(low);
 187   xorl(x_hi, x_hi);
 188   decrementl(x_hi);
 189 
 190   bind(done);
 191 }
 192 
 193 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 194     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 195 }
 196 
 197 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 198   // leal(dst, as_Address(adr));
 199   // see note in movl as to why we must use a move
 200   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 201 }
 202 
 203 void MacroAssembler::leave() {
 204   mov(rsp, rbp);
 205   pop(rbp);
 206 }
 207 
 208 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 209   // Multiplication of two Java long values stored on the stack
 210   // as illustrated below. Result is in rdx:rax.
 211   //
 212   // rsp ---> [  ??  ] \               \
 213   //            ....    | y_rsp_offset  |
 214   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 215   //          [ y_hi ]                  | (in bytes)
 216   //            ....                    |
 217   //          [ x_lo ]                 /
 218   //          [ x_hi ]
 219   //            ....
 220   //
 221   // Basic idea: lo(result) = lo(x_lo * y_lo)
 222   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 223   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 224   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 225   Label quick;
 226   // load x_hi, y_hi and check if quick
 227   // multiplication is possible
 228   movl(rbx, x_hi);
 229   movl(rcx, y_hi);
 230   movl(rax, rbx);
 231   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 232   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 233   // do full multiplication
 234   // 1st step
 235   mull(y_lo);                                    // x_hi * y_lo
 236   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 237   // 2nd step
 238   movl(rax, x_lo);
 239   mull(rcx);                                     // x_lo * y_hi
 240   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 241   // 3rd step
 242   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 243   movl(rax, x_lo);
 244   mull(y_lo);                                    // x_lo * y_lo
 245   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 246 }
 247 
 248 void MacroAssembler::lneg(Register hi, Register lo) {
 249   negl(lo);
 250   adcl(hi, 0);
 251   negl(hi);
 252 }
 253 
 254 void MacroAssembler::lshl(Register hi, Register lo) {
 255   // Java shift left long support (semantics as described in JVM spec., p.305)
 256   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 257   // shift value is in rcx !
 258   assert(hi != rcx, "must not use rcx");
 259   assert(lo != rcx, "must not use rcx");
 260   const Register s = rcx;                        // shift count
 261   const int      n = BitsPerWord;
 262   Label L;
 263   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 264   cmpl(s, n);                                    // if (s < n)
 265   jcc(Assembler::less, L);                       // else (s >= n)
 266   movl(hi, lo);                                  // x := x << n
 267   xorl(lo, lo);
 268   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 269   bind(L);                                       // s (mod n) < n
 270   shldl(hi, lo);                                 // x := x << s
 271   shll(lo);
 272 }
 273 
 274 
 275 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 276   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 277   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 278   assert(hi != rcx, "must not use rcx");
 279   assert(lo != rcx, "must not use rcx");
 280   const Register s = rcx;                        // shift count
 281   const int      n = BitsPerWord;
 282   Label L;
 283   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 284   cmpl(s, n);                                    // if (s < n)
 285   jcc(Assembler::less, L);                       // else (s >= n)
 286   movl(lo, hi);                                  // x := x >> n
 287   if (sign_extension) sarl(hi, 31);
 288   else                xorl(hi, hi);
 289   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 290   bind(L);                                       // s (mod n) < n
 291   shrdl(lo, hi);                                 // x := x >> s
 292   if (sign_extension) sarl(hi);
 293   else                shrl(hi);
 294 }
 295 
 296 void MacroAssembler::movoop(Register dst, jobject obj) {
 297   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 298 }
 299 
 300 void MacroAssembler::movoop(Address dst, jobject obj) {
 301   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 302 }
 303 
 304 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 305   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 309   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 310 }
 311 
 312 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 313   // scratch register is not used,
 314   // it is defined to match parameters of 64-bit version of this method.
 315   if (src.is_lval()) {
 316     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 317   } else {
 318     movl(dst, as_Address(src));
 319   }
 320 }
 321 
 322 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 323   movl(as_Address(dst), src);
 324 }
 325 
 326 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 327   movl(dst, as_Address(src));
 328 }
 329 
 330 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 331 void MacroAssembler::movptr(Address dst, intptr_t src) {
 332   movl(dst, src);
 333 }
 334 
 335 
 336 void MacroAssembler::pop_callee_saved_registers() {
 337   pop(rcx);
 338   pop(rdx);
 339   pop(rdi);
 340   pop(rsi);
 341 }
 342 
 343 void MacroAssembler::pop_fTOS() {
 344   fld_d(Address(rsp, 0));
 345   addl(rsp, 2 * wordSize);
 346 }
 347 
 348 void MacroAssembler::push_callee_saved_registers() {
 349   push(rsi);
 350   push(rdi);
 351   push(rdx);
 352   push(rcx);
 353 }
 354 
 355 void MacroAssembler::push_fTOS() {
 356   subl(rsp, 2 * wordSize);
 357   fstp_d(Address(rsp, 0));
 358 }
 359 
 360 
 361 void MacroAssembler::pushoop(jobject obj) {
 362   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 363 }
 364 
 365 void MacroAssembler::pushklass(Metadata* obj) {
 366   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 367 }
 368 
 369 void MacroAssembler::pushptr(AddressLiteral src) {
 370   if (src.is_lval()) {
 371     push_literal32((int32_t)src.target(), src.rspec());
 372   } else {
 373     pushl(as_Address(src));
 374   }
 375 }
 376 
 377 void MacroAssembler::set_word_if_not_zero(Register dst) {
 378   xorl(dst, dst);
 379   set_byte_if_not_zero(dst);
 380 }
 381 
 382 static void pass_arg0(MacroAssembler* masm, Register arg) {
 383   masm->push(arg);
 384 }
 385 
 386 static void pass_arg1(MacroAssembler* masm, Register arg) {
 387   masm->push(arg);
 388 }
 389 
 390 static void pass_arg2(MacroAssembler* masm, Register arg) {
 391   masm->push(arg);
 392 }
 393 
 394 static void pass_arg3(MacroAssembler* masm, Register arg) {
 395   masm->push(arg);
 396 }
 397 
 398 #ifndef PRODUCT
 399 extern "C" void findpc(intptr_t x);
 400 #endif
 401 
 402 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 403   // In order to get locks to work, we need to fake a in_VM state
 404   JavaThread* thread = JavaThread::current();
 405   JavaThreadState saved_state = thread->thread_state();
 406   thread->set_thread_state(_thread_in_vm);
 407   if (ShowMessageBoxOnError) {
 408     JavaThread* thread = JavaThread::current();
 409     JavaThreadState saved_state = thread->thread_state();
 410     thread->set_thread_state(_thread_in_vm);
 411     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 412       ttyLocker ttyl;
 413       BytecodeCounter::print();
 414     }
 415     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 416     // This is the value of eip which points to where verify_oop will return.
 417     if (os::message_box(msg, "Execution stopped, print registers?")) {
 418       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 419       BREAKPOINT;
 420     }
 421   } else {
 422     ttyLocker ttyl;
 423     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 424   }
 425   // Don't assert holding the ttyLock
 426     assert(false, "DEBUG MESSAGE: %s", msg);
 427   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 428 }
 429 
 430 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 431   ttyLocker ttyl;
 432   FlagSetting fs(Debugging, true);
 433   tty->print_cr("eip = 0x%08x", eip);
 434 #ifndef PRODUCT
 435   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 436     tty->cr();
 437     findpc(eip);
 438     tty->cr();
 439   }
 440 #endif
 441 #define PRINT_REG(rax) \
 442   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 443   PRINT_REG(rax);
 444   PRINT_REG(rbx);
 445   PRINT_REG(rcx);
 446   PRINT_REG(rdx);
 447   PRINT_REG(rdi);
 448   PRINT_REG(rsi);
 449   PRINT_REG(rbp);
 450   PRINT_REG(rsp);
 451 #undef PRINT_REG
 452   // Print some words near top of staack.
 453   int* dump_sp = (int*) rsp;
 454   for (int col1 = 0; col1 < 8; col1++) {
 455     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 456     os::print_location(tty, *dump_sp++);
 457   }
 458   for (int row = 0; row < 16; row++) {
 459     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 460     for (int col = 0; col < 8; col++) {
 461       tty->print(" 0x%08x", *dump_sp++);
 462     }
 463     tty->cr();
 464   }
 465   // Print some instructions around pc:
 466   Disassembler::decode((address)eip-64, (address)eip);
 467   tty->print_cr("--------");
 468   Disassembler::decode((address)eip, (address)eip+32);
 469 }
 470 
 471 void MacroAssembler::stop(const char* msg) {
 472   ExternalAddress message((address)msg);
 473   // push address of message
 474   pushptr(message.addr());
 475   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 476   pusha();                                            // push registers
 477   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 478   hlt();
 479 }
 480 
 481 void MacroAssembler::warn(const char* msg) {
 482   push_CPU_state();
 483 
 484   ExternalAddress message((address) msg);
 485   // push address of message
 486   pushptr(message.addr());
 487 
 488   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 489   addl(rsp, wordSize);       // discard argument
 490   pop_CPU_state();
 491 }
 492 
 493 void MacroAssembler::print_state() {
 494   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 495   pusha();                                            // push registers
 496 
 497   push_CPU_state();
 498   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 499   pop_CPU_state();
 500 
 501   popa();
 502   addl(rsp, wordSize);
 503 }
 504 
 505 #else // _LP64
 506 
 507 // 64 bit versions
 508 
 509 Address MacroAssembler::as_Address(AddressLiteral adr) {
 510   // amd64 always does this as a pc-rel
 511   // we can be absolute or disp based on the instruction type
 512   // jmp/call are displacements others are absolute
 513   assert(!adr.is_lval(), "must be rval");
 514   assert(reachable(adr), "must be");
 515   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 516 
 517 }
 518 
 519 Address MacroAssembler::as_Address(ArrayAddress adr) {
 520   AddressLiteral base = adr.base();
 521   lea(rscratch1, base);
 522   Address index = adr.index();
 523   assert(index._disp == 0, "must not have disp"); // maybe it can?
 524   Address array(rscratch1, index._index, index._scale, index._disp);
 525   return array;
 526 }
 527 
 528 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 529   Label L, E;
 530 
 531 #ifdef _WIN64
 532   // Windows always allocates space for it's register args
 533   assert(num_args <= 4, "only register arguments supported");
 534   subq(rsp,  frame::arg_reg_save_area_bytes);
 535 #endif
 536 
 537   // Align stack if necessary
 538   testl(rsp, 15);
 539   jcc(Assembler::zero, L);
 540 
 541   subq(rsp, 8);
 542   {
 543     call(RuntimeAddress(entry_point));
 544   }
 545   addq(rsp, 8);
 546   jmp(E);
 547 
 548   bind(L);
 549   {
 550     call(RuntimeAddress(entry_point));
 551   }
 552 
 553   bind(E);
 554 
 555 #ifdef _WIN64
 556   // restore stack pointer
 557   addq(rsp, frame::arg_reg_save_area_bytes);
 558 #endif
 559 
 560 }
 561 
 562 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 563   assert(!src2.is_lval(), "should use cmpptr");
 564 
 565   if (reachable(src2)) {
 566     cmpq(src1, as_Address(src2));
 567   } else {
 568     lea(rscratch1, src2);
 569     Assembler::cmpq(src1, Address(rscratch1, 0));
 570   }
 571 }
 572 
 573 int MacroAssembler::corrected_idivq(Register reg) {
 574   // Full implementation of Java ldiv and lrem; checks for special
 575   // case as described in JVM spec., p.243 & p.271.  The function
 576   // returns the (pc) offset of the idivl instruction - may be needed
 577   // for implicit exceptions.
 578   //
 579   //         normal case                           special case
 580   //
 581   // input : rax: dividend                         min_long
 582   //         reg: divisor   (may not be eax/edx)   -1
 583   //
 584   // output: rax: quotient  (= rax idiv reg)       min_long
 585   //         rdx: remainder (= rax irem reg)       0
 586   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 587   static const int64_t min_long = 0x8000000000000000;
 588   Label normal_case, special_case;
 589 
 590   // check for special case
 591   cmp64(rax, ExternalAddress((address) &min_long));
 592   jcc(Assembler::notEqual, normal_case);
 593   xorl(rdx, rdx); // prepare rdx for possible special case (where
 594                   // remainder = 0)
 595   cmpq(reg, -1);
 596   jcc(Assembler::equal, special_case);
 597 
 598   // handle normal case
 599   bind(normal_case);
 600   cdqq();
 601   int idivq_offset = offset();
 602   idivq(reg);
 603 
 604   // normal and special case exit
 605   bind(special_case);
 606 
 607   return idivq_offset;
 608 }
 609 
 610 void MacroAssembler::decrementq(Register reg, int value) {
 611   if (value == min_jint) { subq(reg, value); return; }
 612   if (value <  0) { incrementq(reg, -value); return; }
 613   if (value == 0) {                        ; return; }
 614   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 615   /* else */      { subq(reg, value)       ; return; }
 616 }
 617 
 618 void MacroAssembler::decrementq(Address dst, int value) {
 619   if (value == min_jint) { subq(dst, value); return; }
 620   if (value <  0) { incrementq(dst, -value); return; }
 621   if (value == 0) {                        ; return; }
 622   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 623   /* else */      { subq(dst, value)       ; return; }
 624 }
 625 
 626 void MacroAssembler::incrementq(AddressLiteral dst) {
 627   if (reachable(dst)) {
 628     incrementq(as_Address(dst));
 629   } else {
 630     lea(rscratch1, dst);
 631     incrementq(Address(rscratch1, 0));
 632   }
 633 }
 634 
 635 void MacroAssembler::incrementq(Register reg, int value) {
 636   if (value == min_jint) { addq(reg, value); return; }
 637   if (value <  0) { decrementq(reg, -value); return; }
 638   if (value == 0) {                        ; return; }
 639   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 640   /* else */      { addq(reg, value)       ; return; }
 641 }
 642 
 643 void MacroAssembler::incrementq(Address dst, int value) {
 644   if (value == min_jint) { addq(dst, value); return; }
 645   if (value <  0) { decrementq(dst, -value); return; }
 646   if (value == 0) {                        ; return; }
 647   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 648   /* else */      { addq(dst, value)       ; return; }
 649 }
 650 
 651 // 32bit can do a case table jump in one instruction but we no longer allow the base
 652 // to be installed in the Address class
 653 void MacroAssembler::jump(ArrayAddress entry) {
 654   lea(rscratch1, entry.base());
 655   Address dispatch = entry.index();
 656   assert(dispatch._base == noreg, "must be");
 657   dispatch._base = rscratch1;
 658   jmp(dispatch);
 659 }
 660 
 661 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 662   ShouldNotReachHere(); // 64bit doesn't use two regs
 663   cmpq(x_lo, y_lo);
 664 }
 665 
 666 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 667     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 668 }
 669 
 670 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 671   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 672   movptr(dst, rscratch1);
 673 }
 674 
 675 void MacroAssembler::leave() {
 676   // %%% is this really better? Why not on 32bit too?
 677   emit_int8((unsigned char)0xC9); // LEAVE
 678 }
 679 
 680 void MacroAssembler::lneg(Register hi, Register lo) {
 681   ShouldNotReachHere(); // 64bit doesn't use two regs
 682   negq(lo);
 683 }
 684 
 685 void MacroAssembler::movoop(Register dst, jobject obj) {
 686   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 687 }
 688 
 689 void MacroAssembler::movoop(Address dst, jobject obj) {
 690   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 691   movq(dst, rscratch1);
 692 }
 693 
 694 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 695   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 696 }
 697 
 698 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 699   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 700   movq(dst, rscratch1);
 701 }
 702 
 703 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 704   if (src.is_lval()) {
 705     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 706   } else {
 707     if (reachable(src)) {
 708       movq(dst, as_Address(src));
 709     } else {
 710       lea(scratch, src);
 711       movq(dst, Address(scratch, 0));
 712     }
 713   }
 714 }
 715 
 716 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 717   movq(as_Address(dst), src);
 718 }
 719 
 720 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 721   movq(dst, as_Address(src));
 722 }
 723 
 724 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 725 void MacroAssembler::movptr(Address dst, intptr_t src) {
 726   mov64(rscratch1, src);
 727   movq(dst, rscratch1);
 728 }
 729 
 730 // These are mostly for initializing NULL
 731 void MacroAssembler::movptr(Address dst, int32_t src) {
 732   movslq(dst, src);
 733 }
 734 
 735 void MacroAssembler::movptr(Register dst, int32_t src) {
 736   mov64(dst, (intptr_t)src);
 737 }
 738 
 739 void MacroAssembler::pushoop(jobject obj) {
 740   movoop(rscratch1, obj);
 741   push(rscratch1);
 742 }
 743 
 744 void MacroAssembler::pushklass(Metadata* obj) {
 745   mov_metadata(rscratch1, obj);
 746   push(rscratch1);
 747 }
 748 
 749 void MacroAssembler::pushptr(AddressLiteral src) {
 750   lea(rscratch1, src);
 751   if (src.is_lval()) {
 752     push(rscratch1);
 753   } else {
 754     pushq(Address(rscratch1, 0));
 755   }
 756 }
 757 
 758 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 759   // we must set sp to zero to clear frame
 760   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 761   // must clear fp, so that compiled frames are not confused; it is
 762   // possible that we need it only for debugging
 763   if (clear_fp) {
 764     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 765   }
 766 
 767   // Always clear the pc because it could have been set by make_walkable()
 768   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 769 }
 770 
 771 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 772                                          Register last_java_fp,
 773                                          address  last_java_pc) {
 774   // determine last_java_sp register
 775   if (!last_java_sp->is_valid()) {
 776     last_java_sp = rsp;
 777   }
 778 
 779   // last_java_fp is optional
 780   if (last_java_fp->is_valid()) {
 781     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 782            last_java_fp);
 783   }
 784 
 785   // last_java_pc is optional
 786   if (last_java_pc != NULL) {
 787     Address java_pc(r15_thread,
 788                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 789     lea(rscratch1, InternalAddress(last_java_pc));
 790     movptr(java_pc, rscratch1);
 791   }
 792 
 793   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 794 }
 795 
 796 static void pass_arg0(MacroAssembler* masm, Register arg) {
 797   if (c_rarg0 != arg ) {
 798     masm->mov(c_rarg0, arg);
 799   }
 800 }
 801 
 802 static void pass_arg1(MacroAssembler* masm, Register arg) {
 803   if (c_rarg1 != arg ) {
 804     masm->mov(c_rarg1, arg);
 805   }
 806 }
 807 
 808 static void pass_arg2(MacroAssembler* masm, Register arg) {
 809   if (c_rarg2 != arg ) {
 810     masm->mov(c_rarg2, arg);
 811   }
 812 }
 813 
 814 static void pass_arg3(MacroAssembler* masm, Register arg) {
 815   if (c_rarg3 != arg ) {
 816     masm->mov(c_rarg3, arg);
 817   }
 818 }
 819 
 820 void MacroAssembler::stop(const char* msg) {
 821   address rip = pc();
 822   pusha(); // get regs on stack
 823   lea(c_rarg0, ExternalAddress((address) msg));
 824   lea(c_rarg1, InternalAddress(rip));
 825   movq(c_rarg2, rsp); // pass pointer to regs array
 826   andq(rsp, -16); // align stack as required by ABI
 827   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 828   hlt();
 829 }
 830 
 831 void MacroAssembler::warn(const char* msg) {
 832   push(rbp);
 833   movq(rbp, rsp);
 834   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 835   push_CPU_state();   // keeps alignment at 16 bytes
 836   lea(c_rarg0, ExternalAddress((address) msg));
 837   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 838   pop_CPU_state();
 839   mov(rsp, rbp);
 840   pop(rbp);
 841 }
 842 
 843 void MacroAssembler::print_state() {
 844   address rip = pc();
 845   pusha();            // get regs on stack
 846   push(rbp);
 847   movq(rbp, rsp);
 848   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 849   push_CPU_state();   // keeps alignment at 16 bytes
 850 
 851   lea(c_rarg0, InternalAddress(rip));
 852   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 853   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 854 
 855   pop_CPU_state();
 856   mov(rsp, rbp);
 857   pop(rbp);
 858   popa();
 859 }
 860 
 861 #ifndef PRODUCT
 862 extern "C" void findpc(intptr_t x);
 863 #endif
 864 
 865 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 866   // In order to get locks to work, we need to fake a in_VM state
 867   if (ShowMessageBoxOnError) {
 868     JavaThread* thread = JavaThread::current();
 869     JavaThreadState saved_state = thread->thread_state();
 870     thread->set_thread_state(_thread_in_vm);
 871 #ifndef PRODUCT
 872     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 873       ttyLocker ttyl;
 874       BytecodeCounter::print();
 875     }
 876 #endif
 877     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 878     // XXX correct this offset for amd64
 879     // This is the value of eip which points to where verify_oop will return.
 880     if (os::message_box(msg, "Execution stopped, print registers?")) {
 881       print_state64(pc, regs);
 882       BREAKPOINT;
 883       assert(false, "start up GDB");
 884     }
 885     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 886   } else {
 887     ttyLocker ttyl;
 888     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 889                     msg);
 890     assert(false, "DEBUG MESSAGE: %s", msg);
 891   }
 892 }
 893 
 894 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 895   ttyLocker ttyl;
 896   FlagSetting fs(Debugging, true);
 897   tty->print_cr("rip = 0x%016lx", pc);
 898 #ifndef PRODUCT
 899   tty->cr();
 900   findpc(pc);
 901   tty->cr();
 902 #endif
 903 #define PRINT_REG(rax, value) \
 904   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 905   PRINT_REG(rax, regs[15]);
 906   PRINT_REG(rbx, regs[12]);
 907   PRINT_REG(rcx, regs[14]);
 908   PRINT_REG(rdx, regs[13]);
 909   PRINT_REG(rdi, regs[8]);
 910   PRINT_REG(rsi, regs[9]);
 911   PRINT_REG(rbp, regs[10]);
 912   PRINT_REG(rsp, regs[11]);
 913   PRINT_REG(r8 , regs[7]);
 914   PRINT_REG(r9 , regs[6]);
 915   PRINT_REG(r10, regs[5]);
 916   PRINT_REG(r11, regs[4]);
 917   PRINT_REG(r12, regs[3]);
 918   PRINT_REG(r13, regs[2]);
 919   PRINT_REG(r14, regs[1]);
 920   PRINT_REG(r15, regs[0]);
 921 #undef PRINT_REG
 922   // Print some words near top of staack.
 923   int64_t* rsp = (int64_t*) regs[11];
 924   int64_t* dump_sp = rsp;
 925   for (int col1 = 0; col1 < 8; col1++) {
 926     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 927     os::print_location(tty, *dump_sp++);
 928   }
 929   for (int row = 0; row < 25; row++) {
 930     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 931     for (int col = 0; col < 4; col++) {
 932       tty->print(" 0x%016lx", *dump_sp++);
 933     }
 934     tty->cr();
 935   }
 936   // Print some instructions around pc:
 937   Disassembler::decode((address)pc-64, (address)pc);
 938   tty->print_cr("--------");
 939   Disassembler::decode((address)pc, (address)pc+32);
 940 }
 941 
 942 #endif // _LP64
 943 
 944 // Now versions that are common to 32/64 bit
 945 
 946 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 947   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 948 }
 949 
 950 void MacroAssembler::addptr(Register dst, Register src) {
 951   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 952 }
 953 
 954 void MacroAssembler::addptr(Address dst, Register src) {
 955   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 956 }
 957 
 958 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 959   if (reachable(src)) {
 960     Assembler::addsd(dst, as_Address(src));
 961   } else {
 962     lea(rscratch1, src);
 963     Assembler::addsd(dst, Address(rscratch1, 0));
 964   }
 965 }
 966 
 967 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 968   if (reachable(src)) {
 969     addss(dst, as_Address(src));
 970   } else {
 971     lea(rscratch1, src);
 972     addss(dst, Address(rscratch1, 0));
 973   }
 974 }
 975 
 976 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 977   if (reachable(src)) {
 978     Assembler::addpd(dst, as_Address(src));
 979   } else {
 980     lea(rscratch1, src);
 981     Assembler::addpd(dst, Address(rscratch1, 0));
 982   }
 983 }
 984 
 985 void MacroAssembler::align(int modulus) {
 986   align(modulus, offset());
 987 }
 988 
 989 void MacroAssembler::align(int modulus, int target) {
 990   if (target % modulus != 0) {
 991     nop(modulus - (target % modulus));
 992   }
 993 }
 994 
 995 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 996   // Used in sign-masking with aligned address.
 997   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 998   if (reachable(src)) {
 999     Assembler::andpd(dst, as_Address(src));
1000   } else {
1001     lea(rscratch1, src);
1002     Assembler::andpd(dst, Address(rscratch1, 0));
1003   }
1004 }
1005 
1006 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1007   // Used in sign-masking with aligned address.
1008   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1009   if (reachable(src)) {
1010     Assembler::andps(dst, as_Address(src));
1011   } else {
1012     lea(rscratch1, src);
1013     Assembler::andps(dst, Address(rscratch1, 0));
1014   }
1015 }
1016 
1017 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1018   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1019 }
1020 
1021 void MacroAssembler::atomic_incl(Address counter_addr) {
1022   if (os::is_MP())
1023     lock();
1024   incrementl(counter_addr);
1025 }
1026 
1027 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1028   if (reachable(counter_addr)) {
1029     atomic_incl(as_Address(counter_addr));
1030   } else {
1031     lea(scr, counter_addr);
1032     atomic_incl(Address(scr, 0));
1033   }
1034 }
1035 
1036 #ifdef _LP64
1037 void MacroAssembler::atomic_incq(Address counter_addr) {
1038   if (os::is_MP())
1039     lock();
1040   incrementq(counter_addr);
1041 }
1042 
1043 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1044   if (reachable(counter_addr)) {
1045     atomic_incq(as_Address(counter_addr));
1046   } else {
1047     lea(scr, counter_addr);
1048     atomic_incq(Address(scr, 0));
1049   }
1050 }
1051 #endif
1052 
1053 // Writes to stack successive pages until offset reached to check for
1054 // stack overflow + shadow pages.  This clobbers tmp.
1055 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1056   movptr(tmp, rsp);
1057   // Bang stack for total size given plus shadow page size.
1058   // Bang one page at a time because large size can bang beyond yellow and
1059   // red zones.
1060   Label loop;
1061   bind(loop);
1062   movl(Address(tmp, (-os::vm_page_size())), size );
1063   subptr(tmp, os::vm_page_size());
1064   subl(size, os::vm_page_size());
1065   jcc(Assembler::greater, loop);
1066 
1067   // Bang down shadow pages too.
1068   // At this point, (tmp-0) is the last address touched, so don't
1069   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1070   // was post-decremented.)  Skip this address by starting at i=1, and
1071   // touch a few more pages below.  N.B.  It is important to touch all
1072   // the way down including all pages in the shadow zone.
1073   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1074     // this could be any sized move but this is can be a debugging crumb
1075     // so the bigger the better.
1076     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1077   }
1078 }
1079 
1080 void MacroAssembler::reserved_stack_check() {
1081     // testing if reserved zone needs to be enabled
1082     Label no_reserved_zone_enabling;
1083     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1084     NOT_LP64(get_thread(rsi);)
1085 
1086     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1087     jcc(Assembler::below, no_reserved_zone_enabling);
1088 
1089     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1090     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1091     should_not_reach_here();
1092 
1093     bind(no_reserved_zone_enabling);
1094 }
1095 
1096 int MacroAssembler::biased_locking_enter(Register lock_reg,
1097                                          Register obj_reg,
1098                                          Register swap_reg,
1099                                          Register tmp_reg,
1100                                          bool swap_reg_contains_mark,
1101                                          Label& done,
1102                                          Label* slow_case,
1103                                          BiasedLockingCounters* counters) {
1104   assert(UseBiasedLocking, "why call this otherwise?");
1105   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1106   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1107   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1108   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1109   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1110   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1111 
1112   shenandoah_store_addr_check(obj_reg);
1113 
1114   if (PrintBiasedLockingStatistics && counters == NULL) {
1115     counters = BiasedLocking::counters();
1116   }
1117   // Biased locking
1118   // See whether the lock is currently biased toward our thread and
1119   // whether the epoch is still valid
1120   // Note that the runtime guarantees sufficient alignment of JavaThread
1121   // pointers to allow age to be placed into low bits
1122   // First check to see whether biasing is even enabled for this object
1123   Label cas_label;
1124   int null_check_offset = -1;
1125   if (!swap_reg_contains_mark) {
1126     null_check_offset = offset();
1127     movptr(swap_reg, mark_addr);
1128   }
1129   movptr(tmp_reg, swap_reg);
1130   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1131   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1132   jcc(Assembler::notEqual, cas_label);
1133   // The bias pattern is present in the object's header. Need to check
1134   // whether the bias owner and the epoch are both still current.
1135 #ifndef _LP64
1136   // Note that because there is no current thread register on x86_32 we
1137   // need to store off the mark word we read out of the object to
1138   // avoid reloading it and needing to recheck invariants below. This
1139   // store is unfortunate but it makes the overall code shorter and
1140   // simpler.
1141   movptr(saved_mark_addr, swap_reg);
1142 #endif
1143   if (swap_reg_contains_mark) {
1144     null_check_offset = offset();
1145   }
1146   load_prototype_header(tmp_reg, obj_reg);
1147 #ifdef _LP64
1148   orptr(tmp_reg, r15_thread);
1149   xorptr(tmp_reg, swap_reg);
1150   Register header_reg = tmp_reg;
1151 #else
1152   xorptr(tmp_reg, swap_reg);
1153   get_thread(swap_reg);
1154   xorptr(swap_reg, tmp_reg);
1155   Register header_reg = swap_reg;
1156 #endif
1157   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1158   if (counters != NULL) {
1159     cond_inc32(Assembler::zero,
1160                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1161   }
1162   jcc(Assembler::equal, done);
1163 
1164   Label try_revoke_bias;
1165   Label try_rebias;
1166 
1167   // At this point we know that the header has the bias pattern and
1168   // that we are not the bias owner in the current epoch. We need to
1169   // figure out more details about the state of the header in order to
1170   // know what operations can be legally performed on the object's
1171   // header.
1172 
1173   // If the low three bits in the xor result aren't clear, that means
1174   // the prototype header is no longer biased and we have to revoke
1175   // the bias on this object.
1176   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1177   jccb_if_possible(Assembler::notZero, try_revoke_bias);
1178 
1179   // Biasing is still enabled for this data type. See whether the
1180   // epoch of the current bias is still valid, meaning that the epoch
1181   // bits of the mark word are equal to the epoch bits of the
1182   // prototype header. (Note that the prototype header's epoch bits
1183   // only change at a safepoint.) If not, attempt to rebias the object
1184   // toward the current thread. Note that we must be absolutely sure
1185   // that the current epoch is invalid in order to do this because
1186   // otherwise the manipulations it performs on the mark word are
1187   // illegal.
1188   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1189   jccb_if_possible(Assembler::notZero, try_rebias);
1190 
1191   // The epoch of the current bias is still valid but we know nothing
1192   // about the owner; it might be set or it might be clear. Try to
1193   // acquire the bias of the object using an atomic operation. If this
1194   // fails we will go in to the runtime to revoke the object's bias.
1195   // Note that we first construct the presumed unbiased header so we
1196   // don't accidentally blow away another thread's valid bias.
1197   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1198   andptr(swap_reg,
1199          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1200 #ifdef _LP64
1201   movptr(tmp_reg, swap_reg);
1202   orptr(tmp_reg, r15_thread);
1203 #else
1204   get_thread(tmp_reg);
1205   orptr(tmp_reg, swap_reg);
1206 #endif
1207   if (os::is_MP()) {
1208     lock();
1209   }
1210   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1211   // If the biasing toward our thread failed, this means that
1212   // another thread succeeded in biasing it toward itself and we
1213   // need to revoke that bias. The revocation will occur in the
1214   // interpreter runtime in the slow case.
1215   if (counters != NULL) {
1216     cond_inc32(Assembler::zero,
1217                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1218   }
1219   if (slow_case != NULL) {
1220     jcc(Assembler::notZero, *slow_case);
1221   }
1222   jmp(done);
1223 
1224   bind(try_rebias);
1225   // At this point we know the epoch has expired, meaning that the
1226   // current "bias owner", if any, is actually invalid. Under these
1227   // circumstances _only_, we are allowed to use the current header's
1228   // value as the comparison value when doing the cas to acquire the
1229   // bias in the current epoch. In other words, we allow transfer of
1230   // the bias from one thread to another directly in this situation.
1231   //
1232   // FIXME: due to a lack of registers we currently blow away the age
1233   // bits in this situation. Should attempt to preserve them.
1234   load_prototype_header(tmp_reg, obj_reg);
1235 #ifdef _LP64
1236   orptr(tmp_reg, r15_thread);
1237 #else
1238   get_thread(swap_reg);
1239   orptr(tmp_reg, swap_reg);
1240   movptr(swap_reg, saved_mark_addr);
1241 #endif
1242   if (os::is_MP()) {
1243     lock();
1244   }
1245   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1246   // If the biasing toward our thread failed, then another thread
1247   // succeeded in biasing it toward itself and we need to revoke that
1248   // bias. The revocation will occur in the runtime in the slow case.
1249   if (counters != NULL) {
1250     cond_inc32(Assembler::zero,
1251                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1252   }
1253   if (slow_case != NULL) {
1254     jcc(Assembler::notZero, *slow_case);
1255   }
1256   jmp(done);
1257 
1258   bind(try_revoke_bias);
1259   // The prototype mark in the klass doesn't have the bias bit set any
1260   // more, indicating that objects of this data type are not supposed
1261   // to be biased any more. We are going to try to reset the mark of
1262   // this object to the prototype value and fall through to the
1263   // CAS-based locking scheme. Note that if our CAS fails, it means
1264   // that another thread raced us for the privilege of revoking the
1265   // bias of this particular object, so it's okay to continue in the
1266   // normal locking code.
1267   //
1268   // FIXME: due to a lack of registers we currently blow away the age
1269   // bits in this situation. Should attempt to preserve them.
1270   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1271   load_prototype_header(tmp_reg, obj_reg);
1272   if (os::is_MP()) {
1273     lock();
1274   }
1275   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1276   // Fall through to the normal CAS-based lock, because no matter what
1277   // the result of the above CAS, some thread must have succeeded in
1278   // removing the bias bit from the object's header.
1279   if (counters != NULL) {
1280     cond_inc32(Assembler::zero,
1281                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1282   }
1283 
1284   bind(cas_label);
1285 
1286   return null_check_offset;
1287 }
1288 
1289 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1290   assert(UseBiasedLocking, "why call this otherwise?");
1291 
1292   // Check for biased locking unlock case, which is a no-op
1293   // Note: we do not have to check the thread ID for two reasons.
1294   // First, the interpreter checks for IllegalMonitorStateException at
1295   // a higher level. Second, if the bias was revoked while we held the
1296   // lock, the object could not be rebiased toward another thread, so
1297   // the bias bit would be clear.
1298   shenandoah_store_addr_check(obj_reg); // Access mark word
1299   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1300   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1301   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1302   jcc(Assembler::equal, done);
1303 }
1304 
1305 #ifdef COMPILER2
1306 
1307 #if INCLUDE_RTM_OPT
1308 
1309 // Update rtm_counters based on abort status
1310 // input: abort_status
1311 //        rtm_counters (RTMLockingCounters*)
1312 // flags are killed
1313 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1314 
1315   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1316   if (PrintPreciseRTMLockingStatistics) {
1317     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1318       Label check_abort;
1319       testl(abort_status, (1<<i));
1320       jccb(Assembler::equal, check_abort);
1321       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1322       bind(check_abort);
1323     }
1324   }
1325 }
1326 
1327 // Branch if (random & (count-1) != 0), count is 2^n
1328 // tmp, scr and flags are killed
1329 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1330   assert(tmp == rax, "");
1331   assert(scr == rdx, "");
1332   rdtsc(); // modifies EDX:EAX
1333   andptr(tmp, count-1);
1334   jccb(Assembler::notZero, brLabel);
1335 }
1336 
1337 // Perform abort ratio calculation, set no_rtm bit if high ratio
1338 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1339 // tmpReg, rtm_counters_Reg and flags are killed
1340 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1341                                                  Register rtm_counters_Reg,
1342                                                  RTMLockingCounters* rtm_counters,
1343                                                  Metadata* method_data) {
1344   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1345 
1346   if (RTMLockingCalculationDelay > 0) {
1347     // Delay calculation
1348     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1349     testptr(tmpReg, tmpReg);
1350     jccb(Assembler::equal, L_done);
1351   }
1352   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1353   //   Aborted transactions = abort_count * 100
1354   //   All transactions = total_count *  RTMTotalCountIncrRate
1355   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1356 
1357   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1358   cmpptr(tmpReg, RTMAbortThreshold);
1359   jccb(Assembler::below, L_check_always_rtm2);
1360   imulptr(tmpReg, tmpReg, 100);
1361 
1362   Register scrReg = rtm_counters_Reg;
1363   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1364   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1365   imulptr(scrReg, scrReg, RTMAbortRatio);
1366   cmpptr(tmpReg, scrReg);
1367   jccb(Assembler::below, L_check_always_rtm1);
1368   if (method_data != NULL) {
1369     // set rtm_state to "no rtm" in MDO
1370     mov_metadata(tmpReg, method_data);
1371     if (os::is_MP()) {
1372       lock();
1373     }
1374     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1375   }
1376   jmpb(L_done);
1377   bind(L_check_always_rtm1);
1378   // Reload RTMLockingCounters* address
1379   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1380   bind(L_check_always_rtm2);
1381   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1382   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1383   jccb(Assembler::below, L_done);
1384   if (method_data != NULL) {
1385     // set rtm_state to "always rtm" in MDO
1386     mov_metadata(tmpReg, method_data);
1387     if (os::is_MP()) {
1388       lock();
1389     }
1390     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1391   }
1392   bind(L_done);
1393 }
1394 
1395 // Update counters and perform abort ratio calculation
1396 // input:  abort_status_Reg
1397 // rtm_counters_Reg, flags are killed
1398 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1399                                    Register rtm_counters_Reg,
1400                                    RTMLockingCounters* rtm_counters,
1401                                    Metadata* method_data,
1402                                    bool profile_rtm) {
1403 
1404   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1405   // update rtm counters based on rax value at abort
1406   // reads abort_status_Reg, updates flags
1407   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1408   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1409   if (profile_rtm) {
1410     // Save abort status because abort_status_Reg is used by following code.
1411     if (RTMRetryCount > 0) {
1412       push(abort_status_Reg);
1413     }
1414     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1415     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1416     // restore abort status
1417     if (RTMRetryCount > 0) {
1418       pop(abort_status_Reg);
1419     }
1420   }
1421 }
1422 
1423 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1424 // inputs: retry_count_Reg
1425 //       : abort_status_Reg
1426 // output: retry_count_Reg decremented by 1
1427 // flags are killed
1428 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1429   Label doneRetry;
1430   assert(abort_status_Reg == rax, "");
1431   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1432   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1433   // if reason is in 0x6 and retry count != 0 then retry
1434   andptr(abort_status_Reg, 0x6);
1435   jccb(Assembler::zero, doneRetry);
1436   testl(retry_count_Reg, retry_count_Reg);
1437   jccb(Assembler::zero, doneRetry);
1438   pause();
1439   decrementl(retry_count_Reg);
1440   jmp(retryLabel);
1441   bind(doneRetry);
1442 }
1443 
1444 // Spin and retry if lock is busy,
1445 // inputs: box_Reg (monitor address)
1446 //       : retry_count_Reg
1447 // output: retry_count_Reg decremented by 1
1448 //       : clear z flag if retry count exceeded
1449 // tmp_Reg, scr_Reg, flags are killed
1450 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1451                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1452   Label SpinLoop, SpinExit, doneRetry;
1453   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1454 
1455   testl(retry_count_Reg, retry_count_Reg);
1456   jccb(Assembler::zero, doneRetry);
1457   decrementl(retry_count_Reg);
1458   movptr(scr_Reg, RTMSpinLoopCount);
1459 
1460   bind(SpinLoop);
1461   pause();
1462   decrementl(scr_Reg);
1463   jccb(Assembler::lessEqual, SpinExit);
1464   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1465   testptr(tmp_Reg, tmp_Reg);
1466   jccb(Assembler::notZero, SpinLoop);
1467 
1468   bind(SpinExit);
1469   jmp(retryLabel);
1470   bind(doneRetry);
1471   incrementl(retry_count_Reg); // clear z flag
1472 }
1473 
1474 // Use RTM for normal stack locks
1475 // Input: objReg (object to lock)
1476 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1477                                        Register retry_on_abort_count_Reg,
1478                                        RTMLockingCounters* stack_rtm_counters,
1479                                        Metadata* method_data, bool profile_rtm,
1480                                        Label& DONE_LABEL, Label& IsInflated) {
1481   assert(UseRTMForStackLocks, "why call this otherwise?");
1482   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1483   assert(tmpReg == rax, "");
1484   assert(scrReg == rdx, "");
1485   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1486 
1487   if (RTMRetryCount > 0) {
1488     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1489     bind(L_rtm_retry);
1490   }
1491   shenandoah_store_addr_check(objReg); // Access mark word
1492   movptr(tmpReg, Address(objReg, 0));
1493   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1494   jcc(Assembler::notZero, IsInflated);
1495 
1496   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1497     Label L_noincrement;
1498     if (RTMTotalCountIncrRate > 1) {
1499       // tmpReg, scrReg and flags are killed
1500       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1501     }
1502     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1503     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1504     bind(L_noincrement);
1505   }
1506   xbegin(L_on_abort);
1507   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1508   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1509   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1510   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1511 
1512   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1513   if (UseRTMXendForLockBusy) {
1514     xend();
1515     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1516     jmp(L_decrement_retry);
1517   }
1518   else {
1519     xabort(0);
1520   }
1521   bind(L_on_abort);
1522   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1523     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1524   }
1525   bind(L_decrement_retry);
1526   if (RTMRetryCount > 0) {
1527     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1528     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1529   }
1530 }
1531 
1532 // Use RTM for inflating locks
1533 // inputs: objReg (object to lock)
1534 //         boxReg (on-stack box address (displaced header location) - KILLED)
1535 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1536 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1537                                           Register scrReg, Register retry_on_busy_count_Reg,
1538                                           Register retry_on_abort_count_Reg,
1539                                           RTMLockingCounters* rtm_counters,
1540                                           Metadata* method_data, bool profile_rtm,
1541                                           Label& DONE_LABEL) {
1542   assert(UseRTMLocking, "why call this otherwise?");
1543   assert(tmpReg == rax, "");
1544   assert(scrReg == rdx, "");
1545   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1546   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1547 
1548   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1549   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1550   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1551 
1552   if (RTMRetryCount > 0) {
1553     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1554     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1555     bind(L_rtm_retry);
1556   }
1557   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1558     Label L_noincrement;
1559     if (RTMTotalCountIncrRate > 1) {
1560       // tmpReg, scrReg and flags are killed
1561       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1562     }
1563     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1564     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1565     bind(L_noincrement);
1566   }
1567   xbegin(L_on_abort);
1568   shenandoah_store_addr_check(objReg); // Access mark word
1569   movptr(tmpReg, Address(objReg, 0));
1570   movptr(tmpReg, Address(tmpReg, owner_offset));
1571   testptr(tmpReg, tmpReg);
1572   jcc(Assembler::zero, DONE_LABEL);
1573   if (UseRTMXendForLockBusy) {
1574     xend();
1575     jmp(L_decrement_retry);
1576   }
1577   else {
1578     xabort(0);
1579   }
1580   bind(L_on_abort);
1581   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1582   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1583     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1584   }
1585   if (RTMRetryCount > 0) {
1586     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1587     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1588   }
1589 
1590   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1591   testptr(tmpReg, tmpReg) ;
1592   jccb(Assembler::notZero, L_decrement_retry) ;
1593 
1594   // Appears unlocked - try to swing _owner from null to non-null.
1595   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1596 #ifdef _LP64
1597   Register threadReg = r15_thread;
1598 #else
1599   get_thread(scrReg);
1600   Register threadReg = scrReg;
1601 #endif
1602   if (os::is_MP()) {
1603     lock();
1604   }
1605   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1606 
1607   if (RTMRetryCount > 0) {
1608     // success done else retry
1609     jccb(Assembler::equal, DONE_LABEL) ;
1610     bind(L_decrement_retry);
1611     // Spin and retry if lock is busy.
1612     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1613   }
1614   else {
1615     bind(L_decrement_retry);
1616   }
1617 }
1618 
1619 #endif //  INCLUDE_RTM_OPT
1620 
1621 // Fast_Lock and Fast_Unlock used by C2
1622 
1623 // Because the transitions from emitted code to the runtime
1624 // monitorenter/exit helper stubs are so slow it's critical that
1625 // we inline both the stack-locking fast-path and the inflated fast path.
1626 //
1627 // See also: cmpFastLock and cmpFastUnlock.
1628 //
1629 // What follows is a specialized inline transliteration of the code
1630 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1631 // another option would be to emit TrySlowEnter and TrySlowExit methods
1632 // at startup-time.  These methods would accept arguments as
1633 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1634 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1635 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1636 // In practice, however, the # of lock sites is bounded and is usually small.
1637 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1638 // if the processor uses simple bimodal branch predictors keyed by EIP
1639 // Since the helper routines would be called from multiple synchronization
1640 // sites.
1641 //
1642 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1643 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1644 // to those specialized methods.  That'd give us a mostly platform-independent
1645 // implementation that the JITs could optimize and inline at their pleasure.
1646 // Done correctly, the only time we'd need to cross to native could would be
1647 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1648 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1649 // (b) explicit barriers or fence operations.
1650 //
1651 // TODO:
1652 //
1653 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1654 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1655 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1656 //    the lock operators would typically be faster than reifying Self.
1657 //
1658 // *  Ideally I'd define the primitives as:
1659 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1660 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1661 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1662 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1663 //    Furthermore the register assignments are overconstrained, possibly resulting in
1664 //    sub-optimal code near the synchronization site.
1665 //
1666 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1667 //    Alternately, use a better sp-proximity test.
1668 //
1669 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1670 //    Either one is sufficient to uniquely identify a thread.
1671 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1672 //
1673 // *  Intrinsify notify() and notifyAll() for the common cases where the
1674 //    object is locked by the calling thread but the waitlist is empty.
1675 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1676 //
1677 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1678 //    But beware of excessive branch density on AMD Opterons.
1679 //
1680 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1681 //    or failure of the fast-path.  If the fast-path fails then we pass
1682 //    control to the slow-path, typically in C.  In Fast_Lock and
1683 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1684 //    will emit a conditional branch immediately after the node.
1685 //    So we have branches to branches and lots of ICC.ZF games.
1686 //    Instead, it might be better to have C2 pass a "FailureLabel"
1687 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1688 //    will drop through the node.  ICC.ZF is undefined at exit.
1689 //    In the case of failure, the node will branch directly to the
1690 //    FailureLabel
1691 
1692 
1693 // obj: object to lock
1694 // box: on-stack box address (displaced header location) - KILLED
1695 // rax,: tmp -- KILLED
1696 // scr: tmp -- KILLED
1697 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1698                                Register scrReg, Register cx1Reg, Register cx2Reg,
1699                                BiasedLockingCounters* counters,
1700                                RTMLockingCounters* rtm_counters,
1701                                RTMLockingCounters* stack_rtm_counters,
1702                                Metadata* method_data,
1703                                bool use_rtm, bool profile_rtm) {
1704   // Ensure the register assignments are disjoint
1705   assert(tmpReg == rax, "");
1706 
1707   if (use_rtm) {
1708     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1709   } else {
1710     assert(cx1Reg == noreg, "");
1711     assert(cx2Reg == noreg, "");
1712     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1713   }
1714 
1715   shenandoah_store_addr_check(objReg); // Access mark word
1716 
1717   if (counters != NULL) {
1718     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1719   }
1720   if (EmitSync & 1) {
1721       // set box->dhw = markOopDesc::unused_mark()
1722       // Force all sync thru slow-path: slow_enter() and slow_exit()
1723       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1724       cmpptr (rsp, (int32_t)NULL_WORD);
1725   } else {
1726     // Possible cases that we'll encounter in fast_lock
1727     // ------------------------------------------------
1728     // * Inflated
1729     //    -- unlocked
1730     //    -- Locked
1731     //       = by self
1732     //       = by other
1733     // * biased
1734     //    -- by Self
1735     //    -- by other
1736     // * neutral
1737     // * stack-locked
1738     //    -- by self
1739     //       = sp-proximity test hits
1740     //       = sp-proximity test generates false-negative
1741     //    -- by other
1742     //
1743 
1744     Label IsInflated, DONE_LABEL;
1745 
1746     // it's stack-locked, biased or neutral
1747     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1748     // order to reduce the number of conditional branches in the most common cases.
1749     // Beware -- there's a subtle invariant that fetch of the markword
1750     // at [FETCH], below, will never observe a biased encoding (*101b).
1751     // If this invariant is not held we risk exclusion (safety) failure.
1752     if (UseBiasedLocking && !UseOptoBiasInlining) {
1753       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1754     }
1755 
1756 #if INCLUDE_RTM_OPT
1757     if (UseRTMForStackLocks && use_rtm) {
1758       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1759                         stack_rtm_counters, method_data, profile_rtm,
1760                         DONE_LABEL, IsInflated);
1761     }
1762 #endif // INCLUDE_RTM_OPT
1763 
1764     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1765     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1766     jccb_if_possible(Assembler::notZero, IsInflated);
1767 
1768     // Attempt stack-locking ...
1769     orptr (tmpReg, markOopDesc::unlocked_value);
1770     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1771     if (os::is_MP()) {
1772       lock();
1773     }
1774     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1775     if (counters != NULL) {
1776       cond_inc32(Assembler::equal,
1777                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1778     }
1779     jcc(Assembler::equal, DONE_LABEL);           // Success
1780 
1781     // Recursive locking.
1782     // The object is stack-locked: markword contains stack pointer to BasicLock.
1783     // Locked by current thread if difference with current SP is less than one page.
1784     subptr(tmpReg, rsp);
1785     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1786     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1787     movptr(Address(boxReg, 0), tmpReg);
1788     if (counters != NULL) {
1789       cond_inc32(Assembler::equal,
1790                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1791     }
1792     jmp(DONE_LABEL);
1793 
1794     bind(IsInflated);
1795     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1796 
1797 #if INCLUDE_RTM_OPT
1798     // Use the same RTM locking code in 32- and 64-bit VM.
1799     if (use_rtm) {
1800       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1801                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1802     } else {
1803 #endif // INCLUDE_RTM_OPT
1804 
1805 #ifndef _LP64
1806     // The object is inflated.
1807 
1808     // boxReg refers to the on-stack BasicLock in the current frame.
1809     // We'd like to write:
1810     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1811     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1812     // additional latency as we have another ST in the store buffer that must drain.
1813 
1814     if (EmitSync & 8192) {
1815        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1816        get_thread (scrReg);
1817        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1818        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1819        if (os::is_MP()) {
1820          lock();
1821        }
1822        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1823     } else
1824     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1825        // register juggle because we need tmpReg for cmpxchgptr below
1826        movptr(scrReg, boxReg);
1827        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1828 
1829        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1830        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1831           // prefetchw [eax + Offset(_owner)-2]
1832           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1833        }
1834 
1835        if ((EmitSync & 64) == 0) {
1836          // Optimistic form: consider XORL tmpReg,tmpReg
1837          movptr(tmpReg, NULL_WORD);
1838        } else {
1839          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1840          // Test-And-CAS instead of CAS
1841          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1842          testptr(tmpReg, tmpReg);                   // Locked ?
1843          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1844        }
1845 
1846        // Appears unlocked - try to swing _owner from null to non-null.
1847        // Ideally, I'd manifest "Self" with get_thread and then attempt
1848        // to CAS the register containing Self into m->Owner.
1849        // But we don't have enough registers, so instead we can either try to CAS
1850        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1851        // we later store "Self" into m->Owner.  Transiently storing a stack address
1852        // (rsp or the address of the box) into  m->owner is harmless.
1853        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1854        if (os::is_MP()) {
1855          lock();
1856        }
1857        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1858        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1859        // If we weren't able to swing _owner from NULL to the BasicLock
1860        // then take the slow path.
1861        jccb_if_possible(Assembler::notZero, DONE_LABEL);
1862        // update _owner from BasicLock to thread
1863        get_thread (scrReg);                    // beware: clobbers ICCs
1864        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1865        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1866 
1867        // If the CAS fails we can either retry or pass control to the slow-path.
1868        // We use the latter tactic.
1869        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1870        // If the CAS was successful ...
1871        //   Self has acquired the lock
1872        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1873        // Intentional fall-through into DONE_LABEL ...
1874     } else {
1875        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1876        movptr(boxReg, tmpReg);
1877 
1878        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1879        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1880           // prefetchw [eax + Offset(_owner)-2]
1881           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1882        }
1883 
1884        if ((EmitSync & 64) == 0) {
1885          // Optimistic form
1886          xorptr  (tmpReg, tmpReg);
1887        } else {
1888          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1889          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1890          testptr(tmpReg, tmpReg);                   // Locked ?
1891          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1892        }
1893 
1894        // Appears unlocked - try to swing _owner from null to non-null.
1895        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1896        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1897        get_thread (scrReg);
1898        if (os::is_MP()) {
1899          lock();
1900        }
1901        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1902 
1903        // If the CAS fails we can either retry or pass control to the slow-path.
1904        // We use the latter tactic.
1905        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1906        // If the CAS was successful ...
1907        //   Self has acquired the lock
1908        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1909        // Intentional fall-through into DONE_LABEL ...
1910     }
1911 #else // _LP64
1912     // It's inflated
1913     movq(scrReg, tmpReg);
1914     xorq(tmpReg, tmpReg);
1915 
1916     if (os::is_MP()) {
1917       lock();
1918     }
1919     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1920     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1921     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1922     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1923     // Intentional fall-through into DONE_LABEL ...
1924     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1925 #endif // _LP64
1926 #if INCLUDE_RTM_OPT
1927     } // use_rtm()
1928 #endif
1929     // DONE_LABEL is a hot target - we'd really like to place it at the
1930     // start of cache line by padding with NOPs.
1931     // See the AMD and Intel software optimization manuals for the
1932     // most efficient "long" NOP encodings.
1933     // Unfortunately none of our alignment mechanisms suffice.
1934     bind(DONE_LABEL);
1935 
1936     // At DONE_LABEL the icc ZFlag is set as follows ...
1937     // Fast_Unlock uses the same protocol.
1938     // ZFlag == 1 -> Success
1939     // ZFlag == 0 -> Failure - force control through the slow-path
1940   }
1941 }
1942 
1943 // obj: object to unlock
1944 // box: box address (displaced header location), killed.  Must be EAX.
1945 // tmp: killed, cannot be obj nor box.
1946 //
1947 // Some commentary on balanced locking:
1948 //
1949 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1950 // Methods that don't have provably balanced locking are forced to run in the
1951 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1952 // The interpreter provides two properties:
1953 // I1:  At return-time the interpreter automatically and quietly unlocks any
1954 //      objects acquired the current activation (frame).  Recall that the
1955 //      interpreter maintains an on-stack list of locks currently held by
1956 //      a frame.
1957 // I2:  If a method attempts to unlock an object that is not held by the
1958 //      the frame the interpreter throws IMSX.
1959 //
1960 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1961 // B() doesn't have provably balanced locking so it runs in the interpreter.
1962 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1963 // is still locked by A().
1964 //
1965 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1966 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1967 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1968 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1969 // Arguably given that the spec legislates the JNI case as undefined our implementation
1970 // could reasonably *avoid* checking owner in Fast_Unlock().
1971 // In the interest of performance we elide m->Owner==Self check in unlock.
1972 // A perfectly viable alternative is to elide the owner check except when
1973 // Xcheck:jni is enabled.
1974 
1975 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1976   assert(boxReg == rax, "");
1977   assert_different_registers(objReg, boxReg, tmpReg);
1978 
1979   shenandoah_store_addr_check(objReg); // Access mark word
1980 
1981   if (EmitSync & 4) {
1982     // Disable - inhibit all inlining.  Force control through the slow-path
1983     cmpptr (rsp, 0);
1984   } else {
1985     Label DONE_LABEL, Stacked, CheckSucc;
1986 
1987     // Critically, the biased locking test must have precedence over
1988     // and appear before the (box->dhw == 0) recursive stack-lock test.
1989     if (UseBiasedLocking && !UseOptoBiasInlining) {
1990        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1991     }
1992 
1993 #if INCLUDE_RTM_OPT
1994     if (UseRTMForStackLocks && use_rtm) {
1995       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1996       Label L_regular_unlock;
1997       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1998       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1999       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
2000       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2001       xend();                                       // otherwise end...
2002       jmp(DONE_LABEL);                              // ... and we're done
2003       bind(L_regular_unlock);
2004     }
2005 #endif
2006 
2007     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2008     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2009     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
2010     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2011     jccb  (Assembler::zero, Stacked);
2012 
2013     // It's inflated.
2014 #if INCLUDE_RTM_OPT
2015     if (use_rtm) {
2016       Label L_regular_inflated_unlock;
2017       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2018       movptr(boxReg, Address(tmpReg, owner_offset));
2019       testptr(boxReg, boxReg);
2020       jccb(Assembler::notZero, L_regular_inflated_unlock);
2021       xend();
2022       jmpb_if_possible(DONE_LABEL);
2023       bind(L_regular_inflated_unlock);
2024     }
2025 #endif
2026 
2027     // Despite our balanced locking property we still check that m->_owner == Self
2028     // as java routines or native JNI code called by this thread might
2029     // have released the lock.
2030     // Refer to the comments in synchronizer.cpp for how we might encode extra
2031     // state in _succ so we can avoid fetching EntryList|cxq.
2032     //
2033     // I'd like to add more cases in fast_lock() and fast_unlock() --
2034     // such as recursive enter and exit -- but we have to be wary of
2035     // I$ bloat, T$ effects and BP$ effects.
2036     //
2037     // If there's no contention try a 1-0 exit.  That is, exit without
2038     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2039     // we detect and recover from the race that the 1-0 exit admits.
2040     //
2041     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2042     // before it STs null into _owner, releasing the lock.  Updates
2043     // to data protected by the critical section must be visible before
2044     // we drop the lock (and thus before any other thread could acquire
2045     // the lock and observe the fields protected by the lock).
2046     // IA32's memory-model is SPO, so STs are ordered with respect to
2047     // each other and there's no need for an explicit barrier (fence).
2048     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2049 #ifndef _LP64
2050     get_thread (boxReg);
2051     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2052       // prefetchw [ebx + Offset(_owner)-2]
2053       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2054     }
2055 
2056     // Note that we could employ various encoding schemes to reduce
2057     // the number of loads below (currently 4) to just 2 or 3.
2058     // Refer to the comments in synchronizer.cpp.
2059     // In practice the chain of fetches doesn't seem to impact performance, however.
2060     xorptr(boxReg, boxReg);
2061     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2062        // Attempt to reduce branch density - AMD's branch predictor.
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2064        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2065        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2066        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2067        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2068        jmpb_if_possible(DONE_LABEL);
2069     } else {
2070        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2071        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2072        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2073        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2074        jccb  (Assembler::notZero, CheckSucc);
2075        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2076        jmpb_if_possible(DONE_LABEL);
2077     }
2078 
2079     // The Following code fragment (EmitSync & 65536) improves the performance of
2080     // contended applications and contended synchronization microbenchmarks.
2081     // Unfortunately the emission of the code - even though not executed - causes regressions
2082     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2083     // with an equal number of never-executed NOPs results in the same regression.
2084     // We leave it off by default.
2085 
2086     if ((EmitSync & 65536) != 0) {
2087        Label LSuccess, LGoSlowPath ;
2088 
2089        bind  (CheckSucc);
2090 
2091        // Optional pre-test ... it's safe to elide this
2092        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2093        jccb(Assembler::zero, LGoSlowPath);
2094 
2095        // We have a classic Dekker-style idiom:
2096        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2097        // There are a number of ways to implement the barrier:
2098        // (1) lock:andl &m->_owner, 0
2099        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2100        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2101        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2102        // (2) If supported, an explicit MFENCE is appealing.
2103        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2104        //     particularly if the write-buffer is full as might be the case if
2105        //     if stores closely precede the fence or fence-equivalent instruction.
2106        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2107        //     as the situation has changed with Nehalem and Shanghai.
2108        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2109        //     The $lines underlying the top-of-stack should be in M-state.
2110        //     The locked add instruction is serializing, of course.
2111        // (4) Use xchg, which is serializing
2112        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2113        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2114        //     The integer condition codes will tell us if succ was 0.
2115        //     Since _succ and _owner should reside in the same $line and
2116        //     we just stored into _owner, it's likely that the $line
2117        //     remains in M-state for the lock:orl.
2118        //
2119        // We currently use (3), although it's likely that switching to (2)
2120        // is correct for the future.
2121 
2122        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2123        if (os::is_MP()) {
2124          lock(); addptr(Address(rsp, 0), 0);
2125        }
2126        // Ratify _succ remains non-null
2127        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2128        jccb  (Assembler::notZero, LSuccess);
2129 
2130        xorptr(boxReg, boxReg);                  // box is really EAX
2131        if (os::is_MP()) { lock(); }
2132        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2133        // There's no successor so we tried to regrab the lock with the
2134        // placeholder value. If that didn't work, then another thread
2135        // grabbed the lock so we're done (and exit was a success).
2136        jccb  (Assembler::notEqual, LSuccess);
2137        // Since we're low on registers we installed rsp as a placeholding in _owner.
2138        // Now install Self over rsp.  This is safe as we're transitioning from
2139        // non-null to non=null
2140        get_thread (boxReg);
2141        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2142        // Intentional fall-through into LGoSlowPath ...
2143 
2144        bind  (LGoSlowPath);
2145        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2146        jmpb_if_possible(DONE_LABEL);
2147 
2148        bind  (LSuccess);
2149        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2150        jmpb_if_possible(DONE_LABEL);
2151     }
2152 
2153     bind (Stacked);
2154     // It's not inflated and it's not recursively stack-locked and it's not biased.
2155     // It must be stack-locked.
2156     // Try to reset the header to displaced header.
2157     // The "box" value on the stack is stable, so we can reload
2158     // and be assured we observe the same value as above.
2159     movptr(tmpReg, Address(boxReg, 0));
2160     if (os::is_MP()) {
2161       lock();
2162     }
2163     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2164     // Intention fall-thru into DONE_LABEL
2165 
2166     // DONE_LABEL is a hot target - we'd really like to place it at the
2167     // start of cache line by padding with NOPs.
2168     // See the AMD and Intel software optimization manuals for the
2169     // most efficient "long" NOP encodings.
2170     // Unfortunately none of our alignment mechanisms suffice.
2171     if ((EmitSync & 65536) == 0) {
2172        bind (CheckSucc);
2173     }
2174 #else // _LP64
2175     // It's inflated
2176     if (EmitSync & 1024) {
2177       // Emit code to check that _owner == Self
2178       // We could fold the _owner test into subsequent code more efficiently
2179       // than using a stand-alone check, but since _owner checking is off by
2180       // default we don't bother. We also might consider predicating the
2181       // _owner==Self check on Xcheck:jni or running on a debug build.
2182       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2183       xorptr(boxReg, r15_thread);
2184     } else {
2185       xorptr(boxReg, boxReg);
2186     }
2187     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2188     jccb_if_possible(Assembler::notZero, DONE_LABEL);
2189     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2190     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2191     jccb  (Assembler::notZero, CheckSucc);
2192     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2193     jmpb_if_possible(DONE_LABEL);
2194 
2195     if ((EmitSync & 65536) == 0) {
2196       // Try to avoid passing control into the slow_path ...
2197       Label LSuccess, LGoSlowPath ;
2198       bind  (CheckSucc);
2199 
2200       // The following optional optimization can be elided if necessary
2201       // Effectively: if (succ == null) goto SlowPath
2202       // The code reduces the window for a race, however,
2203       // and thus benefits performance.
2204       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2205       jccb  (Assembler::zero, LGoSlowPath);
2206 
2207       xorptr(boxReg, boxReg);
2208       if ((EmitSync & 16) && os::is_MP()) {
2209         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2210       } else {
2211         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2212         if (os::is_MP()) {
2213           // Memory barrier/fence
2214           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2215           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2216           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2217           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2218           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2219           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2220           lock(); addl(Address(rsp, 0), 0);
2221         }
2222       }
2223       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2224       jccb  (Assembler::notZero, LSuccess);
2225 
2226       // Rare inopportune interleaving - race.
2227       // The successor vanished in the small window above.
2228       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2229       // We need to ensure progress and succession.
2230       // Try to reacquire the lock.
2231       // If that fails then the new owner is responsible for succession and this
2232       // thread needs to take no further action and can exit via the fast path (success).
2233       // If the re-acquire succeeds then pass control into the slow path.
2234       // As implemented, this latter mode is horrible because we generated more
2235       // coherence traffic on the lock *and* artifically extended the critical section
2236       // length while by virtue of passing control into the slow path.
2237 
2238       // box is really RAX -- the following CMPXCHG depends on that binding
2239       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2240       if (os::is_MP()) { lock(); }
2241       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2242       // There's no successor so we tried to regrab the lock.
2243       // If that didn't work, then another thread grabbed the
2244       // lock so we're done (and exit was a success).
2245       jccb  (Assembler::notEqual, LSuccess);
2246       // Intentional fall-through into slow-path
2247 
2248       bind  (LGoSlowPath);
2249       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2250       jmpb_if_possible(DONE_LABEL);
2251 
2252       bind  (LSuccess);
2253       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2254       jmpb_if_possible  (DONE_LABEL);
2255     }
2256 
2257     bind  (Stacked);
2258     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2259     if (os::is_MP()) { lock(); }
2260     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2261 
2262     if (EmitSync & 65536) {
2263        bind (CheckSucc);
2264     }
2265 #endif
2266     bind(DONE_LABEL);
2267   }
2268 }
2269 #endif // COMPILER2
2270 
2271 void MacroAssembler::c2bool(Register x) {
2272   // implements x == 0 ? 0 : 1
2273   // note: must only look at least-significant byte of x
2274   //       since C-style booleans are stored in one byte
2275   //       only! (was bug)
2276   andl(x, 0xFF);
2277   setb(Assembler::notZero, x);
2278 }
2279 
2280 // Wouldn't need if AddressLiteral version had new name
2281 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2282   Assembler::call(L, rtype);
2283 }
2284 
2285 void MacroAssembler::call(Register entry) {
2286   Assembler::call(entry);
2287 }
2288 
2289 void MacroAssembler::call(AddressLiteral entry) {
2290   if (reachable(entry)) {
2291     Assembler::call_literal(entry.target(), entry.rspec());
2292   } else {
2293     lea(rscratch1, entry);
2294     Assembler::call(rscratch1);
2295   }
2296 }
2297 
2298 void MacroAssembler::ic_call(address entry, jint method_index) {
2299   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2300   movptr(rax, (intptr_t)Universe::non_oop_word());
2301   call(AddressLiteral(entry, rh));
2302 }
2303 
2304 // Implementation of call_VM versions
2305 
2306 void MacroAssembler::call_VM(Register oop_result,
2307                              address entry_point,
2308                              bool check_exceptions) {
2309   Label C, E;
2310   call(C, relocInfo::none);
2311   jmp(E);
2312 
2313   bind(C);
2314   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2315   ret(0);
2316 
2317   bind(E);
2318 }
2319 
2320 void MacroAssembler::call_VM(Register oop_result,
2321                              address entry_point,
2322                              Register arg_1,
2323                              bool check_exceptions) {
2324   Label C, E;
2325   call(C, relocInfo::none);
2326   jmp(E);
2327 
2328   bind(C);
2329   pass_arg1(this, arg_1);
2330   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2331   ret(0);
2332 
2333   bind(E);
2334 }
2335 
2336 void MacroAssembler::call_VM(Register oop_result,
2337                              address entry_point,
2338                              Register arg_1,
2339                              Register arg_2,
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_rarg2, "smashed arg"));
2348 
2349   pass_arg2(this, arg_2);
2350   pass_arg1(this, arg_1);
2351   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2352   ret(0);
2353 
2354   bind(E);
2355 }
2356 
2357 void MacroAssembler::call_VM(Register oop_result,
2358                              address entry_point,
2359                              Register arg_1,
2360                              Register arg_2,
2361                              Register arg_3,
2362                              bool check_exceptions) {
2363   Label C, E;
2364   call(C, relocInfo::none);
2365   jmp(E);
2366 
2367   bind(C);
2368 
2369   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2370   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2371   pass_arg3(this, arg_3);
2372 
2373   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2374   pass_arg2(this, arg_2);
2375 
2376   pass_arg1(this, arg_1);
2377   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2378   ret(0);
2379 
2380   bind(E);
2381 }
2382 
2383 void MacroAssembler::call_VM(Register oop_result,
2384                              Register last_java_sp,
2385                              address entry_point,
2386                              int number_of_arguments,
2387                              bool check_exceptions) {
2388   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2389   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, 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                              bool check_exceptions) {
2397   pass_arg1(this, arg_1);
2398   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2399 }
2400 
2401 void MacroAssembler::call_VM(Register oop_result,
2402                              Register last_java_sp,
2403                              address entry_point,
2404                              Register arg_1,
2405                              Register arg_2,
2406                              bool check_exceptions) {
2407 
2408   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2409   pass_arg2(this, arg_2);
2410   pass_arg1(this, arg_1);
2411   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2412 }
2413 
2414 void MacroAssembler::call_VM(Register oop_result,
2415                              Register last_java_sp,
2416                              address entry_point,
2417                              Register arg_1,
2418                              Register arg_2,
2419                              Register arg_3,
2420                              bool check_exceptions) {
2421   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2422   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2423   pass_arg3(this, arg_3);
2424   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2425   pass_arg2(this, arg_2);
2426   pass_arg1(this, arg_1);
2427   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2428 }
2429 
2430 void MacroAssembler::super_call_VM(Register oop_result,
2431                                    Register last_java_sp,
2432                                    address entry_point,
2433                                    int number_of_arguments,
2434                                    bool check_exceptions) {
2435   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2436   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, 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                                    bool check_exceptions) {
2444   pass_arg1(this, arg_1);
2445   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2446 }
2447 
2448 void MacroAssembler::super_call_VM(Register oop_result,
2449                                    Register last_java_sp,
2450                                    address entry_point,
2451                                    Register arg_1,
2452                                    Register arg_2,
2453                                    bool check_exceptions) {
2454 
2455   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2456   pass_arg2(this, arg_2);
2457   pass_arg1(this, arg_1);
2458   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2459 }
2460 
2461 void MacroAssembler::super_call_VM(Register oop_result,
2462                                    Register last_java_sp,
2463                                    address entry_point,
2464                                    Register arg_1,
2465                                    Register arg_2,
2466                                    Register arg_3,
2467                                    bool check_exceptions) {
2468   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2469   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2470   pass_arg3(this, arg_3);
2471   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2472   pass_arg2(this, arg_2);
2473   pass_arg1(this, arg_1);
2474   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2475 }
2476 
2477 void MacroAssembler::call_VM_base(Register oop_result,
2478                                   Register java_thread,
2479                                   Register last_java_sp,
2480                                   address  entry_point,
2481                                   int      number_of_arguments,
2482                                   bool     check_exceptions) {
2483   // determine java_thread register
2484   if (!java_thread->is_valid()) {
2485 #ifdef _LP64
2486     java_thread = r15_thread;
2487 #else
2488     java_thread = rdi;
2489     get_thread(java_thread);
2490 #endif // LP64
2491   }
2492   // determine last_java_sp register
2493   if (!last_java_sp->is_valid()) {
2494     last_java_sp = rsp;
2495   }
2496   // debugging support
2497   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2498   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2499 #ifdef ASSERT
2500   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2501   // r12 is the heapbase.
2502   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2503 #endif // ASSERT
2504 
2505   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2506   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2507 
2508   // push java thread (becomes first argument of C function)
2509 
2510   NOT_LP64(push(java_thread); number_of_arguments++);
2511   LP64_ONLY(mov(c_rarg0, r15_thread));
2512 
2513   // set last Java frame before call
2514   assert(last_java_sp != rbp, "can't use ebp/rbp");
2515 
2516   // Only interpreter should have to set fp
2517   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2518 
2519   // do the call, remove parameters
2520   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2521 
2522   // restore the thread (cannot use the pushed argument since arguments
2523   // may be overwritten by C code generated by an optimizing compiler);
2524   // however can use the register value directly if it is callee saved.
2525   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2526     // rdi & rsi (also r15) are callee saved -> nothing to do
2527 #ifdef ASSERT
2528     guarantee(java_thread != rax, "change this code");
2529     push(rax);
2530     { Label L;
2531       get_thread(rax);
2532       cmpptr(java_thread, rax);
2533       jcc(Assembler::equal, L);
2534       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2535       bind(L);
2536     }
2537     pop(rax);
2538 #endif
2539   } else {
2540     get_thread(java_thread);
2541   }
2542   // reset last Java frame
2543   // Only interpreter should have to clear fp
2544   reset_last_Java_frame(java_thread, true);
2545 
2546    // C++ interp handles this in the interpreter
2547   check_and_handle_popframe(java_thread);
2548   check_and_handle_earlyret(java_thread);
2549 
2550   if (check_exceptions) {
2551     // check for pending exceptions (java_thread is set upon return)
2552     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2553 #ifndef _LP64
2554     jump_cc(Assembler::notEqual,
2555             RuntimeAddress(StubRoutines::forward_exception_entry()));
2556 #else
2557     // This used to conditionally jump to forward_exception however it is
2558     // possible if we relocate that the branch will not reach. So we must jump
2559     // around so we can always reach
2560 
2561     Label ok;
2562     jcc(Assembler::equal, ok);
2563     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2564     bind(ok);
2565 #endif // LP64
2566   }
2567 
2568   // get oop result if there is one and reset the value in the thread
2569   if (oop_result->is_valid()) {
2570     get_vm_result(oop_result, java_thread);
2571   }
2572 }
2573 
2574 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2575 
2576   // Calculate the value for last_Java_sp
2577   // somewhat subtle. call_VM does an intermediate call
2578   // which places a return address on the stack just under the
2579   // stack pointer as the user finsihed with it. This allows
2580   // use to retrieve last_Java_pc from last_Java_sp[-1].
2581   // On 32bit we then have to push additional args on the stack to accomplish
2582   // the actual requested call. On 64bit call_VM only can use register args
2583   // so the only extra space is the return address that call_VM created.
2584   // This hopefully explains the calculations here.
2585 
2586 #ifdef _LP64
2587   // We've pushed one address, correct last_Java_sp
2588   lea(rax, Address(rsp, wordSize));
2589 #else
2590   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2591 #endif // LP64
2592 
2593   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2594 
2595 }
2596 
2597 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2598 void MacroAssembler::call_VM_leaf0(address entry_point) {
2599   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2600 }
2601 
2602 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2603   call_VM_leaf_base(entry_point, number_of_arguments);
2604 }
2605 
2606 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2607   pass_arg0(this, arg_0);
2608   call_VM_leaf(entry_point, 1);
2609 }
2610 
2611 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2612 
2613   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2614   pass_arg1(this, arg_1);
2615   pass_arg0(this, arg_0);
2616   call_VM_leaf(entry_point, 2);
2617 }
2618 
2619 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2620   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2621   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2622   pass_arg2(this, arg_2);
2623   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2624   pass_arg1(this, arg_1);
2625   pass_arg0(this, arg_0);
2626   call_VM_leaf(entry_point, 3);
2627 }
2628 
2629 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2630   pass_arg0(this, arg_0);
2631   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2632 }
2633 
2634 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2635 
2636   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2637   pass_arg1(this, arg_1);
2638   pass_arg0(this, arg_0);
2639   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2640 }
2641 
2642 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2643   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2644   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2645   pass_arg2(this, arg_2);
2646   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2647   pass_arg1(this, arg_1);
2648   pass_arg0(this, arg_0);
2649   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2650 }
2651 
2652 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2653   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2654   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2655   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2656   pass_arg3(this, arg_3);
2657   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2658   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2659   pass_arg2(this, arg_2);
2660   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2661   pass_arg1(this, arg_1);
2662   pass_arg0(this, arg_0);
2663   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2664 }
2665 
2666 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2667   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2668   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2669   verify_oop(oop_result, "broken oop in call_VM_base");
2670 }
2671 
2672 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2673   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2674   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2675 }
2676 
2677 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2678 }
2679 
2680 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2681 }
2682 
2683 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2684   if (reachable(src1)) {
2685     cmpl(as_Address(src1), imm);
2686   } else {
2687     lea(rscratch1, src1);
2688     cmpl(Address(rscratch1, 0), imm);
2689   }
2690 }
2691 
2692 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2693   assert(!src2.is_lval(), "use cmpptr");
2694   if (reachable(src2)) {
2695     cmpl(src1, as_Address(src2));
2696   } else {
2697     lea(rscratch1, src2);
2698     cmpl(src1, Address(rscratch1, 0));
2699   }
2700 }
2701 
2702 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2703   Assembler::cmpl(src1, imm);
2704 }
2705 
2706 void MacroAssembler::cmp32(Register src1, Address src2) {
2707   Assembler::cmpl(src1, src2);
2708 }
2709 
2710 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2711   ucomisd(opr1, opr2);
2712 
2713   Label L;
2714   if (unordered_is_less) {
2715     movl(dst, -1);
2716     jcc(Assembler::parity, L);
2717     jcc(Assembler::below , L);
2718     movl(dst, 0);
2719     jcc(Assembler::equal , L);
2720     increment(dst);
2721   } else { // unordered is greater
2722     movl(dst, 1);
2723     jcc(Assembler::parity, L);
2724     jcc(Assembler::above , L);
2725     movl(dst, 0);
2726     jcc(Assembler::equal , L);
2727     decrementl(dst);
2728   }
2729   bind(L);
2730 }
2731 
2732 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2733   ucomiss(opr1, opr2);
2734 
2735   Label L;
2736   if (unordered_is_less) {
2737     movl(dst, -1);
2738     jcc(Assembler::parity, L);
2739     jcc(Assembler::below , L);
2740     movl(dst, 0);
2741     jcc(Assembler::equal , L);
2742     increment(dst);
2743   } else { // unordered is greater
2744     movl(dst, 1);
2745     jcc(Assembler::parity, L);
2746     jcc(Assembler::above , L);
2747     movl(dst, 0);
2748     jcc(Assembler::equal , L);
2749     decrementl(dst);
2750   }
2751   bind(L);
2752 }
2753 
2754 
2755 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2756   if (reachable(src1)) {
2757     cmpb(as_Address(src1), imm);
2758   } else {
2759     lea(rscratch1, src1);
2760     cmpb(Address(rscratch1, 0), imm);
2761   }
2762 }
2763 
2764 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2765 #ifdef _LP64
2766   if (src2.is_lval()) {
2767     movptr(rscratch1, src2);
2768     Assembler::cmpq(src1, rscratch1);
2769   } else if (reachable(src2)) {
2770     cmpq(src1, as_Address(src2));
2771   } else {
2772     lea(rscratch1, src2);
2773     Assembler::cmpq(src1, Address(rscratch1, 0));
2774   }
2775 #else
2776   if (src2.is_lval()) {
2777     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2778   } else {
2779     cmpl(src1, as_Address(src2));
2780   }
2781 #endif // _LP64
2782 }
2783 
2784 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2785   assert(src2.is_lval(), "not a mem-mem compare");
2786 #ifdef _LP64
2787   // moves src2's literal address
2788   movptr(rscratch1, src2);
2789   Assembler::cmpq(src1, rscratch1);
2790 #else
2791   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2792 #endif // _LP64
2793 }
2794 
2795 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2796   if (reachable(adr)) {
2797     if (os::is_MP())
2798       lock();
2799     cmpxchgptr(reg, as_Address(adr));
2800   } else {
2801     lea(rscratch1, adr);
2802     if (os::is_MP())
2803       lock();
2804     cmpxchgptr(reg, Address(rscratch1, 0));
2805   }
2806 }
2807 
2808 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2809   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2810 }
2811 
2812 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2813   if (reachable(src)) {
2814     Assembler::comisd(dst, as_Address(src));
2815   } else {
2816     lea(rscratch1, src);
2817     Assembler::comisd(dst, Address(rscratch1, 0));
2818   }
2819 }
2820 
2821 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2822   if (reachable(src)) {
2823     Assembler::comiss(dst, as_Address(src));
2824   } else {
2825     lea(rscratch1, src);
2826     Assembler::comiss(dst, Address(rscratch1, 0));
2827   }
2828 }
2829 
2830 
2831 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2832   Condition negated_cond = negate_condition(cond);
2833   Label L;
2834   jcc(negated_cond, L);
2835   pushf(); // Preserve flags
2836   atomic_incl(counter_addr);
2837   popf();
2838   bind(L);
2839 }
2840 
2841 int MacroAssembler::corrected_idivl(Register reg) {
2842   // Full implementation of Java idiv and irem; checks for
2843   // special case as described in JVM spec., p.243 & p.271.
2844   // The function returns the (pc) offset of the idivl
2845   // instruction - may be needed for implicit exceptions.
2846   //
2847   //         normal case                           special case
2848   //
2849   // input : rax,: dividend                         min_int
2850   //         reg: divisor   (may not be rax,/rdx)   -1
2851   //
2852   // output: rax,: quotient  (= rax, idiv reg)       min_int
2853   //         rdx: remainder (= rax, irem reg)       0
2854   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2855   const int min_int = 0x80000000;
2856   Label normal_case, special_case;
2857 
2858   // check for special case
2859   cmpl(rax, min_int);
2860   jcc(Assembler::notEqual, normal_case);
2861   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2862   cmpl(reg, -1);
2863   jcc(Assembler::equal, special_case);
2864 
2865   // handle normal case
2866   bind(normal_case);
2867   cdql();
2868   int idivl_offset = offset();
2869   idivl(reg);
2870 
2871   // normal and special case exit
2872   bind(special_case);
2873 
2874   return idivl_offset;
2875 }
2876 
2877 
2878 
2879 void MacroAssembler::decrementl(Register reg, int value) {
2880   if (value == min_jint) {subl(reg, value) ; return; }
2881   if (value <  0) { incrementl(reg, -value); return; }
2882   if (value == 0) {                        ; return; }
2883   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2884   /* else */      { subl(reg, value)       ; return; }
2885 }
2886 
2887 void MacroAssembler::decrementl(Address dst, int value) {
2888   if (value == min_jint) {subl(dst, value) ; return; }
2889   if (value <  0) { incrementl(dst, -value); return; }
2890   if (value == 0) {                        ; return; }
2891   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2892   /* else */      { subl(dst, value)       ; return; }
2893 }
2894 
2895 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2896   assert (shift_value > 0, "illegal shift value");
2897   Label _is_positive;
2898   testl (reg, reg);
2899   jcc (Assembler::positive, _is_positive);
2900   int offset = (1 << shift_value) - 1 ;
2901 
2902   if (offset == 1) {
2903     incrementl(reg);
2904   } else {
2905     addl(reg, offset);
2906   }
2907 
2908   bind (_is_positive);
2909   sarl(reg, shift_value);
2910 }
2911 
2912 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2913   if (reachable(src)) {
2914     Assembler::divsd(dst, as_Address(src));
2915   } else {
2916     lea(rscratch1, src);
2917     Assembler::divsd(dst, Address(rscratch1, 0));
2918   }
2919 }
2920 
2921 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2922   if (reachable(src)) {
2923     Assembler::divss(dst, as_Address(src));
2924   } else {
2925     lea(rscratch1, src);
2926     Assembler::divss(dst, Address(rscratch1, 0));
2927   }
2928 }
2929 
2930 // !defined(COMPILER2) is because of stupid core builds
2931 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2932 void MacroAssembler::empty_FPU_stack() {
2933   if (VM_Version::supports_mmx()) {
2934     emms();
2935   } else {
2936     for (int i = 8; i-- > 0; ) ffree(i);
2937   }
2938 }
2939 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2940 
2941 
2942 // Defines obj, preserves var_size_in_bytes
2943 void MacroAssembler::eden_allocate(Register obj,
2944                                    Register var_size_in_bytes,
2945                                    int con_size_in_bytes,
2946                                    Register t1,
2947                                    Label& slow_case) {
2948   assert(obj == rax, "obj must be in rax, for cmpxchg");
2949   assert_different_registers(obj, var_size_in_bytes, t1);
2950   if (!Universe::heap()->supports_inline_contig_alloc()) {
2951     jmp(slow_case);
2952   } else {
2953     Register end = t1;
2954     Label retry;
2955     bind(retry);
2956     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2957     movptr(obj, heap_top);
2958     if (var_size_in_bytes == noreg) {
2959       lea(end, Address(obj, con_size_in_bytes));
2960     } else {
2961       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2962     }
2963     // if end < obj then we wrapped around => object too long => slow case
2964     cmpptr(end, obj);
2965     jcc(Assembler::below, slow_case);
2966     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2967     jcc(Assembler::above, slow_case);
2968     // Compare obj with the top addr, and if still equal, store the new top addr in
2969     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2970     // it otherwise. Use lock prefix for atomicity on MPs.
2971     locked_cmpxchgptr(end, heap_top);
2972     jcc(Assembler::notEqual, retry);
2973   }
2974 }
2975 
2976 void MacroAssembler::enter() {
2977   push(rbp);
2978   mov(rbp, rsp);
2979 }
2980 
2981 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2982 void MacroAssembler::fat_nop() {
2983   if (UseAddressNop) {
2984     addr_nop_5();
2985   } else {
2986     emit_int8(0x26); // es:
2987     emit_int8(0x2e); // cs:
2988     emit_int8(0x64); // fs:
2989     emit_int8(0x65); // gs:
2990     emit_int8((unsigned char)0x90);
2991   }
2992 }
2993 
2994 void MacroAssembler::fcmp(Register tmp) {
2995   fcmp(tmp, 1, true, true);
2996 }
2997 
2998 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2999   assert(!pop_right || pop_left, "usage error");
3000   if (VM_Version::supports_cmov()) {
3001     assert(tmp == noreg, "unneeded temp");
3002     if (pop_left) {
3003       fucomip(index);
3004     } else {
3005       fucomi(index);
3006     }
3007     if (pop_right) {
3008       fpop();
3009     }
3010   } else {
3011     assert(tmp != noreg, "need temp");
3012     if (pop_left) {
3013       if (pop_right) {
3014         fcompp();
3015       } else {
3016         fcomp(index);
3017       }
3018     } else {
3019       fcom(index);
3020     }
3021     // convert FPU condition into eflags condition via rax,
3022     save_rax(tmp);
3023     fwait(); fnstsw_ax();
3024     sahf();
3025     restore_rax(tmp);
3026   }
3027   // condition codes set as follows:
3028   //
3029   // CF (corresponds to C0) if x < y
3030   // PF (corresponds to C2) if unordered
3031   // ZF (corresponds to C3) if x = y
3032 }
3033 
3034 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3035   fcmp2int(dst, unordered_is_less, 1, true, true);
3036 }
3037 
3038 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3039   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3040   Label L;
3041   if (unordered_is_less) {
3042     movl(dst, -1);
3043     jcc(Assembler::parity, L);
3044     jcc(Assembler::below , L);
3045     movl(dst, 0);
3046     jcc(Assembler::equal , L);
3047     increment(dst);
3048   } else { // unordered is greater
3049     movl(dst, 1);
3050     jcc(Assembler::parity, L);
3051     jcc(Assembler::above , L);
3052     movl(dst, 0);
3053     jcc(Assembler::equal , L);
3054     decrementl(dst);
3055   }
3056   bind(L);
3057 }
3058 
3059 void MacroAssembler::fld_d(AddressLiteral src) {
3060   fld_d(as_Address(src));
3061 }
3062 
3063 void MacroAssembler::fld_s(AddressLiteral src) {
3064   fld_s(as_Address(src));
3065 }
3066 
3067 void MacroAssembler::fld_x(AddressLiteral src) {
3068   Assembler::fld_x(as_Address(src));
3069 }
3070 
3071 void MacroAssembler::fldcw(AddressLiteral src) {
3072   Assembler::fldcw(as_Address(src));
3073 }
3074 
3075 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3076   if (reachable(src)) {
3077     Assembler::mulpd(dst, as_Address(src));
3078   } else {
3079     lea(rscratch1, src);
3080     Assembler::mulpd(dst, Address(rscratch1, 0));
3081   }
3082 }
3083 
3084 void MacroAssembler::increase_precision() {
3085   subptr(rsp, BytesPerWord);
3086   fnstcw(Address(rsp, 0));
3087   movl(rax, Address(rsp, 0));
3088   orl(rax, 0x300);
3089   push(rax);
3090   fldcw(Address(rsp, 0));
3091   pop(rax);
3092 }
3093 
3094 void MacroAssembler::restore_precision() {
3095   fldcw(Address(rsp, 0));
3096   addptr(rsp, BytesPerWord);
3097 }
3098 
3099 void MacroAssembler::fpop() {
3100   ffree();
3101   fincstp();
3102 }
3103 
3104 void MacroAssembler::load_float(Address src) {
3105   if (UseSSE >= 1) {
3106     movflt(xmm0, src);
3107   } else {
3108     LP64_ONLY(ShouldNotReachHere());
3109     NOT_LP64(fld_s(src));
3110   }
3111 }
3112 
3113 void MacroAssembler::store_float(Address dst) {
3114   if (UseSSE >= 1) {
3115     movflt(dst, xmm0);
3116   } else {
3117     LP64_ONLY(ShouldNotReachHere());
3118     NOT_LP64(fstp_s(dst));
3119   }
3120 }
3121 
3122 void MacroAssembler::load_double(Address src) {
3123   if (UseSSE >= 2) {
3124     movdbl(xmm0, src);
3125   } else {
3126     LP64_ONLY(ShouldNotReachHere());
3127     NOT_LP64(fld_d(src));
3128   }
3129 }
3130 
3131 void MacroAssembler::store_double(Address dst) {
3132   if (UseSSE >= 2) {
3133     movdbl(dst, xmm0);
3134   } else {
3135     LP64_ONLY(ShouldNotReachHere());
3136     NOT_LP64(fstp_d(dst));
3137   }
3138 }
3139 
3140 void MacroAssembler::fremr(Register tmp) {
3141   save_rax(tmp);
3142   { Label L;
3143     bind(L);
3144     fprem();
3145     fwait(); fnstsw_ax();
3146 #ifdef _LP64
3147     testl(rax, 0x400);
3148     jcc(Assembler::notEqual, L);
3149 #else
3150     sahf();
3151     jcc(Assembler::parity, L);
3152 #endif // _LP64
3153   }
3154   restore_rax(tmp);
3155   // Result is in ST0.
3156   // Note: fxch & fpop to get rid of ST1
3157   // (otherwise FPU stack could overflow eventually)
3158   fxch(1);
3159   fpop();
3160 }
3161 
3162 // dst = c = a * b + c
3163 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3164   Assembler::vfmadd231sd(c, a, b);
3165   if (dst != c) {
3166     movdbl(dst, c);
3167   }
3168 }
3169 
3170 // dst = c = a * b + c
3171 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3172   Assembler::vfmadd231ss(c, a, b);
3173   if (dst != c) {
3174     movflt(dst, c);
3175   }
3176 }
3177 
3178 
3179 
3180 
3181 void MacroAssembler::incrementl(AddressLiteral dst) {
3182   if (reachable(dst)) {
3183     incrementl(as_Address(dst));
3184   } else {
3185     lea(rscratch1, dst);
3186     incrementl(Address(rscratch1, 0));
3187   }
3188 }
3189 
3190 void MacroAssembler::incrementl(ArrayAddress dst) {
3191   incrementl(as_Address(dst));
3192 }
3193 
3194 void MacroAssembler::incrementl(Register reg, int value) {
3195   if (value == min_jint) {addl(reg, value) ; return; }
3196   if (value <  0) { decrementl(reg, -value); return; }
3197   if (value == 0) {                        ; return; }
3198   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3199   /* else */      { addl(reg, value)       ; return; }
3200 }
3201 
3202 void MacroAssembler::incrementl(Address dst, int value) {
3203   if (value == min_jint) {addl(dst, value) ; return; }
3204   if (value <  0) { decrementl(dst, -value); return; }
3205   if (value == 0) {                        ; return; }
3206   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3207   /* else */      { addl(dst, value)       ; return; }
3208 }
3209 
3210 void MacroAssembler::jump(AddressLiteral dst) {
3211   if (reachable(dst)) {
3212     jmp_literal(dst.target(), dst.rspec());
3213   } else {
3214     lea(rscratch1, dst);
3215     jmp(rscratch1);
3216   }
3217 }
3218 
3219 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3220   if (reachable(dst)) {
3221     InstructionMark im(this);
3222     relocate(dst.reloc());
3223     const int short_size = 2;
3224     const int long_size = 6;
3225     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3226     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3227       // 0111 tttn #8-bit disp
3228       emit_int8(0x70 | cc);
3229       emit_int8((offs - short_size) & 0xFF);
3230     } else {
3231       // 0000 1111 1000 tttn #32-bit disp
3232       emit_int8(0x0F);
3233       emit_int8((unsigned char)(0x80 | cc));
3234       emit_int32(offs - long_size);
3235     }
3236   } else {
3237 #ifdef ASSERT
3238     warning("reversing conditional branch");
3239 #endif /* ASSERT */
3240     Label skip;
3241     jccb(reverse[cc], skip);
3242     lea(rscratch1, dst);
3243     Assembler::jmp(rscratch1);
3244     bind(skip);
3245   }
3246 }
3247 
3248 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3249   if (reachable(src)) {
3250     Assembler::ldmxcsr(as_Address(src));
3251   } else {
3252     lea(rscratch1, src);
3253     Assembler::ldmxcsr(Address(rscratch1, 0));
3254   }
3255 }
3256 
3257 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3258   int off;
3259   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3260     off = offset();
3261     movsbl(dst, src); // movsxb
3262   } else {
3263     off = load_unsigned_byte(dst, src);
3264     shll(dst, 24);
3265     sarl(dst, 24);
3266   }
3267   return off;
3268 }
3269 
3270 // Note: load_signed_short used to be called load_signed_word.
3271 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3272 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3273 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3274 int MacroAssembler::load_signed_short(Register dst, Address src) {
3275   int off;
3276   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3277     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3278     // version but this is what 64bit has always done. This seems to imply
3279     // that users are only using 32bits worth.
3280     off = offset();
3281     movswl(dst, src); // movsxw
3282   } else {
3283     off = load_unsigned_short(dst, src);
3284     shll(dst, 16);
3285     sarl(dst, 16);
3286   }
3287   return off;
3288 }
3289 
3290 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3291   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3292   // and "3.9 Partial Register Penalties", p. 22).
3293   int off;
3294   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3295     off = offset();
3296     movzbl(dst, src); // movzxb
3297   } else {
3298     xorl(dst, dst);
3299     off = offset();
3300     movb(dst, src);
3301   }
3302   return off;
3303 }
3304 
3305 // Note: load_unsigned_short used to be called load_unsigned_word.
3306 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3307   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3308   // and "3.9 Partial Register Penalties", p. 22).
3309   int off;
3310   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3311     off = offset();
3312     movzwl(dst, src); // movzxw
3313   } else {
3314     xorl(dst, dst);
3315     off = offset();
3316     movw(dst, src);
3317   }
3318   return off;
3319 }
3320 
3321 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3322   switch (size_in_bytes) {
3323 #ifndef _LP64
3324   case  8:
3325     assert(dst2 != noreg, "second dest register required");
3326     movl(dst,  src);
3327     movl(dst2, src.plus_disp(BytesPerInt));
3328     break;
3329 #else
3330   case  8:  movq(dst, src); break;
3331 #endif
3332   case  4:  movl(dst, src); break;
3333   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3334   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3335   default:  ShouldNotReachHere();
3336   }
3337 }
3338 
3339 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3340   switch (size_in_bytes) {
3341 #ifndef _LP64
3342   case  8:
3343     assert(src2 != noreg, "second source register required");
3344     movl(dst,                        src);
3345     movl(dst.plus_disp(BytesPerInt), src2);
3346     break;
3347 #else
3348   case  8:  movq(dst, src); break;
3349 #endif
3350   case  4:  movl(dst, src); break;
3351   case  2:  movw(dst, src); break;
3352   case  1:  movb(dst, src); break;
3353   default:  ShouldNotReachHere();
3354   }
3355 }
3356 
3357 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3358   if (reachable(dst)) {
3359     movl(as_Address(dst), src);
3360   } else {
3361     lea(rscratch1, dst);
3362     movl(Address(rscratch1, 0), src);
3363   }
3364 }
3365 
3366 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3367   if (reachable(src)) {
3368     movl(dst, as_Address(src));
3369   } else {
3370     lea(rscratch1, src);
3371     movl(dst, Address(rscratch1, 0));
3372   }
3373 }
3374 
3375 // C++ bool manipulation
3376 
3377 void MacroAssembler::movbool(Register dst, Address src) {
3378   if(sizeof(bool) == 1)
3379     movb(dst, src);
3380   else if(sizeof(bool) == 2)
3381     movw(dst, src);
3382   else if(sizeof(bool) == 4)
3383     movl(dst, src);
3384   else
3385     // unsupported
3386     ShouldNotReachHere();
3387 }
3388 
3389 void MacroAssembler::movbool(Address dst, bool boolconst) {
3390   if(sizeof(bool) == 1)
3391     movb(dst, (int) boolconst);
3392   else if(sizeof(bool) == 2)
3393     movw(dst, (int) boolconst);
3394   else if(sizeof(bool) == 4)
3395     movl(dst, (int) boolconst);
3396   else
3397     // unsupported
3398     ShouldNotReachHere();
3399 }
3400 
3401 void MacroAssembler::movbool(Address dst, Register src) {
3402   if(sizeof(bool) == 1)
3403     movb(dst, src);
3404   else if(sizeof(bool) == 2)
3405     movw(dst, src);
3406   else if(sizeof(bool) == 4)
3407     movl(dst, src);
3408   else
3409     // unsupported
3410     ShouldNotReachHere();
3411 }
3412 
3413 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3414   movb(as_Address(dst), src);
3415 }
3416 
3417 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3418   if (reachable(src)) {
3419     movdl(dst, as_Address(src));
3420   } else {
3421     lea(rscratch1, src);
3422     movdl(dst, Address(rscratch1, 0));
3423   }
3424 }
3425 
3426 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3427   if (reachable(src)) {
3428     movq(dst, as_Address(src));
3429   } else {
3430     lea(rscratch1, src);
3431     movq(dst, Address(rscratch1, 0));
3432   }
3433 }
3434 
3435 void MacroAssembler::setvectmask(Register dst, Register src) {
3436   Assembler::movl(dst, 1);
3437   Assembler::shlxl(dst, dst, src);
3438   Assembler::decl(dst);
3439   Assembler::kmovdl(k1, dst);
3440   Assembler::movl(dst, src);
3441 }
3442 
3443 void MacroAssembler::restorevectmask() {
3444   Assembler::knotwl(k1, k0);
3445 }
3446 
3447 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3448   if (reachable(src)) {
3449     if (UseXmmLoadAndClearUpper) {
3450       movsd (dst, as_Address(src));
3451     } else {
3452       movlpd(dst, as_Address(src));
3453     }
3454   } else {
3455     lea(rscratch1, src);
3456     if (UseXmmLoadAndClearUpper) {
3457       movsd (dst, Address(rscratch1, 0));
3458     } else {
3459       movlpd(dst, Address(rscratch1, 0));
3460     }
3461   }
3462 }
3463 
3464 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3465   if (reachable(src)) {
3466     movss(dst, as_Address(src));
3467   } else {
3468     lea(rscratch1, src);
3469     movss(dst, Address(rscratch1, 0));
3470   }
3471 }
3472 
3473 void MacroAssembler::movptr(Register dst, Register src) {
3474   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3475 }
3476 
3477 void MacroAssembler::movptr(Register dst, Address src) {
3478   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3479 }
3480 
3481 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3482 void MacroAssembler::movptr(Register dst, intptr_t src) {
3483   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3484 }
3485 
3486 void MacroAssembler::movptr(Address dst, Register src) {
3487   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3488 }
3489 
3490 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3491   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3492     Assembler::vextractf32x4(dst, src, 0);
3493   } else {
3494     Assembler::movdqu(dst, src);
3495   }
3496 }
3497 
3498 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3499   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3500     Assembler::vinsertf32x4(dst, dst, src, 0);
3501   } else {
3502     Assembler::movdqu(dst, src);
3503   }
3504 }
3505 
3506 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3507   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3508     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3509   } else {
3510     Assembler::movdqu(dst, src);
3511   }
3512 }
3513 
3514 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3515   if (reachable(src)) {
3516     movdqu(dst, as_Address(src));
3517   } else {
3518     lea(scratchReg, src);
3519     movdqu(dst, Address(scratchReg, 0));
3520   }
3521 }
3522 
3523 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3524   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3525     vextractf64x4_low(dst, src);
3526   } else {
3527     Assembler::vmovdqu(dst, src);
3528   }
3529 }
3530 
3531 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3532   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3533     vinsertf64x4_low(dst, src);
3534   } else {
3535     Assembler::vmovdqu(dst, src);
3536   }
3537 }
3538 
3539 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3540   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3541     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3542   }
3543   else {
3544     Assembler::vmovdqu(dst, src);
3545   }
3546 }
3547 
3548 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3549   if (reachable(src)) {
3550     vmovdqu(dst, as_Address(src));
3551   }
3552   else {
3553     lea(rscratch1, src);
3554     vmovdqu(dst, Address(rscratch1, 0));
3555   }
3556 }
3557 
3558 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3559   if (reachable(src)) {
3560     Assembler::movdqa(dst, as_Address(src));
3561   } else {
3562     lea(rscratch1, src);
3563     Assembler::movdqa(dst, Address(rscratch1, 0));
3564   }
3565 }
3566 
3567 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3568   if (reachable(src)) {
3569     Assembler::movsd(dst, as_Address(src));
3570   } else {
3571     lea(rscratch1, src);
3572     Assembler::movsd(dst, Address(rscratch1, 0));
3573   }
3574 }
3575 
3576 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3577   if (reachable(src)) {
3578     Assembler::movss(dst, as_Address(src));
3579   } else {
3580     lea(rscratch1, src);
3581     Assembler::movss(dst, Address(rscratch1, 0));
3582   }
3583 }
3584 
3585 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3586   if (reachable(src)) {
3587     Assembler::mulsd(dst, as_Address(src));
3588   } else {
3589     lea(rscratch1, src);
3590     Assembler::mulsd(dst, Address(rscratch1, 0));
3591   }
3592 }
3593 
3594 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3595   if (reachable(src)) {
3596     Assembler::mulss(dst, as_Address(src));
3597   } else {
3598     lea(rscratch1, src);
3599     Assembler::mulss(dst, Address(rscratch1, 0));
3600   }
3601 }
3602 
3603 void MacroAssembler::null_check(Register reg, int offset) {
3604   if (needs_explicit_null_check(offset)) {
3605     // provoke OS NULL exception if reg = NULL by
3606     // accessing M[reg] w/o changing any (non-CC) registers
3607     // NOTE: cmpl is plenty here to provoke a segv
3608 
3609     if (ShenandoahVerifyReadsToFromSpace) {
3610       oopDesc::bs()->interpreter_read_barrier(this, reg);
3611     }
3612 
3613     cmpptr(rax, Address(reg, 0));
3614     // Note: should probably use testl(rax, Address(reg, 0));
3615     //       may be shorter code (however, this version of
3616     //       testl needs to be implemented first)
3617   } else {
3618     // nothing to do, (later) access of M[reg + offset]
3619     // will provoke OS NULL exception if reg = NULL
3620   }
3621 }
3622 
3623 void MacroAssembler::os_breakpoint() {
3624   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3625   // (e.g., MSVC can't call ps() otherwise)
3626   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3627 }
3628 
3629 #ifdef _LP64
3630 #define XSTATE_BV 0x200
3631 #endif
3632 
3633 void MacroAssembler::pop_CPU_state() {
3634   pop_FPU_state();
3635   pop_IU_state();
3636 }
3637 
3638 void MacroAssembler::pop_FPU_state() {
3639 #ifndef _LP64
3640   frstor(Address(rsp, 0));
3641 #else
3642   fxrstor(Address(rsp, 0));
3643 #endif
3644   addptr(rsp, FPUStateSizeInWords * wordSize);
3645 }
3646 
3647 void MacroAssembler::pop_IU_state() {
3648   popa();
3649   LP64_ONLY(addq(rsp, 8));
3650   popf();
3651 }
3652 
3653 // Save Integer and Float state
3654 // Warning: Stack must be 16 byte aligned (64bit)
3655 void MacroAssembler::push_CPU_state() {
3656   push_IU_state();
3657   push_FPU_state();
3658 }
3659 
3660 void MacroAssembler::push_FPU_state() {
3661   subptr(rsp, FPUStateSizeInWords * wordSize);
3662 #ifndef _LP64
3663   fnsave(Address(rsp, 0));
3664   fwait();
3665 #else
3666   fxsave(Address(rsp, 0));
3667 #endif // LP64
3668 }
3669 
3670 void MacroAssembler::push_IU_state() {
3671   // Push flags first because pusha kills them
3672   pushf();
3673   // Make sure rsp stays 16-byte aligned
3674   LP64_ONLY(subq(rsp, 8));
3675   pusha();
3676 }
3677 
3678 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3679   if (!java_thread->is_valid()) {
3680     java_thread = rdi;
3681     get_thread(java_thread);
3682   }
3683   // we must set sp to zero to clear frame
3684   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3685   if (clear_fp) {
3686     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3687   }
3688 
3689   // Always clear the pc because it could have been set by make_walkable()
3690   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3691 
3692 }
3693 
3694 void MacroAssembler::restore_rax(Register tmp) {
3695   if (tmp == noreg) pop(rax);
3696   else if (tmp != rax) mov(rax, tmp);
3697 }
3698 
3699 void MacroAssembler::round_to(Register reg, int modulus) {
3700   addptr(reg, modulus - 1);
3701   andptr(reg, -modulus);
3702 }
3703 
3704 void MacroAssembler::save_rax(Register tmp) {
3705   if (tmp == noreg) push(rax);
3706   else if (tmp != rax) mov(tmp, rax);
3707 }
3708 
3709 // Write serialization page so VM thread can do a pseudo remote membar.
3710 // We use the current thread pointer to calculate a thread specific
3711 // offset to write to within the page. This minimizes bus traffic
3712 // due to cache line collision.
3713 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3714   movl(tmp, thread);
3715   shrl(tmp, os::get_serialize_page_shift_count());
3716   andl(tmp, (os::vm_page_size() - sizeof(int)));
3717 
3718   Address index(noreg, tmp, Address::times_1);
3719   ExternalAddress page(os::get_memory_serialize_page());
3720 
3721   // Size of store must match masking code above
3722   movl(as_Address(ArrayAddress(page, index)), tmp);
3723 }
3724 
3725 // Special Shenandoah CAS implementation that handles false negatives
3726 // due to concurrent evacuation.
3727 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3728                               bool exchange,
3729                               Register tmp1, Register tmp2) {
3730   assert(UseShenandoahGC, "Should only be used with Shenandoah");
3731   assert(ShenandoahCASBarrier, "Should only be used when CAS barrier is enabled");
3732   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
3733 
3734   Label retry, done;
3735 
3736   // Remember oldval for retry logic below
3737   if (UseCompressedOops) {
3738     movl(tmp1, oldval);
3739   } else {
3740     movptr(tmp1, oldval);
3741   }
3742 
3743   // Step 1. Try to CAS with given arguments. If successful, then we are done,
3744   // and can safely return.
3745   if (os::is_MP()) lock();
3746   if (UseCompressedOops) {
3747     cmpxchgl(newval, addr);
3748   } else {
3749     cmpxchgptr(newval, addr);
3750   }
3751   jcc(Assembler::equal, done, true);
3752 
3753   // Step 2. CAS had failed. This may be a false negative.
3754   //
3755   // The trouble comes when we compare the to-space pointer with the from-space
3756   // pointer to the same object. To resolve this, it will suffice to read both
3757   // oldval and the value from memory through the read barriers -- this will give
3758   // both to-space pointers. If they mismatch, then it was a legitimate failure.
3759   //
3760   if (UseCompressedOops) {
3761     decode_heap_oop(tmp1);
3762   }
3763   oopDesc::bs()->interpreter_read_barrier(this, tmp1);
3764 
3765   if (UseCompressedOops) {
3766     movl(tmp2, oldval);
3767     decode_heap_oop(tmp2);
3768   } else {
3769     movptr(tmp2, oldval);
3770   }
3771   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3772 
3773   cmpptr(tmp1, tmp2);
3774   jcc(Assembler::notEqual, done, true);
3775 
3776   // Step 3. Try to CAS again with resolved to-space pointers.
3777   //
3778   // Corner case: it may happen that somebody stored the from-space pointer
3779   // to memory while we were preparing for retry. Therefore, we can fail again
3780   // on retry, and so need to do this in loop, always re-reading the failure
3781   // witness through the read barrier.
3782   bind(retry);
3783   if (os::is_MP()) lock();
3784   if (UseCompressedOops) {
3785     cmpxchgl(newval, addr);
3786   } else {
3787     cmpxchgptr(newval, addr);
3788   }
3789   jcc(Assembler::equal, done, true);
3790 
3791   if (UseCompressedOops) {
3792     movl(tmp2, oldval);
3793     decode_heap_oop(tmp2);
3794   } else {
3795     movptr(tmp2, oldval);
3796   }
3797   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3798 
3799   cmpptr(tmp1, tmp2);
3800   jcc(Assembler::equal, retry, true);
3801 
3802   // Step 4. If we need a boolean result out of CAS, check the flag again,
3803   // and promote the result. Note that we handle the flag from both the CAS
3804   // itself and from the retry loop.
3805   bind(done);
3806   if (!exchange) {
3807     setb(Assembler::equal, res);
3808     movzbl(res, res);
3809   }
3810 }
3811 
3812 // Calls to C land
3813 //
3814 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3815 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3816 // has to be reset to 0. This is required to allow proper stack traversal.
3817 void MacroAssembler::set_last_Java_frame(Register java_thread,
3818                                          Register last_java_sp,
3819                                          Register last_java_fp,
3820                                          address  last_java_pc) {
3821   // determine java_thread register
3822   if (!java_thread->is_valid()) {
3823     java_thread = rdi;
3824     get_thread(java_thread);
3825   }
3826   // determine last_java_sp register
3827   if (!last_java_sp->is_valid()) {
3828     last_java_sp = rsp;
3829   }
3830 
3831   // last_java_fp is optional
3832 
3833   if (last_java_fp->is_valid()) {
3834     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3835   }
3836 
3837   // last_java_pc is optional
3838 
3839   if (last_java_pc != NULL) {
3840     lea(Address(java_thread,
3841                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3842         InternalAddress(last_java_pc));
3843 
3844   }
3845   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3846 }
3847 
3848 void MacroAssembler::shlptr(Register dst, int imm8) {
3849   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3850 }
3851 
3852 void MacroAssembler::shrptr(Register dst, int imm8) {
3853   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3854 }
3855 
3856 void MacroAssembler::sign_extend_byte(Register reg) {
3857   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3858     movsbl(reg, reg); // movsxb
3859   } else {
3860     shll(reg, 24);
3861     sarl(reg, 24);
3862   }
3863 }
3864 
3865 void MacroAssembler::sign_extend_short(Register reg) {
3866   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3867     movswl(reg, reg); // movsxw
3868   } else {
3869     shll(reg, 16);
3870     sarl(reg, 16);
3871   }
3872 }
3873 
3874 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3875   assert(reachable(src), "Address should be reachable");
3876   testl(dst, as_Address(src));
3877 }
3878 
3879 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3880   int dst_enc = dst->encoding();
3881   int src_enc = src->encoding();
3882   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3883     Assembler::pcmpeqb(dst, src);
3884   } else if ((dst_enc < 16) && (src_enc < 16)) {
3885     Assembler::pcmpeqb(dst, src);
3886   } else if (src_enc < 16) {
3887     subptr(rsp, 64);
3888     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3889     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3890     Assembler::pcmpeqb(xmm0, src);
3891     movdqu(dst, xmm0);
3892     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3893     addptr(rsp, 64);
3894   } else if (dst_enc < 16) {
3895     subptr(rsp, 64);
3896     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3897     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3898     Assembler::pcmpeqb(dst, xmm0);
3899     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3900     addptr(rsp, 64);
3901   } else {
3902     subptr(rsp, 64);
3903     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3904     subptr(rsp, 64);
3905     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3906     movdqu(xmm0, src);
3907     movdqu(xmm1, dst);
3908     Assembler::pcmpeqb(xmm1, xmm0);
3909     movdqu(dst, xmm1);
3910     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3911     addptr(rsp, 64);
3912     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3913     addptr(rsp, 64);
3914   }
3915 }
3916 
3917 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3918   int dst_enc = dst->encoding();
3919   int src_enc = src->encoding();
3920   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3921     Assembler::pcmpeqw(dst, src);
3922   } else if ((dst_enc < 16) && (src_enc < 16)) {
3923     Assembler::pcmpeqw(dst, src);
3924   } else if (src_enc < 16) {
3925     subptr(rsp, 64);
3926     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3927     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3928     Assembler::pcmpeqw(xmm0, src);
3929     movdqu(dst, xmm0);
3930     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3931     addptr(rsp, 64);
3932   } else if (dst_enc < 16) {
3933     subptr(rsp, 64);
3934     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3935     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3936     Assembler::pcmpeqw(dst, xmm0);
3937     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3938     addptr(rsp, 64);
3939   } else {
3940     subptr(rsp, 64);
3941     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3942     subptr(rsp, 64);
3943     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3944     movdqu(xmm0, src);
3945     movdqu(xmm1, dst);
3946     Assembler::pcmpeqw(xmm1, xmm0);
3947     movdqu(dst, xmm1);
3948     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3949     addptr(rsp, 64);
3950     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3951     addptr(rsp, 64);
3952   }
3953 }
3954 
3955 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3956   int dst_enc = dst->encoding();
3957   if (dst_enc < 16) {
3958     Assembler::pcmpestri(dst, src, imm8);
3959   } else {
3960     subptr(rsp, 64);
3961     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3962     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3963     Assembler::pcmpestri(xmm0, src, imm8);
3964     movdqu(dst, xmm0);
3965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3966     addptr(rsp, 64);
3967   }
3968 }
3969 
3970 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3971   int dst_enc = dst->encoding();
3972   int src_enc = src->encoding();
3973   if ((dst_enc < 16) && (src_enc < 16)) {
3974     Assembler::pcmpestri(dst, src, imm8);
3975   } else if (src_enc < 16) {
3976     subptr(rsp, 64);
3977     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3978     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3979     Assembler::pcmpestri(xmm0, src, imm8);
3980     movdqu(dst, xmm0);
3981     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3982     addptr(rsp, 64);
3983   } else if (dst_enc < 16) {
3984     subptr(rsp, 64);
3985     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3986     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3987     Assembler::pcmpestri(dst, xmm0, imm8);
3988     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3989     addptr(rsp, 64);
3990   } else {
3991     subptr(rsp, 64);
3992     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3993     subptr(rsp, 64);
3994     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3995     movdqu(xmm0, src);
3996     movdqu(xmm1, dst);
3997     Assembler::pcmpestri(xmm1, xmm0, imm8);
3998     movdqu(dst, xmm1);
3999     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4000     addptr(rsp, 64);
4001     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4002     addptr(rsp, 64);
4003   }
4004 }
4005 
4006 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4007   int dst_enc = dst->encoding();
4008   int src_enc = src->encoding();
4009   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4010     Assembler::pmovzxbw(dst, src);
4011   } else if ((dst_enc < 16) && (src_enc < 16)) {
4012     Assembler::pmovzxbw(dst, src);
4013   } else if (src_enc < 16) {
4014     subptr(rsp, 64);
4015     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4016     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4017     Assembler::pmovzxbw(xmm0, src);
4018     movdqu(dst, xmm0);
4019     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4020     addptr(rsp, 64);
4021   } else if (dst_enc < 16) {
4022     subptr(rsp, 64);
4023     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4024     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4025     Assembler::pmovzxbw(dst, xmm0);
4026     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4027     addptr(rsp, 64);
4028   } else {
4029     subptr(rsp, 64);
4030     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4031     subptr(rsp, 64);
4032     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4033     movdqu(xmm0, src);
4034     movdqu(xmm1, dst);
4035     Assembler::pmovzxbw(xmm1, xmm0);
4036     movdqu(dst, xmm1);
4037     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4038     addptr(rsp, 64);
4039     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4040     addptr(rsp, 64);
4041   }
4042 }
4043 
4044 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4045   int dst_enc = dst->encoding();
4046   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4047     Assembler::pmovzxbw(dst, src);
4048   } else if (dst_enc < 16) {
4049     Assembler::pmovzxbw(dst, src);
4050   } else {
4051     subptr(rsp, 64);
4052     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4053     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4054     Assembler::pmovzxbw(xmm0, src);
4055     movdqu(dst, xmm0);
4056     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4057     addptr(rsp, 64);
4058   }
4059 }
4060 
4061 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4062   int src_enc = src->encoding();
4063   if (src_enc < 16) {
4064     Assembler::pmovmskb(dst, src);
4065   } else {
4066     subptr(rsp, 64);
4067     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4068     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4069     Assembler::pmovmskb(dst, xmm0);
4070     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4071     addptr(rsp, 64);
4072   }
4073 }
4074 
4075 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4076   int dst_enc = dst->encoding();
4077   int src_enc = src->encoding();
4078   if ((dst_enc < 16) && (src_enc < 16)) {
4079     Assembler::ptest(dst, src);
4080   } else if (src_enc < 16) {
4081     subptr(rsp, 64);
4082     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4083     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4084     Assembler::ptest(xmm0, src);
4085     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4086     addptr(rsp, 64);
4087   } else if (dst_enc < 16) {
4088     subptr(rsp, 64);
4089     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4090     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4091     Assembler::ptest(dst, xmm0);
4092     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4093     addptr(rsp, 64);
4094   } else {
4095     subptr(rsp, 64);
4096     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4097     subptr(rsp, 64);
4098     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4099     movdqu(xmm0, src);
4100     movdqu(xmm1, dst);
4101     Assembler::ptest(xmm1, xmm0);
4102     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4103     addptr(rsp, 64);
4104     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4105     addptr(rsp, 64);
4106   }
4107 }
4108 
4109 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4110   if (reachable(src)) {
4111     Assembler::sqrtsd(dst, as_Address(src));
4112   } else {
4113     lea(rscratch1, src);
4114     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4115   }
4116 }
4117 
4118 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4119   if (reachable(src)) {
4120     Assembler::sqrtss(dst, as_Address(src));
4121   } else {
4122     lea(rscratch1, src);
4123     Assembler::sqrtss(dst, Address(rscratch1, 0));
4124   }
4125 }
4126 
4127 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4128   if (reachable(src)) {
4129     Assembler::subsd(dst, as_Address(src));
4130   } else {
4131     lea(rscratch1, src);
4132     Assembler::subsd(dst, Address(rscratch1, 0));
4133   }
4134 }
4135 
4136 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4137   if (reachable(src)) {
4138     Assembler::subss(dst, as_Address(src));
4139   } else {
4140     lea(rscratch1, src);
4141     Assembler::subss(dst, Address(rscratch1, 0));
4142   }
4143 }
4144 
4145 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4146   if (reachable(src)) {
4147     Assembler::ucomisd(dst, as_Address(src));
4148   } else {
4149     lea(rscratch1, src);
4150     Assembler::ucomisd(dst, Address(rscratch1, 0));
4151   }
4152 }
4153 
4154 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4155   if (reachable(src)) {
4156     Assembler::ucomiss(dst, as_Address(src));
4157   } else {
4158     lea(rscratch1, src);
4159     Assembler::ucomiss(dst, Address(rscratch1, 0));
4160   }
4161 }
4162 
4163 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4164   // Used in sign-bit flipping with aligned address.
4165   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4166   if (reachable(src)) {
4167     Assembler::xorpd(dst, as_Address(src));
4168   } else {
4169     lea(rscratch1, src);
4170     Assembler::xorpd(dst, Address(rscratch1, 0));
4171   }
4172 }
4173 
4174 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4175   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4176     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4177   }
4178   else {
4179     Assembler::xorpd(dst, src);
4180   }
4181 }
4182 
4183 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4184   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4185     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4186   } else {
4187     Assembler::xorps(dst, src);
4188   }
4189 }
4190 
4191 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4192   // Used in sign-bit flipping with aligned address.
4193   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4194   if (reachable(src)) {
4195     Assembler::xorps(dst, as_Address(src));
4196   } else {
4197     lea(rscratch1, src);
4198     Assembler::xorps(dst, Address(rscratch1, 0));
4199   }
4200 }
4201 
4202 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4203   // Used in sign-bit flipping with aligned address.
4204   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4205   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4206   if (reachable(src)) {
4207     Assembler::pshufb(dst, as_Address(src));
4208   } else {
4209     lea(rscratch1, src);
4210     Assembler::pshufb(dst, Address(rscratch1, 0));
4211   }
4212 }
4213 
4214 // AVX 3-operands instructions
4215 
4216 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4217   if (reachable(src)) {
4218     vaddsd(dst, nds, as_Address(src));
4219   } else {
4220     lea(rscratch1, src);
4221     vaddsd(dst, nds, Address(rscratch1, 0));
4222   }
4223 }
4224 
4225 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4226   if (reachable(src)) {
4227     vaddss(dst, nds, as_Address(src));
4228   } else {
4229     lea(rscratch1, src);
4230     vaddss(dst, nds, Address(rscratch1, 0));
4231   }
4232 }
4233 
4234 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4235   int dst_enc = dst->encoding();
4236   int nds_enc = nds->encoding();
4237   int src_enc = src->encoding();
4238   if ((dst_enc < 16) && (nds_enc < 16)) {
4239     vandps(dst, nds, negate_field, vector_len);
4240   } else if ((src_enc < 16) && (dst_enc < 16)) {
4241     movss(src, nds);
4242     vandps(dst, src, negate_field, vector_len);
4243   } else if (src_enc < 16) {
4244     movss(src, nds);
4245     vandps(src, src, negate_field, vector_len);
4246     movss(dst, src);
4247   } else if (dst_enc < 16) {
4248     movdqu(src, xmm0);
4249     movss(xmm0, nds);
4250     vandps(dst, xmm0, negate_field, vector_len);
4251     movdqu(xmm0, src);
4252   } else if (nds_enc < 16) {
4253     movdqu(src, xmm0);
4254     vandps(xmm0, nds, negate_field, vector_len);
4255     movss(dst, xmm0);
4256     movdqu(xmm0, src);
4257   } else {
4258     movdqu(src, xmm0);
4259     movss(xmm0, nds);
4260     vandps(xmm0, xmm0, negate_field, vector_len);
4261     movss(dst, xmm0);
4262     movdqu(xmm0, src);
4263   }
4264 }
4265 
4266 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4267   int dst_enc = dst->encoding();
4268   int nds_enc = nds->encoding();
4269   int src_enc = src->encoding();
4270   if ((dst_enc < 16) && (nds_enc < 16)) {
4271     vandpd(dst, nds, negate_field, vector_len);
4272   } else if ((src_enc < 16) && (dst_enc < 16)) {
4273     movsd(src, nds);
4274     vandpd(dst, src, negate_field, vector_len);
4275   } else if (src_enc < 16) {
4276     movsd(src, nds);
4277     vandpd(src, src, negate_field, vector_len);
4278     movsd(dst, src);
4279   } else if (dst_enc < 16) {
4280     movdqu(src, xmm0);
4281     movsd(xmm0, nds);
4282     vandpd(dst, xmm0, negate_field, vector_len);
4283     movdqu(xmm0, src);
4284   } else if (nds_enc < 16) {
4285     movdqu(src, xmm0);
4286     vandpd(xmm0, nds, negate_field, vector_len);
4287     movsd(dst, xmm0);
4288     movdqu(xmm0, src);
4289   } else {
4290     movdqu(src, xmm0);
4291     movsd(xmm0, nds);
4292     vandpd(xmm0, xmm0, negate_field, vector_len);
4293     movsd(dst, xmm0);
4294     movdqu(xmm0, src);
4295   }
4296 }
4297 
4298 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4299   int dst_enc = dst->encoding();
4300   int nds_enc = nds->encoding();
4301   int src_enc = src->encoding();
4302   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4303     Assembler::vpaddb(dst, nds, src, vector_len);
4304   } else if ((dst_enc < 16) && (src_enc < 16)) {
4305     Assembler::vpaddb(dst, dst, src, vector_len);
4306   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4307     // use nds as scratch for src
4308     evmovdqul(nds, src, Assembler::AVX_512bit);
4309     Assembler::vpaddb(dst, dst, nds, vector_len);
4310   } else if ((src_enc < 16) && (nds_enc < 16)) {
4311     // use nds as scratch for dst
4312     evmovdqul(nds, dst, Assembler::AVX_512bit);
4313     Assembler::vpaddb(nds, nds, src, vector_len);
4314     evmovdqul(dst, nds, Assembler::AVX_512bit);
4315   } else if (dst_enc < 16) {
4316     // use nds as scatch for xmm0 to hold src
4317     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4318     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4319     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4320     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4321   } else {
4322     // worse case scenario, all regs are in the upper bank
4323     subptr(rsp, 64);
4324     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4325     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4326     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4327     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4328     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4329     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4330     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4331     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4332     addptr(rsp, 64);
4333   }
4334 }
4335 
4336 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4337   int dst_enc = dst->encoding();
4338   int nds_enc = nds->encoding();
4339   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4340     Assembler::vpaddb(dst, nds, src, vector_len);
4341   } else if (dst_enc < 16) {
4342     Assembler::vpaddb(dst, dst, src, vector_len);
4343   } else if (nds_enc < 16) {
4344     // implies dst_enc in upper bank with src as scratch
4345     evmovdqul(nds, dst, Assembler::AVX_512bit);
4346     Assembler::vpaddb(nds, nds, src, vector_len);
4347     evmovdqul(dst, nds, Assembler::AVX_512bit);
4348   } else {
4349     // worse case scenario, all regs in upper bank
4350     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4351     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4352     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4353     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4354   }
4355 }
4356 
4357 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4358   int dst_enc = dst->encoding();
4359   int nds_enc = nds->encoding();
4360   int src_enc = src->encoding();
4361   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4362     Assembler::vpaddw(dst, nds, src, vector_len);
4363   } else if ((dst_enc < 16) && (src_enc < 16)) {
4364     Assembler::vpaddw(dst, dst, src, vector_len);
4365   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4366     // use nds as scratch for src
4367     evmovdqul(nds, src, Assembler::AVX_512bit);
4368     Assembler::vpaddw(dst, dst, nds, vector_len);
4369   } else if ((src_enc < 16) && (nds_enc < 16)) {
4370     // use nds as scratch for dst
4371     evmovdqul(nds, dst, Assembler::AVX_512bit);
4372     Assembler::vpaddw(nds, nds, src, vector_len);
4373     evmovdqul(dst, nds, Assembler::AVX_512bit);
4374   } else if (dst_enc < 16) {
4375     // use nds as scatch for xmm0 to hold src
4376     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4377     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4378     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4379     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4380   } else {
4381     // worse case scenario, all regs are in the upper bank
4382     subptr(rsp, 64);
4383     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4384     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4385     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4386     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4387     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4388     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4389     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4390     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4391     addptr(rsp, 64);
4392   }
4393 }
4394 
4395 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4396   int dst_enc = dst->encoding();
4397   int nds_enc = nds->encoding();
4398   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4399     Assembler::vpaddw(dst, nds, src, vector_len);
4400   } else if (dst_enc < 16) {
4401     Assembler::vpaddw(dst, dst, src, vector_len);
4402   } else if (nds_enc < 16) {
4403     // implies dst_enc in upper bank with src as scratch
4404     evmovdqul(nds, dst, Assembler::AVX_512bit);
4405     Assembler::vpaddw(nds, nds, src, vector_len);
4406     evmovdqul(dst, nds, Assembler::AVX_512bit);
4407   } else {
4408     // worse case scenario, all regs in upper bank
4409     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4410     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4411     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4412     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4413   }
4414 }
4415 
4416 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4417   if (reachable(src)) {
4418     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4419   } else {
4420     lea(rscratch1, src);
4421     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4422   }
4423 }
4424 
4425 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4426   int dst_enc = dst->encoding();
4427   int src_enc = src->encoding();
4428   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4429     Assembler::vpbroadcastw(dst, src);
4430   } else if ((dst_enc < 16) && (src_enc < 16)) {
4431     Assembler::vpbroadcastw(dst, src);
4432   } else if (src_enc < 16) {
4433     subptr(rsp, 64);
4434     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4435     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4436     Assembler::vpbroadcastw(xmm0, src);
4437     movdqu(dst, xmm0);
4438     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4439     addptr(rsp, 64);
4440   } else if (dst_enc < 16) {
4441     subptr(rsp, 64);
4442     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4443     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4444     Assembler::vpbroadcastw(dst, xmm0);
4445     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4446     addptr(rsp, 64);
4447   } else {
4448     subptr(rsp, 64);
4449     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4450     subptr(rsp, 64);
4451     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4452     movdqu(xmm0, src);
4453     movdqu(xmm1, dst);
4454     Assembler::vpbroadcastw(xmm1, xmm0);
4455     movdqu(dst, xmm1);
4456     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4457     addptr(rsp, 64);
4458     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4459     addptr(rsp, 64);
4460   }
4461 }
4462 
4463 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4464   int dst_enc = dst->encoding();
4465   int nds_enc = nds->encoding();
4466   int src_enc = src->encoding();
4467   assert(dst_enc == nds_enc, "");
4468   if ((dst_enc < 16) && (src_enc < 16)) {
4469     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4470   } else if (src_enc < 16) {
4471     subptr(rsp, 64);
4472     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4473     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4474     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4475     movdqu(dst, xmm0);
4476     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4477     addptr(rsp, 64);
4478   } else if (dst_enc < 16) {
4479     subptr(rsp, 64);
4480     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4481     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4482     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4483     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4484     addptr(rsp, 64);
4485   } else {
4486     subptr(rsp, 64);
4487     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4488     subptr(rsp, 64);
4489     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4490     movdqu(xmm0, src);
4491     movdqu(xmm1, dst);
4492     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4493     movdqu(dst, xmm1);
4494     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4495     addptr(rsp, 64);
4496     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4497     addptr(rsp, 64);
4498   }
4499 }
4500 
4501 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4502   int dst_enc = dst->encoding();
4503   int nds_enc = nds->encoding();
4504   int src_enc = src->encoding();
4505   assert(dst_enc == nds_enc, "");
4506   if ((dst_enc < 16) && (src_enc < 16)) {
4507     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4508   } else if (src_enc < 16) {
4509     subptr(rsp, 64);
4510     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4511     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4512     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4513     movdqu(dst, xmm0);
4514     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4515     addptr(rsp, 64);
4516   } else if (dst_enc < 16) {
4517     subptr(rsp, 64);
4518     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4519     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4520     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4521     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4522     addptr(rsp, 64);
4523   } else {
4524     subptr(rsp, 64);
4525     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4526     subptr(rsp, 64);
4527     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4528     movdqu(xmm0, src);
4529     movdqu(xmm1, dst);
4530     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4531     movdqu(dst, xmm1);
4532     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4533     addptr(rsp, 64);
4534     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4535     addptr(rsp, 64);
4536   }
4537 }
4538 
4539 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4540   int dst_enc = dst->encoding();
4541   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4542     Assembler::vpmovzxbw(dst, src, vector_len);
4543   } else if (dst_enc < 16) {
4544     Assembler::vpmovzxbw(dst, src, vector_len);
4545   } else {
4546     subptr(rsp, 64);
4547     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4548     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4549     Assembler::vpmovzxbw(xmm0, src, vector_len);
4550     movdqu(dst, xmm0);
4551     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4552     addptr(rsp, 64);
4553   }
4554 }
4555 
4556 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4557   int src_enc = src->encoding();
4558   if (src_enc < 16) {
4559     Assembler::vpmovmskb(dst, src);
4560   } else {
4561     subptr(rsp, 64);
4562     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4563     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4564     Assembler::vpmovmskb(dst, xmm0);
4565     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4566     addptr(rsp, 64);
4567   }
4568 }
4569 
4570 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4571   int dst_enc = dst->encoding();
4572   int nds_enc = nds->encoding();
4573   int src_enc = src->encoding();
4574   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4575     Assembler::vpmullw(dst, nds, src, vector_len);
4576   } else if ((dst_enc < 16) && (src_enc < 16)) {
4577     Assembler::vpmullw(dst, dst, src, vector_len);
4578   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4579     // use nds as scratch for src
4580     evmovdqul(nds, src, Assembler::AVX_512bit);
4581     Assembler::vpmullw(dst, dst, nds, vector_len);
4582   } else if ((src_enc < 16) && (nds_enc < 16)) {
4583     // use nds as scratch for dst
4584     evmovdqul(nds, dst, Assembler::AVX_512bit);
4585     Assembler::vpmullw(nds, nds, src, vector_len);
4586     evmovdqul(dst, nds, Assembler::AVX_512bit);
4587   } else if (dst_enc < 16) {
4588     // use nds as scatch for xmm0 to hold src
4589     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4590     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4591     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4592     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4593   } else {
4594     // worse case scenario, all regs are in the upper bank
4595     subptr(rsp, 64);
4596     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4597     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4598     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4599     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4600     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4601     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4603     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4604     addptr(rsp, 64);
4605   }
4606 }
4607 
4608 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4609   int dst_enc = dst->encoding();
4610   int nds_enc = nds->encoding();
4611   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4612     Assembler::vpmullw(dst, nds, src, vector_len);
4613   } else if (dst_enc < 16) {
4614     Assembler::vpmullw(dst, dst, src, vector_len);
4615   } else if (nds_enc < 16) {
4616     // implies dst_enc in upper bank with src as scratch
4617     evmovdqul(nds, dst, Assembler::AVX_512bit);
4618     Assembler::vpmullw(nds, nds, src, vector_len);
4619     evmovdqul(dst, nds, Assembler::AVX_512bit);
4620   } else {
4621     // worse case scenario, all regs in upper bank
4622     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4623     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4624     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4625     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4626   }
4627 }
4628 
4629 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4630   int dst_enc = dst->encoding();
4631   int nds_enc = nds->encoding();
4632   int src_enc = src->encoding();
4633   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4634     Assembler::vpsubb(dst, nds, src, vector_len);
4635   } else if ((dst_enc < 16) && (src_enc < 16)) {
4636     Assembler::vpsubb(dst, dst, src, vector_len);
4637   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4638     // use nds as scratch for src
4639     evmovdqul(nds, src, Assembler::AVX_512bit);
4640     Assembler::vpsubb(dst, dst, nds, vector_len);
4641   } else if ((src_enc < 16) && (nds_enc < 16)) {
4642     // use nds as scratch for dst
4643     evmovdqul(nds, dst, Assembler::AVX_512bit);
4644     Assembler::vpsubb(nds, nds, src, vector_len);
4645     evmovdqul(dst, nds, Assembler::AVX_512bit);
4646   } else if (dst_enc < 16) {
4647     // use nds as scatch for xmm0 to hold src
4648     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4649     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4650     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4651     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4652   } else {
4653     // worse case scenario, all regs are in the upper bank
4654     subptr(rsp, 64);
4655     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4656     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4657     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4658     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4659     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4660     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4661     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4662     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4663     addptr(rsp, 64);
4664   }
4665 }
4666 
4667 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4668   int dst_enc = dst->encoding();
4669   int nds_enc = nds->encoding();
4670   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4671     Assembler::vpsubb(dst, nds, src, vector_len);
4672   } else if (dst_enc < 16) {
4673     Assembler::vpsubb(dst, dst, src, vector_len);
4674   } else if (nds_enc < 16) {
4675     // implies dst_enc in upper bank with src as scratch
4676     evmovdqul(nds, dst, Assembler::AVX_512bit);
4677     Assembler::vpsubb(nds, nds, src, vector_len);
4678     evmovdqul(dst, nds, Assembler::AVX_512bit);
4679   } else {
4680     // worse case scenario, all regs in upper bank
4681     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4682     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4683     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4684     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4685   }
4686 }
4687 
4688 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4689   int dst_enc = dst->encoding();
4690   int nds_enc = nds->encoding();
4691   int src_enc = src->encoding();
4692   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4693     Assembler::vpsubw(dst, nds, src, vector_len);
4694   } else if ((dst_enc < 16) && (src_enc < 16)) {
4695     Assembler::vpsubw(dst, dst, src, vector_len);
4696   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4697     // use nds as scratch for src
4698     evmovdqul(nds, src, Assembler::AVX_512bit);
4699     Assembler::vpsubw(dst, dst, nds, vector_len);
4700   } else if ((src_enc < 16) && (nds_enc < 16)) {
4701     // use nds as scratch for dst
4702     evmovdqul(nds, dst, Assembler::AVX_512bit);
4703     Assembler::vpsubw(nds, nds, src, vector_len);
4704     evmovdqul(dst, nds, Assembler::AVX_512bit);
4705   } else if (dst_enc < 16) {
4706     // use nds as scatch for xmm0 to hold src
4707     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4708     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4709     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4710     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4711   } else {
4712     // worse case scenario, all regs are in the upper bank
4713     subptr(rsp, 64);
4714     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4715     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4716     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4717     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4718     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4719     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4720     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4721     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4722     addptr(rsp, 64);
4723   }
4724 }
4725 
4726 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4727   int dst_enc = dst->encoding();
4728   int nds_enc = nds->encoding();
4729   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4730     Assembler::vpsubw(dst, nds, src, vector_len);
4731   } else if (dst_enc < 16) {
4732     Assembler::vpsubw(dst, dst, src, vector_len);
4733   } else if (nds_enc < 16) {
4734     // implies dst_enc in upper bank with src as scratch
4735     evmovdqul(nds, dst, Assembler::AVX_512bit);
4736     Assembler::vpsubw(nds, nds, src, vector_len);
4737     evmovdqul(dst, nds, Assembler::AVX_512bit);
4738   } else {
4739     // worse case scenario, all regs in upper bank
4740     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4741     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4742     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4743     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4744   }
4745 }
4746 
4747 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4748   int dst_enc = dst->encoding();
4749   int nds_enc = nds->encoding();
4750   int shift_enc = shift->encoding();
4751   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4752     Assembler::vpsraw(dst, nds, shift, vector_len);
4753   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4754     Assembler::vpsraw(dst, dst, shift, vector_len);
4755   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4756     // use nds_enc as scratch with shift
4757     evmovdqul(nds, shift, Assembler::AVX_512bit);
4758     Assembler::vpsraw(dst, dst, nds, vector_len);
4759   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4760     // use nds as scratch with dst
4761     evmovdqul(nds, dst, Assembler::AVX_512bit);
4762     Assembler::vpsraw(nds, nds, shift, vector_len);
4763     evmovdqul(dst, nds, Assembler::AVX_512bit);
4764   } else if (dst_enc < 16) {
4765     // use nds to save a copy of xmm0 and hold shift
4766     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4767     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4768     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4769     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4770   } else if (nds_enc < 16) {
4771     // use nds as dest as temps
4772     evmovdqul(nds, dst, Assembler::AVX_512bit);
4773     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4774     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4775     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4776     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4777     evmovdqul(dst, nds, Assembler::AVX_512bit);
4778   } else {
4779     // worse case scenario, all regs are in the upper bank
4780     subptr(rsp, 64);
4781     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4782     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4783     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4784     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4785     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4786     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4787     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4788     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4789     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4790     addptr(rsp, 64);
4791   }
4792 }
4793 
4794 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4795   int dst_enc = dst->encoding();
4796   int nds_enc = nds->encoding();
4797   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4798     Assembler::vpsraw(dst, nds, shift, vector_len);
4799   } else if (dst_enc < 16) {
4800     Assembler::vpsraw(dst, dst, shift, vector_len);
4801   } else if (nds_enc < 16) {
4802     // use nds as scratch
4803     evmovdqul(nds, dst, Assembler::AVX_512bit);
4804     Assembler::vpsraw(nds, nds, shift, vector_len);
4805     evmovdqul(dst, nds, Assembler::AVX_512bit);
4806   } else {
4807     // use nds as scratch for xmm0
4808     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4809     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4810     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4811     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4812   }
4813 }
4814 
4815 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4816   int dst_enc = dst->encoding();
4817   int nds_enc = nds->encoding();
4818   int shift_enc = shift->encoding();
4819   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4820     Assembler::vpsrlw(dst, nds, shift, vector_len);
4821   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4822     Assembler::vpsrlw(dst, dst, shift, vector_len);
4823   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4824     // use nds_enc as scratch with shift
4825     evmovdqul(nds, shift, Assembler::AVX_512bit);
4826     Assembler::vpsrlw(dst, dst, nds, vector_len);
4827   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4828     // use nds as scratch with dst
4829     evmovdqul(nds, dst, Assembler::AVX_512bit);
4830     Assembler::vpsrlw(nds, nds, shift, vector_len);
4831     evmovdqul(dst, nds, Assembler::AVX_512bit);
4832   } else if (dst_enc < 16) {
4833     // use nds to save a copy of xmm0 and hold shift
4834     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4835     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4836     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4837     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4838   } else if (nds_enc < 16) {
4839     // use nds as dest as temps
4840     evmovdqul(nds, dst, Assembler::AVX_512bit);
4841     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4842     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4843     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4844     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4845     evmovdqul(dst, nds, Assembler::AVX_512bit);
4846   } else {
4847     // worse case scenario, all regs are in the upper bank
4848     subptr(rsp, 64);
4849     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4850     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4851     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4852     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4853     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4854     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4855     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4856     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4857     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4858     addptr(rsp, 64);
4859   }
4860 }
4861 
4862 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4863   int dst_enc = dst->encoding();
4864   int nds_enc = nds->encoding();
4865   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4866     Assembler::vpsrlw(dst, nds, shift, vector_len);
4867   } else if (dst_enc < 16) {
4868     Assembler::vpsrlw(dst, dst, shift, vector_len);
4869   } else if (nds_enc < 16) {
4870     // use nds as scratch
4871     evmovdqul(nds, dst, Assembler::AVX_512bit);
4872     Assembler::vpsrlw(nds, nds, shift, vector_len);
4873     evmovdqul(dst, nds, Assembler::AVX_512bit);
4874   } else {
4875     // use nds as scratch for xmm0
4876     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4877     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4878     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4879     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4880   }
4881 }
4882 
4883 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4884   int dst_enc = dst->encoding();
4885   int nds_enc = nds->encoding();
4886   int shift_enc = shift->encoding();
4887   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4888     Assembler::vpsllw(dst, nds, shift, vector_len);
4889   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4890     Assembler::vpsllw(dst, dst, shift, vector_len);
4891   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4892     // use nds_enc as scratch with shift
4893     evmovdqul(nds, shift, Assembler::AVX_512bit);
4894     Assembler::vpsllw(dst, dst, nds, vector_len);
4895   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4896     // use nds as scratch with dst
4897     evmovdqul(nds, dst, Assembler::AVX_512bit);
4898     Assembler::vpsllw(nds, nds, shift, vector_len);
4899     evmovdqul(dst, nds, Assembler::AVX_512bit);
4900   } else if (dst_enc < 16) {
4901     // use nds to save a copy of xmm0 and hold shift
4902     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4903     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4904     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4905     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4906   } else if (nds_enc < 16) {
4907     // use nds as dest as temps
4908     evmovdqul(nds, dst, Assembler::AVX_512bit);
4909     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4910     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4911     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4912     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4913     evmovdqul(dst, nds, Assembler::AVX_512bit);
4914   } else {
4915     // worse case scenario, all regs are in the upper bank
4916     subptr(rsp, 64);
4917     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4918     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4919     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4920     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4921     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4922     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4923     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4924     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4925     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4926     addptr(rsp, 64);
4927   }
4928 }
4929 
4930 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4931   int dst_enc = dst->encoding();
4932   int nds_enc = nds->encoding();
4933   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4934     Assembler::vpsllw(dst, nds, shift, vector_len);
4935   } else if (dst_enc < 16) {
4936     Assembler::vpsllw(dst, dst, shift, vector_len);
4937   } else if (nds_enc < 16) {
4938     // use nds as scratch
4939     evmovdqul(nds, dst, Assembler::AVX_512bit);
4940     Assembler::vpsllw(nds, nds, shift, vector_len);
4941     evmovdqul(dst, nds, Assembler::AVX_512bit);
4942   } else {
4943     // use nds as scratch for xmm0
4944     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4945     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4946     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4947     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4948   }
4949 }
4950 
4951 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4952   int dst_enc = dst->encoding();
4953   int src_enc = src->encoding();
4954   if ((dst_enc < 16) && (src_enc < 16)) {
4955     Assembler::vptest(dst, src);
4956   } else if (src_enc < 16) {
4957     subptr(rsp, 64);
4958     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4959     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4960     Assembler::vptest(xmm0, src);
4961     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4962     addptr(rsp, 64);
4963   } else if (dst_enc < 16) {
4964     subptr(rsp, 64);
4965     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4966     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4967     Assembler::vptest(dst, xmm0);
4968     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4969     addptr(rsp, 64);
4970   } else {
4971     subptr(rsp, 64);
4972     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4973     subptr(rsp, 64);
4974     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4975     movdqu(xmm0, src);
4976     movdqu(xmm1, dst);
4977     Assembler::vptest(xmm1, xmm0);
4978     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4979     addptr(rsp, 64);
4980     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4981     addptr(rsp, 64);
4982   }
4983 }
4984 
4985 // This instruction exists within macros, ergo we cannot control its input
4986 // when emitted through those patterns.
4987 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4988   if (VM_Version::supports_avx512nobw()) {
4989     int dst_enc = dst->encoding();
4990     int src_enc = src->encoding();
4991     if (dst_enc == src_enc) {
4992       if (dst_enc < 16) {
4993         Assembler::punpcklbw(dst, src);
4994       } else {
4995         subptr(rsp, 64);
4996         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4997         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4998         Assembler::punpcklbw(xmm0, xmm0);
4999         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5000         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5001         addptr(rsp, 64);
5002       }
5003     } else {
5004       if ((src_enc < 16) && (dst_enc < 16)) {
5005         Assembler::punpcklbw(dst, src);
5006       } else if (src_enc < 16) {
5007         subptr(rsp, 64);
5008         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5009         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5010         Assembler::punpcklbw(xmm0, src);
5011         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5012         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5013         addptr(rsp, 64);
5014       } else if (dst_enc < 16) {
5015         subptr(rsp, 64);
5016         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5017         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5018         Assembler::punpcklbw(dst, xmm0);
5019         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5020         addptr(rsp, 64);
5021       } else {
5022         subptr(rsp, 64);
5023         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5024         subptr(rsp, 64);
5025         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5026         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5027         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5028         Assembler::punpcklbw(xmm0, xmm1);
5029         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5030         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5031         addptr(rsp, 64);
5032         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5033         addptr(rsp, 64);
5034       }
5035     }
5036   } else {
5037     Assembler::punpcklbw(dst, src);
5038   }
5039 }
5040 
5041 // This instruction exists within macros, ergo we cannot control its input
5042 // when emitted through those patterns.
5043 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5044   if (VM_Version::supports_avx512nobw()) {
5045     int dst_enc = dst->encoding();
5046     int src_enc = src->encoding();
5047     if (dst_enc == src_enc) {
5048       if (dst_enc < 16) {
5049         Assembler::pshuflw(dst, src, mode);
5050       } else {
5051         subptr(rsp, 64);
5052         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5053         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5054         Assembler::pshuflw(xmm0, xmm0, mode);
5055         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5056         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5057         addptr(rsp, 64);
5058       }
5059     } else {
5060       if ((src_enc < 16) && (dst_enc < 16)) {
5061         Assembler::pshuflw(dst, src, mode);
5062       } else if (src_enc < 16) {
5063         subptr(rsp, 64);
5064         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5066         Assembler::pshuflw(xmm0, src, mode);
5067         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5068         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5069         addptr(rsp, 64);
5070       } else if (dst_enc < 16) {
5071         subptr(rsp, 64);
5072         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5073         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5074         Assembler::pshuflw(dst, xmm0, mode);
5075         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5076         addptr(rsp, 64);
5077       } else {
5078         subptr(rsp, 64);
5079         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5080         subptr(rsp, 64);
5081         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5082         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5083         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5084         Assembler::pshuflw(xmm0, xmm1, mode);
5085         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5086         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5087         addptr(rsp, 64);
5088         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5089         addptr(rsp, 64);
5090       }
5091     }
5092   } else {
5093     Assembler::pshuflw(dst, src, mode);
5094   }
5095 }
5096 
5097 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5098   if (reachable(src)) {
5099     vandpd(dst, nds, as_Address(src), vector_len);
5100   } else {
5101     lea(rscratch1, src);
5102     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5103   }
5104 }
5105 
5106 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5107   if (reachable(src)) {
5108     vandps(dst, nds, as_Address(src), vector_len);
5109   } else {
5110     lea(rscratch1, src);
5111     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5112   }
5113 }
5114 
5115 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5116   if (reachable(src)) {
5117     vdivsd(dst, nds, as_Address(src));
5118   } else {
5119     lea(rscratch1, src);
5120     vdivsd(dst, nds, Address(rscratch1, 0));
5121   }
5122 }
5123 
5124 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5125   if (reachable(src)) {
5126     vdivss(dst, nds, as_Address(src));
5127   } else {
5128     lea(rscratch1, src);
5129     vdivss(dst, nds, Address(rscratch1, 0));
5130   }
5131 }
5132 
5133 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5134   if (reachable(src)) {
5135     vmulsd(dst, nds, as_Address(src));
5136   } else {
5137     lea(rscratch1, src);
5138     vmulsd(dst, nds, Address(rscratch1, 0));
5139   }
5140 }
5141 
5142 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5143   if (reachable(src)) {
5144     vmulss(dst, nds, as_Address(src));
5145   } else {
5146     lea(rscratch1, src);
5147     vmulss(dst, nds, Address(rscratch1, 0));
5148   }
5149 }
5150 
5151 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5152   if (reachable(src)) {
5153     vsubsd(dst, nds, as_Address(src));
5154   } else {
5155     lea(rscratch1, src);
5156     vsubsd(dst, nds, Address(rscratch1, 0));
5157   }
5158 }
5159 
5160 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5161   if (reachable(src)) {
5162     vsubss(dst, nds, as_Address(src));
5163   } else {
5164     lea(rscratch1, src);
5165     vsubss(dst, nds, Address(rscratch1, 0));
5166   }
5167 }
5168 
5169 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5170   int nds_enc = nds->encoding();
5171   int dst_enc = dst->encoding();
5172   bool dst_upper_bank = (dst_enc > 15);
5173   bool nds_upper_bank = (nds_enc > 15);
5174   if (VM_Version::supports_avx512novl() &&
5175       (nds_upper_bank || dst_upper_bank)) {
5176     if (dst_upper_bank) {
5177       subptr(rsp, 64);
5178       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5179       movflt(xmm0, nds);
5180       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5181       movflt(dst, xmm0);
5182       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5183       addptr(rsp, 64);
5184     } else {
5185       movflt(dst, nds);
5186       vxorps(dst, dst, src, Assembler::AVX_128bit);
5187     }
5188   } else {
5189     vxorps(dst, nds, src, Assembler::AVX_128bit);
5190   }
5191 }
5192 
5193 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5194   int nds_enc = nds->encoding();
5195   int dst_enc = dst->encoding();
5196   bool dst_upper_bank = (dst_enc > 15);
5197   bool nds_upper_bank = (nds_enc > 15);
5198   if (VM_Version::supports_avx512novl() &&
5199       (nds_upper_bank || dst_upper_bank)) {
5200     if (dst_upper_bank) {
5201       subptr(rsp, 64);
5202       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5203       movdbl(xmm0, nds);
5204       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5205       movdbl(dst, xmm0);
5206       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5207       addptr(rsp, 64);
5208     } else {
5209       movdbl(dst, nds);
5210       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5211     }
5212   } else {
5213     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5214   }
5215 }
5216 
5217 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5218   if (reachable(src)) {
5219     vxorpd(dst, nds, as_Address(src), vector_len);
5220   } else {
5221     lea(rscratch1, src);
5222     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5223   }
5224 }
5225 
5226 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5227   if (reachable(src)) {
5228     vxorps(dst, nds, as_Address(src), vector_len);
5229   } else {
5230     lea(rscratch1, src);
5231     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5232   }
5233 }
5234 
5235 
5236 //////////////////////////////////////////////////////////////////////////////////
5237 #if INCLUDE_ALL_GCS
5238 
5239 void MacroAssembler::g1_write_barrier_pre(Register obj,
5240                                           Register pre_val,
5241                                           Register thread,
5242                                           Register tmp,
5243                                           bool tosca_live,
5244                                           bool expand_call) {
5245 
5246   // If expand_call is true then we expand the call_VM_leaf macro
5247   // directly to skip generating the check by
5248   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5249 
5250 #ifdef _LP64
5251   assert(thread == r15_thread, "must be");
5252 #endif // _LP64
5253 
5254   Label done;
5255   Label runtime;
5256 
5257   assert(pre_val != noreg, "check this code");
5258 
5259   if (obj != noreg) {
5260     assert_different_registers(obj, pre_val, tmp);
5261     assert(pre_val != rax, "check this code");
5262   }
5263 
5264   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5265                                        SATBMarkQueue::byte_offset_of_active()));
5266   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5267                                        SATBMarkQueue::byte_offset_of_index()));
5268   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5269                                        SATBMarkQueue::byte_offset_of_buf()));
5270 
5271 
5272   // Is marking active?
5273   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5274     cmpl(in_progress, 0);
5275   } else {
5276     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5277     cmpb(in_progress, 0);
5278   }
5279   jcc(Assembler::equal, done);
5280 
5281   // Do we need to load the previous value?
5282   if (obj != noreg) {
5283     load_heap_oop(pre_val, Address(obj, 0));
5284   }
5285 
5286   // Is the previous value null?
5287   cmpptr(pre_val, (int32_t) NULL_WORD);
5288   jcc(Assembler::equal, done);
5289 
5290   // Can we store original value in the thread's buffer?
5291   // Is index == 0?
5292   // (The index field is typed as size_t.)
5293 
5294   movptr(tmp, index);                   // tmp := *index_adr
5295   cmpptr(tmp, 0);                       // tmp == 0?
5296   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5297 
5298   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5299   movptr(index, tmp);                   // *index_adr := tmp
5300   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5301 
5302   // Record the previous value
5303   movptr(Address(tmp, 0), pre_val);
5304   jmp(done);
5305 
5306   bind(runtime);
5307   // save the live input values
5308   if(tosca_live) push(rax);
5309 
5310   if (obj != noreg && obj != rax)
5311     push(obj);
5312 
5313   if (pre_val != rax)
5314     push(pre_val);
5315 
5316   // Calling the runtime using the regular call_VM_leaf mechanism generates
5317   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5318   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5319   //
5320   // If we care generating the pre-barrier without a frame (e.g. in the
5321   // intrinsified Reference.get() routine) then ebp might be pointing to
5322   // the caller frame and so this check will most likely fail at runtime.
5323   //
5324   // Expanding the call directly bypasses the generation of the check.
5325   // So when we do not have have a full interpreter frame on the stack
5326   // expand_call should be passed true.
5327 
5328   NOT_LP64( push(thread); )
5329 
5330   if (expand_call) {
5331     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5332     pass_arg1(this, thread);
5333     pass_arg0(this, pre_val);
5334     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5335   } else {
5336     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5337   }
5338 
5339   NOT_LP64( pop(thread); )
5340 
5341   // save the live input values
5342   if (pre_val != rax)
5343     pop(pre_val);
5344 
5345   if (obj != noreg && obj != rax)
5346     pop(obj);
5347 
5348   if(tosca_live) pop(rax);
5349 
5350   bind(done);
5351 }
5352 
5353 void MacroAssembler::shenandoah_write_barrier_post(Register store_addr,
5354                                                    Register new_val,
5355                                                    Register thread,
5356                                                    Register tmp,
5357                                                    Register tmp2) {
5358   assert(UseShenandoahGC, "why else should we be here?");
5359 
5360   if (! UseShenandoahMatrix) {
5361     // No need for that barrier if not using matrix.
5362     return;
5363   }
5364 
5365   Label done;
5366   testptr(new_val, new_val);
5367   jcc(Assembler::zero, done);
5368   ShenandoahConnectionMatrix* matrix = ShenandoahHeap::heap()->connection_matrix();
5369   address matrix_addr = matrix->matrix_addr();
5370   movptr(rscratch1, (intptr_t) ShenandoahHeap::heap()->first_region_bottom());
5371   // Compute from-region index
5372   movptr(tmp, store_addr);
5373   subptr(tmp, rscratch1);
5374   shrptr(tmp, ShenandoahHeapRegion::RegionSizeShift);
5375   // Compute to-region index
5376   movptr(tmp2, new_val);
5377   subptr(tmp2, rscratch1);
5378   shrptr(tmp2, ShenandoahHeapRegion::RegionSizeShift);
5379   // Compute matrix index
5380   imulq(tmp, tmp, matrix->stride());
5381   addq(tmp, tmp2);
5382   movptr(rscratch1, (intptr_t) matrix_addr);
5383   // Store true at _matrix[from * stride + to]
5384   //movb(Address(rscratch1, tmp, Address::times_1), 3 /*true*/);
5385   movbool(Address(rscratch1, tmp, Address::times_1), true);
5386   bind(done);
5387 }
5388 
5389 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5390                                            Register new_val,
5391                                            Register thread,
5392                                            Register tmp,
5393                                            Register tmp2) {
5394 #ifdef _LP64
5395   assert(thread == r15_thread, "must be");
5396 #endif // _LP64
5397 
5398   assert(UseG1GC, "expect G1 GC");
5399 
5400   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5401                                        DirtyCardQueue::byte_offset_of_index()));
5402   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5403                                        DirtyCardQueue::byte_offset_of_buf()));
5404 
5405   CardTableModRefBS* ct =
5406     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5407   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5408 
5409   Label done;
5410   Label runtime;
5411 
5412   // Does store cross heap regions?
5413 
5414   movptr(tmp, store_addr);
5415   xorptr(tmp, new_val);
5416   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5417   jcc(Assembler::equal, done);
5418 
5419   // crosses regions, storing NULL?
5420 
5421   cmpptr(new_val, (int32_t) NULL_WORD);
5422   jcc(Assembler::equal, done);
5423 
5424   // storing region crossing non-NULL, is card already dirty?
5425 
5426   const Register card_addr = tmp;
5427   const Register cardtable = tmp2;
5428 
5429   movptr(card_addr, store_addr);
5430   shrptr(card_addr, CardTableModRefBS::card_shift);
5431   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5432   // a valid address and therefore is not properly handled by the relocation code.
5433   movptr(cardtable, (intptr_t)ct->byte_map_base);
5434   addptr(card_addr, cardtable);
5435 
5436   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5437   jcc(Assembler::equal, done);
5438 
5439   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5440   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5441   jcc(Assembler::equal, done);
5442 
5443 
5444   // storing a region crossing, non-NULL oop, card is clean.
5445   // dirty card and log.
5446 
5447   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5448 
5449   cmpl(queue_index, 0);
5450   jcc(Assembler::equal, runtime);
5451   subl(queue_index, wordSize);
5452   movptr(tmp2, buffer);
5453 #ifdef _LP64
5454   movslq(rscratch1, queue_index);
5455   addq(tmp2, rscratch1);
5456   movq(Address(tmp2, 0), card_addr);
5457 #else
5458   addl(tmp2, queue_index);
5459   movl(Address(tmp2, 0), card_addr);
5460 #endif
5461   jmp(done);
5462 
5463   bind(runtime);
5464   // save the live input values
5465   push(store_addr);
5466   push(new_val);
5467 #ifdef _LP64
5468   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5469 #else
5470   push(thread);
5471   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5472   pop(thread);
5473 #endif
5474   pop(new_val);
5475   pop(store_addr);
5476 
5477   bind(done);
5478 }
5479 
5480 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5481   assert(UseShenandoahGC, "must only be called with Shenandoah GC active");
5482   assert(ShenandoahWriteBarrier, "must only be called when write barriers are enabled");
5483 
5484   Label done;
5485 
5486   // Check for evacuation-in-progress
5487   Address evacuation_in_progress = Address(r15_thread, in_bytes(JavaThread::evacuation_in_progress_offset()));
5488   cmpb(evacuation_in_progress, 0);
5489 
5490   // The read-barrier.
5491   movptr(dst, Address(dst, BrooksPointer::byte_offset()));
5492 
5493   jccb(Assembler::equal, done);
5494 
5495   if (dst != rax) {
5496     xchgptr(dst, rax); // Move obj into rax and save rax into obj.
5497   }
5498 
5499   assert(StubRoutines::x86::shenandoah_wb() != NULL, "need write barrier stub");
5500   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::shenandoah_wb())));
5501 
5502   if (dst != rax) {
5503     xchgptr(rax, dst); // Swap back obj with rax.
5504   }
5505 
5506   bind(done);
5507 }
5508 
5509 #endif // INCLUDE_ALL_GCS
5510 //////////////////////////////////////////////////////////////////////////////////
5511 
5512 
5513 void MacroAssembler::store_check(Register obj, Address dst) {
5514   store_check(obj);
5515 }
5516 
5517 void MacroAssembler::store_check(Register obj) {
5518   // Does a store check for the oop in register obj. The content of
5519   // register obj is destroyed afterwards.
5520   BarrierSet* bs = Universe::heap()->barrier_set();
5521   assert(bs->kind() == BarrierSet::CardTableForRS ||
5522          bs->kind() == BarrierSet::CardTableExtension,
5523          "Wrong barrier set kind");
5524 
5525   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5526   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5527 
5528   shrptr(obj, CardTableModRefBS::card_shift);
5529 
5530   Address card_addr;
5531 
5532   // The calculation for byte_map_base is as follows:
5533   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5534   // So this essentially converts an address to a displacement and it will
5535   // never need to be relocated. On 64bit however the value may be too
5536   // large for a 32bit displacement.
5537   intptr_t disp = (intptr_t) ct->byte_map_base;
5538   if (is_simm32(disp)) {
5539     card_addr = Address(noreg, obj, Address::times_1, disp);
5540   } else {
5541     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5542     // displacement and done in a single instruction given favorable mapping and a
5543     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5544     // entry and that entry is not properly handled by the relocation code.
5545     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5546     Address index(noreg, obj, Address::times_1);
5547     card_addr = as_Address(ArrayAddress(cardtable, index));
5548   }
5549 
5550   int dirty = CardTableModRefBS::dirty_card_val();
5551   if (UseCondCardMark) {
5552     Label L_already_dirty;
5553     if (UseConcMarkSweepGC) {
5554       membar(Assembler::StoreLoad);
5555     }
5556     cmpb(card_addr, dirty);
5557     jcc(Assembler::equal, L_already_dirty);
5558     movb(card_addr, dirty);
5559     bind(L_already_dirty);
5560   } else {
5561     movb(card_addr, dirty);
5562   }
5563 }
5564 
5565 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5566   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5567 }
5568 
5569 // Force generation of a 4 byte immediate value even if it fits into 8bit
5570 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5571   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5572 }
5573 
5574 void MacroAssembler::subptr(Register dst, Register src) {
5575   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5576 }
5577 
5578 // C++ bool manipulation
5579 void MacroAssembler::testbool(Register dst) {
5580   if(sizeof(bool) == 1)
5581     testb(dst, 0xff);
5582   else if(sizeof(bool) == 2) {
5583     // testw implementation needed for two byte bools
5584     ShouldNotReachHere();
5585   } else if(sizeof(bool) == 4)
5586     testl(dst, dst);
5587   else
5588     // unsupported
5589     ShouldNotReachHere();
5590 }
5591 
5592 void MacroAssembler::testptr(Register dst, Register src) {
5593   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5594 }
5595 
5596 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5597 void MacroAssembler::tlab_allocate(Register obj,
5598                                    Register var_size_in_bytes,
5599                                    int con_size_in_bytes,
5600                                    Register t1,
5601                                    Register t2,
5602                                    Label& slow_case) {
5603   assert_different_registers(obj, t1, t2);
5604   assert_different_registers(obj, var_size_in_bytes, t1);
5605   Register end = t2;
5606   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5607 
5608   verify_tlab();
5609 
5610   NOT_LP64(get_thread(thread));
5611 
5612   uint oop_extra_words = Universe::heap()->oop_extra_words();
5613 
5614   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5615   if (var_size_in_bytes == noreg) {
5616     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5617   } else {
5618     if (oop_extra_words > 0) {
5619       addq(var_size_in_bytes, oop_extra_words * HeapWordSize);
5620     }
5621     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5622   }
5623   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5624   jcc(Assembler::above, slow_case);
5625 
5626   // update the tlab top pointer
5627   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5628 
5629   Universe::heap()->compile_prepare_oop(this, obj);
5630 
5631   // recover var_size_in_bytes if necessary
5632   if (var_size_in_bytes == end) {
5633     subptr(var_size_in_bytes, obj);
5634   }
5635   verify_tlab();
5636 }
5637 
5638 // Preserves rbx, and rdx.
5639 Register MacroAssembler::tlab_refill(Label& retry,
5640                                      Label& try_eden,
5641                                      Label& slow_case) {
5642   Register top = rax;
5643   Register t1  = rcx; // object size
5644   Register t2  = rsi;
5645   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5646   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5647   Label do_refill, discard_tlab;
5648 
5649   if (!Universe::heap()->supports_inline_contig_alloc()) {
5650     // No allocation in the shared eden.
5651     jmp(slow_case);
5652   }
5653 
5654   NOT_LP64(get_thread(thread_reg));
5655 
5656   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5657   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5658 
5659   // calculate amount of free space
5660   subptr(t1, top);
5661   shrptr(t1, LogHeapWordSize);
5662 
5663   // Retain tlab and allocate object in shared space if
5664   // the amount free in the tlab is too large to discard.
5665   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5666   jcc(Assembler::lessEqual, discard_tlab);
5667 
5668   // Retain
5669   // %%% yuck as movptr...
5670   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5671   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5672   if (TLABStats) {
5673     // increment number of slow_allocations
5674     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5675   }
5676   jmp(try_eden);
5677 
5678   bind(discard_tlab);
5679   if (TLABStats) {
5680     // increment number of refills
5681     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5682     // accumulate wastage -- t1 is amount free in tlab
5683     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5684   }
5685 
5686   // if tlab is currently allocated (top or end != null) then
5687   // fill [top, end + alignment_reserve) with array object
5688   testptr(top, top);
5689   jcc(Assembler::zero, do_refill);
5690 
5691   // set up the mark word
5692   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5693   // set the length to the remaining space
5694   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5695   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5696   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5697   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5698   // set klass to intArrayKlass
5699   // dubious reloc why not an oop reloc?
5700   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5701   // store klass last.  concurrent gcs assumes klass length is valid if
5702   // klass field is not null.
5703   store_klass(top, t1);
5704 
5705   movptr(t1, top);
5706   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5707   incr_allocated_bytes(thread_reg, t1, 0);
5708 
5709   // refill the tlab with an eden allocation
5710   bind(do_refill);
5711   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5712   shlptr(t1, LogHeapWordSize);
5713   // allocate new tlab, address returned in top
5714   eden_allocate(top, t1, 0, t2, slow_case);
5715 
5716   // Check that t1 was preserved in eden_allocate.
5717 #ifdef ASSERT
5718   if (UseTLAB) {
5719     Label ok;
5720     Register tsize = rsi;
5721     assert_different_registers(tsize, thread_reg, t1);
5722     push(tsize);
5723     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5724     shlptr(tsize, LogHeapWordSize);
5725     cmpptr(t1, tsize);
5726     jcc(Assembler::equal, ok);
5727     STOP("assert(t1 != tlab size)");
5728     should_not_reach_here();
5729 
5730     bind(ok);
5731     pop(tsize);
5732   }
5733 #endif
5734   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5735   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5736   addptr(top, t1);
5737   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5738   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5739 
5740   if (ZeroTLAB) {
5741     // This is a fast TLAB refill, therefore the GC is not notified of it.
5742     // So compiled code must fill the new TLAB with zeroes.
5743     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5744     zero_memory(top, t1, 0, t2);
5745   }
5746 
5747   verify_tlab();
5748   jmp(retry);
5749 
5750   return thread_reg; // for use by caller
5751 }
5752 
5753 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5754 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5755   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5756   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5757   Label done;
5758 
5759   testptr(length_in_bytes, length_in_bytes);
5760   jcc(Assembler::zero, done);
5761 
5762   // initialize topmost word, divide index by 2, check if odd and test if zero
5763   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5764 #ifdef ASSERT
5765   {
5766     Label L;
5767     testptr(length_in_bytes, BytesPerWord - 1);
5768     jcc(Assembler::zero, L);
5769     stop("length must be a multiple of BytesPerWord");
5770     bind(L);
5771   }
5772 #endif
5773   Register index = length_in_bytes;
5774   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5775   if (UseIncDec) {
5776     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5777   } else {
5778     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5779     shrptr(index, 1);
5780   }
5781 #ifndef _LP64
5782   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5783   {
5784     Label even;
5785     // note: if index was a multiple of 8, then it cannot
5786     //       be 0 now otherwise it must have been 0 before
5787     //       => if it is even, we don't need to check for 0 again
5788     jcc(Assembler::carryClear, even);
5789     // clear topmost word (no jump would be needed if conditional assignment worked here)
5790     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5791     // index could be 0 now, must check again
5792     jcc(Assembler::zero, done);
5793     bind(even);
5794   }
5795 #endif // !_LP64
5796   // initialize remaining object fields: index is a multiple of 2 now
5797   {
5798     Label loop;
5799     bind(loop);
5800     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5801     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5802     decrement(index);
5803     jcc(Assembler::notZero, loop);
5804   }
5805 
5806   bind(done);
5807 }
5808 
5809 void MacroAssembler::incr_allocated_bytes(Register thread,
5810                                           Register var_size_in_bytes,
5811                                           int con_size_in_bytes,
5812                                           Register t1) {
5813   if (!thread->is_valid()) {
5814 #ifdef _LP64
5815     thread = r15_thread;
5816 #else
5817     assert(t1->is_valid(), "need temp reg");
5818     thread = t1;
5819     get_thread(thread);
5820 #endif
5821   }
5822 
5823 #ifdef _LP64
5824   if (var_size_in_bytes->is_valid()) {
5825     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5826   } else {
5827     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5828   }
5829 #else
5830   if (var_size_in_bytes->is_valid()) {
5831     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5832   } else {
5833     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5834   }
5835   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5836 #endif
5837 }
5838 
5839 // Look up the method for a megamorphic invokeinterface call.
5840 // The target method is determined by <intf_klass, itable_index>.
5841 // The receiver klass is in recv_klass.
5842 // On success, the result will be in method_result, and execution falls through.
5843 // On failure, execution transfers to the given label.
5844 void MacroAssembler::lookup_interface_method(Register recv_klass,
5845                                              Register intf_klass,
5846                                              RegisterOrConstant itable_index,
5847                                              Register method_result,
5848                                              Register scan_temp,
5849                                              Label& L_no_such_interface) {
5850   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5851   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5852          "caller must use same register for non-constant itable index as for method");
5853 
5854   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5855   int vtable_base = in_bytes(Klass::vtable_start_offset());
5856   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5857   int scan_step   = itableOffsetEntry::size() * wordSize;
5858   int vte_size    = vtableEntry::size_in_bytes();
5859   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5860   assert(vte_size == wordSize, "else adjust times_vte_scale");
5861 
5862   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5863 
5864   // %%% Could store the aligned, prescaled offset in the klassoop.
5865   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5866 
5867   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5868   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5869   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5870 
5871   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5872   //   if (scan->interface() == intf) {
5873   //     result = (klass + scan->offset() + itable_index);
5874   //   }
5875   // }
5876   Label search, found_method;
5877 
5878   for (int peel = 1; peel >= 0; peel--) {
5879     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5880     cmpptr(intf_klass, method_result);
5881 
5882     if (peel) {
5883       jccb(Assembler::equal, found_method);
5884     } else {
5885       jccb(Assembler::notEqual, search);
5886       // (invert the test to fall through to found_method...)
5887     }
5888 
5889     if (!peel)  break;
5890 
5891     bind(search);
5892 
5893     // Check that the previous entry is non-null.  A null entry means that
5894     // the receiver class doesn't implement the interface, and wasn't the
5895     // same as when the caller was compiled.
5896     testptr(method_result, method_result);
5897     jcc(Assembler::zero, L_no_such_interface);
5898     addptr(scan_temp, scan_step);
5899   }
5900 
5901   bind(found_method);
5902 
5903   // Got a hit.
5904   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5905   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5906 }
5907 
5908 
5909 // virtual method calling
5910 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5911                                            RegisterOrConstant vtable_index,
5912                                            Register method_result) {
5913   const int base = in_bytes(Klass::vtable_start_offset());
5914   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5915   Address vtable_entry_addr(recv_klass,
5916                             vtable_index, Address::times_ptr,
5917                             base + vtableEntry::method_offset_in_bytes());
5918   movptr(method_result, vtable_entry_addr);
5919 }
5920 
5921 
5922 void MacroAssembler::check_klass_subtype(Register sub_klass,
5923                            Register super_klass,
5924                            Register temp_reg,
5925                            Label& L_success) {
5926   Label L_failure;
5927   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5928   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5929   bind(L_failure);
5930 }
5931 
5932 
5933 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5934                                                    Register super_klass,
5935                                                    Register temp_reg,
5936                                                    Label* L_success,
5937                                                    Label* L_failure,
5938                                                    Label* L_slow_path,
5939                                         RegisterOrConstant super_check_offset) {
5940   assert_different_registers(sub_klass, super_klass, temp_reg);
5941   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5942   if (super_check_offset.is_register()) {
5943     assert_different_registers(sub_klass, super_klass,
5944                                super_check_offset.as_register());
5945   } else if (must_load_sco) {
5946     assert(temp_reg != noreg, "supply either a temp or a register offset");
5947   }
5948 
5949   Label L_fallthrough;
5950   int label_nulls = 0;
5951   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5952   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5953   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5954   assert(label_nulls <= 1, "at most one NULL in the batch");
5955 
5956   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5957   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5958   Address super_check_offset_addr(super_klass, sco_offset);
5959 
5960   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5961   // range of a jccb.  If this routine grows larger, reconsider at
5962   // least some of these.
5963 #define local_jcc(assembler_cond, label)                                \
5964   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5965   else                             jcc( assembler_cond, label) /*omit semi*/
5966 
5967   // Hacked jmp, which may only be used just before L_fallthrough.
5968 #define final_jmp(label)                                                \
5969   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5970   else                            jmp(label)                /*omit semi*/
5971 
5972   // If the pointers are equal, we are done (e.g., String[] elements).
5973   // This self-check enables sharing of secondary supertype arrays among
5974   // non-primary types such as array-of-interface.  Otherwise, each such
5975   // type would need its own customized SSA.
5976   // We move this check to the front of the fast path because many
5977   // type checks are in fact trivially successful in this manner,
5978   // so we get a nicely predicted branch right at the start of the check.
5979   cmpptr(sub_klass, super_klass);
5980   local_jcc(Assembler::equal, *L_success);
5981 
5982   // Check the supertype display:
5983   if (must_load_sco) {
5984     // Positive movl does right thing on LP64.
5985     movl(temp_reg, super_check_offset_addr);
5986     super_check_offset = RegisterOrConstant(temp_reg);
5987   }
5988   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5989   cmpptr(super_klass, super_check_addr); // load displayed supertype
5990 
5991   // This check has worked decisively for primary supers.
5992   // Secondary supers are sought in the super_cache ('super_cache_addr').
5993   // (Secondary supers are interfaces and very deeply nested subtypes.)
5994   // This works in the same check above because of a tricky aliasing
5995   // between the super_cache and the primary super display elements.
5996   // (The 'super_check_addr' can address either, as the case requires.)
5997   // Note that the cache is updated below if it does not help us find
5998   // what we need immediately.
5999   // So if it was a primary super, we can just fail immediately.
6000   // Otherwise, it's the slow path for us (no success at this point).
6001 
6002   if (super_check_offset.is_register()) {
6003     local_jcc(Assembler::equal, *L_success);
6004     cmpl(super_check_offset.as_register(), sc_offset);
6005     if (L_failure == &L_fallthrough) {
6006       local_jcc(Assembler::equal, *L_slow_path);
6007     } else {
6008       local_jcc(Assembler::notEqual, *L_failure);
6009       final_jmp(*L_slow_path);
6010     }
6011   } else if (super_check_offset.as_constant() == sc_offset) {
6012     // Need a slow path; fast failure is impossible.
6013     if (L_slow_path == &L_fallthrough) {
6014       local_jcc(Assembler::equal, *L_success);
6015     } else {
6016       local_jcc(Assembler::notEqual, *L_slow_path);
6017       final_jmp(*L_success);
6018     }
6019   } else {
6020     // No slow path; it's a fast decision.
6021     if (L_failure == &L_fallthrough) {
6022       local_jcc(Assembler::equal, *L_success);
6023     } else {
6024       local_jcc(Assembler::notEqual, *L_failure);
6025       final_jmp(*L_success);
6026     }
6027   }
6028 
6029   bind(L_fallthrough);
6030 
6031 #undef local_jcc
6032 #undef final_jmp
6033 }
6034 
6035 
6036 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6037                                                    Register super_klass,
6038                                                    Register temp_reg,
6039                                                    Register temp2_reg,
6040                                                    Label* L_success,
6041                                                    Label* L_failure,
6042                                                    bool set_cond_codes) {
6043   assert_different_registers(sub_klass, super_klass, temp_reg);
6044   if (temp2_reg != noreg)
6045     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6046 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6047 
6048   Label L_fallthrough;
6049   int label_nulls = 0;
6050   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6051   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6052   assert(label_nulls <= 1, "at most one NULL in the batch");
6053 
6054   // a couple of useful fields in sub_klass:
6055   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6056   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6057   Address secondary_supers_addr(sub_klass, ss_offset);
6058   Address super_cache_addr(     sub_klass, sc_offset);
6059 
6060   // Do a linear scan of the secondary super-klass chain.
6061   // This code is rarely used, so simplicity is a virtue here.
6062   // The repne_scan instruction uses fixed registers, which we must spill.
6063   // Don't worry too much about pre-existing connections with the input regs.
6064 
6065   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6066   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6067 
6068   // Get super_klass value into rax (even if it was in rdi or rcx).
6069   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6070   if (super_klass != rax || UseCompressedOops) {
6071     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6072     mov(rax, super_klass);
6073   }
6074   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6075   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6076 
6077 #ifndef PRODUCT
6078   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6079   ExternalAddress pst_counter_addr((address) pst_counter);
6080   NOT_LP64(  incrementl(pst_counter_addr) );
6081   LP64_ONLY( lea(rcx, pst_counter_addr) );
6082   LP64_ONLY( incrementl(Address(rcx, 0)) );
6083 #endif //PRODUCT
6084 
6085   // We will consult the secondary-super array.
6086   movptr(rdi, secondary_supers_addr);
6087   // Load the array length.  (Positive movl does right thing on LP64.)
6088   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6089   // Skip to start of data.
6090   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6091 
6092   // Scan RCX words at [RDI] for an occurrence of RAX.
6093   // Set NZ/Z based on last compare.
6094   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6095   // not change flags (only scas instruction which is repeated sets flags).
6096   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6097 
6098     testptr(rax,rax); // Set Z = 0
6099     repne_scan();
6100 
6101   // Unspill the temp. registers:
6102   if (pushed_rdi)  pop(rdi);
6103   if (pushed_rcx)  pop(rcx);
6104   if (pushed_rax)  pop(rax);
6105 
6106   if (set_cond_codes) {
6107     // Special hack for the AD files:  rdi is guaranteed non-zero.
6108     assert(!pushed_rdi, "rdi must be left non-NULL");
6109     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6110   }
6111 
6112   if (L_failure == &L_fallthrough)
6113         jccb(Assembler::notEqual, *L_failure);
6114   else  jcc(Assembler::notEqual, *L_failure);
6115 
6116   // Success.  Cache the super we found and proceed in triumph.
6117   movptr(super_cache_addr, super_klass);
6118 
6119   if (L_success != &L_fallthrough) {
6120     jmp(*L_success);
6121   }
6122 
6123 #undef IS_A_TEMP
6124 
6125   bind(L_fallthrough);
6126 }
6127 
6128 
6129 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6130   if (VM_Version::supports_cmov()) {
6131     cmovl(cc, dst, src);
6132   } else {
6133     Label L;
6134     jccb(negate_condition(cc), L);
6135     movl(dst, src);
6136     bind(L);
6137   }
6138 }
6139 
6140 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6141   if (VM_Version::supports_cmov()) {
6142     cmovl(cc, dst, src);
6143   } else {
6144     Label L;
6145     jccb(negate_condition(cc), L);
6146     movl(dst, src);
6147     bind(L);
6148   }
6149 }
6150 
6151 void MacroAssembler::verify_oop(Register reg, const char* s) {
6152   if (!VerifyOops) return;
6153 
6154   // Pass register number to verify_oop_subroutine
6155   const char* b = NULL;
6156   {
6157     ResourceMark rm;
6158     stringStream ss;
6159     ss.print("verify_oop: %s: %s", reg->name(), s);
6160     b = code_string(ss.as_string());
6161   }
6162   BLOCK_COMMENT("verify_oop {");
6163 #ifdef _LP64
6164   push(rscratch1);                    // save r10, trashed by movptr()
6165 #endif
6166   push(rax);                          // save rax,
6167   push(reg);                          // pass register argument
6168   ExternalAddress buffer((address) b);
6169   // avoid using pushptr, as it modifies scratch registers
6170   // and our contract is not to modify anything
6171   movptr(rax, buffer.addr());
6172   push(rax);
6173   // call indirectly to solve generation ordering problem
6174   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6175   call(rax);
6176   // Caller pops the arguments (oop, message) and restores rax, r10
6177   BLOCK_COMMENT("} verify_oop");
6178 }
6179 
6180 void MacroAssembler::in_heap_check(Register raddr, Register tmp, Label& done) {
6181   ShenandoahHeap *h = (ShenandoahHeap *)Universe::heap();
6182 
6183   HeapWord* first_region_bottom = h->first_region_bottom();
6184   HeapWord* last_region_end = first_region_bottom + (ShenandoahHeapRegion::RegionSizeBytes / HeapWordSize) * h->max_regions();
6185   guarantee(first_region_bottom < last_region_end, "sanity: %p < %p", first_region_bottom, last_region_end);
6186   movptr(tmp, (intptr_t) first_region_bottom);
6187   cmpptr(raddr, tmp);
6188   jcc(Assembler::below, done);
6189   movptr(tmp, (intptr_t) last_region_end);
6190   cmpptr(raddr, tmp);
6191   jcc(Assembler::aboveEqual, done);
6192 
6193 }
6194 
6195 void MacroAssembler::shenandoah_cset_check(Register raddr, Register tmp1, Register tmp2, Label& done) {
6196   // Test that oop is not in to-space.
6197   movptr(tmp1, raddr);
6198   shrptr(tmp1, ShenandoahHeapRegion::RegionSizeShift);
6199   movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
6200   movbool(tmp2, Address(tmp2, tmp1, Address::times_1));
6201   testbool(tmp2);
6202   jcc(Assembler::zero, done);
6203 
6204   // Check for cancelled GC.
6205   movptr(tmp2, (intptr_t) ShenandoahHeap::cancelled_concgc_addr());
6206   movbool(tmp2, Address(tmp2, 0));
6207   testbool(tmp2);
6208   jcc(Assembler::notZero, done);
6209 
6210 }
6211 
6212 void MacroAssembler::_shenandoah_store_addr_check(Address addr, const char* msg, const char* file, int line) {
6213   _shenandoah_store_addr_check(addr.base(), msg, file, line);
6214 }
6215 
6216 void MacroAssembler::_shenandoah_store_addr_check(Register dst, const char* msg, const char* file, int line) {
6217   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6218   if (dst == rsp) return; // Stack-based target
6219 
6220   Register raddr = r9;
6221   Register tmp1 = r10;
6222   Register tmp2 = r11;
6223 
6224   Label done;
6225 
6226   pushf();
6227   push(raddr);
6228   push(tmp1);
6229   push(tmp2);
6230 
6231   movptr(raddr, dst);
6232 
6233   // Check null.
6234   testptr(raddr, raddr);
6235   jcc(Assembler::zero, done);
6236 
6237   in_heap_check(raddr, tmp1, done);
6238   shenandoah_cset_check(raddr, tmp1, tmp2, done);
6239 
6240   // Fail.
6241   pop(tmp2);
6242   pop(tmp1);
6243   pop(raddr);
6244   popf();
6245   const char* b = NULL;
6246   {
6247     ResourceMark rm;
6248     stringStream ss;
6249     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
6250     b = code_string(ss.as_string());
6251   }
6252   stop(b);
6253 
6254   bind(done);
6255 
6256   pop(tmp2);
6257   pop(tmp1);
6258   pop(raddr);
6259   popf();
6260 }
6261 
6262 void MacroAssembler::_shenandoah_store_check(Register dst, Register value, const char* msg, const char* file, int line) {
6263   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6264   if (dst == rsp) return; // Stack-based target
6265 
6266   Register raddr = r8;
6267   Register rval =  r9;
6268   Register tmp1 = r10;
6269   Register tmp2 = r11;
6270 
6271   // Push tmp regs and flags.
6272   pushf();
6273   push(raddr);
6274   push(rval);
6275   push(tmp1);
6276   push(tmp2);
6277 
6278   movptr(raddr, dst);
6279   movptr(rval, value);
6280 
6281   Label done;
6282 
6283   // If not in-heap target, skip check.
6284   in_heap_check(raddr, tmp1, done);
6285 
6286   // Test that target oop is not in to-space.
6287   shenandoah_cset_check(raddr, tmp1, tmp2, done);
6288 
6289   // Do value-check only when concurrent mark is in progress.
6290   movptr(tmp1, (intptr_t) ShenandoahHeap::concurrent_mark_in_progress_addr());
6291   movbool(tmp1, Address(tmp1, 0));
6292   testbool(tmp1);
6293   jcc(Assembler::zero, done);
6294 
6295   // Null-check value.
6296   testptr(rval, rval);
6297   jcc(Assembler::zero, done);
6298 
6299   // Test that value oop is not in to-space.
6300   shenandoah_cset_check(rval, tmp1, tmp2, done);
6301 
6302   // Failure.
6303   // Pop tmp regs and flags.
6304   pop(tmp2);
6305   pop(tmp1);
6306   pop(rval);
6307   pop(raddr);
6308   popf();
6309   const char* b = NULL;
6310   {
6311     ResourceMark rm;
6312     stringStream ss;
6313     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
6314     b = code_string(ss.as_string());
6315   }
6316   stop(b);
6317 
6318   bind(done);
6319 
6320   // Pop tmp regs and flags.
6321   pop(tmp2);
6322   pop(tmp1);
6323   pop(rval);
6324   pop(raddr);
6325   popf();
6326 }
6327 
6328 void MacroAssembler::_shenandoah_store_check(Address addr, Register value, const char* msg, const char* file, int line) {
6329   _shenandoah_store_check(addr.base(), value, msg, file, line);
6330 }
6331 
6332 void MacroAssembler::_shenandoah_lock_check(Register dst, const char* msg, const char* file, int line) {
6333 #ifdef ASSERT
6334   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6335 
6336   push(r8);
6337   movptr(r8, Address(dst, BasicObjectLock::obj_offset_in_bytes()));
6338   _shenandoah_store_addr_check(r8, msg, file, line);
6339   pop(r8);
6340 #endif
6341 }
6342 
6343 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6344                                                       Register tmp,
6345                                                       int offset) {
6346   intptr_t value = *delayed_value_addr;
6347   if (value != 0)
6348     return RegisterOrConstant(value + offset);
6349 
6350   // load indirectly to solve generation ordering problem
6351   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6352 
6353 #ifdef ASSERT
6354   { Label L;
6355     testptr(tmp, tmp);
6356     if (WizardMode) {
6357       const char* buf = NULL;
6358       {
6359         ResourceMark rm;
6360         stringStream ss;
6361         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6362         buf = code_string(ss.as_string());
6363       }
6364       jcc(Assembler::notZero, L);
6365       STOP(buf);
6366     } else {
6367       jccb(Assembler::notZero, L);
6368       hlt();
6369     }
6370     bind(L);
6371   }
6372 #endif
6373 
6374   if (offset != 0)
6375     addptr(tmp, offset);
6376 
6377   return RegisterOrConstant(tmp);
6378 }
6379 
6380 
6381 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6382                                          int extra_slot_offset) {
6383   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6384   int stackElementSize = Interpreter::stackElementSize;
6385   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6386 #ifdef ASSERT
6387   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6388   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6389 #endif
6390   Register             scale_reg    = noreg;
6391   Address::ScaleFactor scale_factor = Address::no_scale;
6392   if (arg_slot.is_constant()) {
6393     offset += arg_slot.as_constant() * stackElementSize;
6394   } else {
6395     scale_reg    = arg_slot.as_register();
6396     scale_factor = Address::times(stackElementSize);
6397   }
6398   offset += wordSize;           // return PC is on stack
6399   return Address(rsp, scale_reg, scale_factor, offset);
6400 }
6401 
6402 
6403 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6404   if (!VerifyOops) return;
6405 
6406   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6407   // Pass register number to verify_oop_subroutine
6408   const char* b = NULL;
6409   {
6410     ResourceMark rm;
6411     stringStream ss;
6412     ss.print("verify_oop_addr: %s", s);
6413     b = code_string(ss.as_string());
6414   }
6415 #ifdef _LP64
6416   push(rscratch1);                    // save r10, trashed by movptr()
6417 #endif
6418   push(rax);                          // save rax,
6419   // addr may contain rsp so we will have to adjust it based on the push
6420   // we just did (and on 64 bit we do two pushes)
6421   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6422   // stores rax into addr which is backwards of what was intended.
6423   if (addr.uses(rsp)) {
6424     lea(rax, addr);
6425     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6426   } else {
6427     pushptr(addr);
6428   }
6429 
6430   ExternalAddress buffer((address) b);
6431   // pass msg argument
6432   // avoid using pushptr, as it modifies scratch registers
6433   // and our contract is not to modify anything
6434   movptr(rax, buffer.addr());
6435   push(rax);
6436 
6437   // call indirectly to solve generation ordering problem
6438   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6439   call(rax);
6440   // Caller pops the arguments (addr, message) and restores rax, r10.
6441 }
6442 
6443 void MacroAssembler::verify_tlab() {
6444 #ifdef ASSERT
6445   if (UseTLAB && VerifyOops) {
6446     Label next, ok;
6447     Register t1 = rsi;
6448     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6449 
6450     push(t1);
6451     NOT_LP64(push(thread_reg));
6452     NOT_LP64(get_thread(thread_reg));
6453 
6454     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6455     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6456     jcc(Assembler::aboveEqual, next);
6457     STOP("assert(top >= start)");
6458     should_not_reach_here();
6459 
6460     bind(next);
6461     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6462     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6463     jcc(Assembler::aboveEqual, ok);
6464     STOP("assert(top <= end)");
6465     should_not_reach_here();
6466 
6467     bind(ok);
6468     NOT_LP64(pop(thread_reg));
6469     pop(t1);
6470   }
6471 #endif
6472 }
6473 
6474 class ControlWord {
6475  public:
6476   int32_t _value;
6477 
6478   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6479   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6480   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6481   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6482   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6483   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6484   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6485   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6486 
6487   void print() const {
6488     // rounding control
6489     const char* rc;
6490     switch (rounding_control()) {
6491       case 0: rc = "round near"; break;
6492       case 1: rc = "round down"; break;
6493       case 2: rc = "round up  "; break;
6494       case 3: rc = "chop      "; break;
6495     };
6496     // precision control
6497     const char* pc;
6498     switch (precision_control()) {
6499       case 0: pc = "24 bits "; break;
6500       case 1: pc = "reserved"; break;
6501       case 2: pc = "53 bits "; break;
6502       case 3: pc = "64 bits "; break;
6503     };
6504     // flags
6505     char f[9];
6506     f[0] = ' ';
6507     f[1] = ' ';
6508     f[2] = (precision   ()) ? 'P' : 'p';
6509     f[3] = (underflow   ()) ? 'U' : 'u';
6510     f[4] = (overflow    ()) ? 'O' : 'o';
6511     f[5] = (zero_divide ()) ? 'Z' : 'z';
6512     f[6] = (denormalized()) ? 'D' : 'd';
6513     f[7] = (invalid     ()) ? 'I' : 'i';
6514     f[8] = '\x0';
6515     // output
6516     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6517   }
6518 
6519 };
6520 
6521 class StatusWord {
6522  public:
6523   int32_t _value;
6524 
6525   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6526   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6527   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6528   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6529   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6530   int  top() const                     { return  (_value >> 11) & 7      ; }
6531   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6532   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6533   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6534   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6535   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6536   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6537   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6538   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6539 
6540   void print() const {
6541     // condition codes
6542     char c[5];
6543     c[0] = (C3()) ? '3' : '-';
6544     c[1] = (C2()) ? '2' : '-';
6545     c[2] = (C1()) ? '1' : '-';
6546     c[3] = (C0()) ? '0' : '-';
6547     c[4] = '\x0';
6548     // flags
6549     char f[9];
6550     f[0] = (error_status()) ? 'E' : '-';
6551     f[1] = (stack_fault ()) ? 'S' : '-';
6552     f[2] = (precision   ()) ? 'P' : '-';
6553     f[3] = (underflow   ()) ? 'U' : '-';
6554     f[4] = (overflow    ()) ? 'O' : '-';
6555     f[5] = (zero_divide ()) ? 'Z' : '-';
6556     f[6] = (denormalized()) ? 'D' : '-';
6557     f[7] = (invalid     ()) ? 'I' : '-';
6558     f[8] = '\x0';
6559     // output
6560     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6561   }
6562 
6563 };
6564 
6565 class TagWord {
6566  public:
6567   int32_t _value;
6568 
6569   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6570 
6571   void print() const {
6572     printf("%04x", _value & 0xFFFF);
6573   }
6574 
6575 };
6576 
6577 class FPU_Register {
6578  public:
6579   int32_t _m0;
6580   int32_t _m1;
6581   int16_t _ex;
6582 
6583   bool is_indefinite() const           {
6584     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6585   }
6586 
6587   void print() const {
6588     char  sign = (_ex < 0) ? '-' : '+';
6589     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6590     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6591   };
6592 
6593 };
6594 
6595 class FPU_State {
6596  public:
6597   enum {
6598     register_size       = 10,
6599     number_of_registers =  8,
6600     register_mask       =  7
6601   };
6602 
6603   ControlWord  _control_word;
6604   StatusWord   _status_word;
6605   TagWord      _tag_word;
6606   int32_t      _error_offset;
6607   int32_t      _error_selector;
6608   int32_t      _data_offset;
6609   int32_t      _data_selector;
6610   int8_t       _register[register_size * number_of_registers];
6611 
6612   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6613   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6614 
6615   const char* tag_as_string(int tag) const {
6616     switch (tag) {
6617       case 0: return "valid";
6618       case 1: return "zero";
6619       case 2: return "special";
6620       case 3: return "empty";
6621     }
6622     ShouldNotReachHere();
6623     return NULL;
6624   }
6625 
6626   void print() const {
6627     // print computation registers
6628     { int t = _status_word.top();
6629       for (int i = 0; i < number_of_registers; i++) {
6630         int j = (i - t) & register_mask;
6631         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6632         st(j)->print();
6633         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6634       }
6635     }
6636     printf("\n");
6637     // print control registers
6638     printf("ctrl = "); _control_word.print(); printf("\n");
6639     printf("stat = "); _status_word .print(); printf("\n");
6640     printf("tags = "); _tag_word    .print(); printf("\n");
6641   }
6642 
6643 };
6644 
6645 class Flag_Register {
6646  public:
6647   int32_t _value;
6648 
6649   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6650   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6651   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6652   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6653   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6654   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6655   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6656 
6657   void print() const {
6658     // flags
6659     char f[8];
6660     f[0] = (overflow       ()) ? 'O' : '-';
6661     f[1] = (direction      ()) ? 'D' : '-';
6662     f[2] = (sign           ()) ? 'S' : '-';
6663     f[3] = (zero           ()) ? 'Z' : '-';
6664     f[4] = (auxiliary_carry()) ? 'A' : '-';
6665     f[5] = (parity         ()) ? 'P' : '-';
6666     f[6] = (carry          ()) ? 'C' : '-';
6667     f[7] = '\x0';
6668     // output
6669     printf("%08x  flags = %s", _value, f);
6670   }
6671 
6672 };
6673 
6674 class IU_Register {
6675  public:
6676   int32_t _value;
6677 
6678   void print() const {
6679     printf("%08x  %11d", _value, _value);
6680   }
6681 
6682 };
6683 
6684 class IU_State {
6685  public:
6686   Flag_Register _eflags;
6687   IU_Register   _rdi;
6688   IU_Register   _rsi;
6689   IU_Register   _rbp;
6690   IU_Register   _rsp;
6691   IU_Register   _rbx;
6692   IU_Register   _rdx;
6693   IU_Register   _rcx;
6694   IU_Register   _rax;
6695 
6696   void print() const {
6697     // computation registers
6698     printf("rax,  = "); _rax.print(); printf("\n");
6699     printf("rbx,  = "); _rbx.print(); printf("\n");
6700     printf("rcx  = "); _rcx.print(); printf("\n");
6701     printf("rdx  = "); _rdx.print(); printf("\n");
6702     printf("rdi  = "); _rdi.print(); printf("\n");
6703     printf("rsi  = "); _rsi.print(); printf("\n");
6704     printf("rbp,  = "); _rbp.print(); printf("\n");
6705     printf("rsp  = "); _rsp.print(); printf("\n");
6706     printf("\n");
6707     // control registers
6708     printf("flgs = "); _eflags.print(); printf("\n");
6709   }
6710 };
6711 
6712 
6713 class CPU_State {
6714  public:
6715   FPU_State _fpu_state;
6716   IU_State  _iu_state;
6717 
6718   void print() const {
6719     printf("--------------------------------------------------\n");
6720     _iu_state .print();
6721     printf("\n");
6722     _fpu_state.print();
6723     printf("--------------------------------------------------\n");
6724   }
6725 
6726 };
6727 
6728 
6729 static void _print_CPU_state(CPU_State* state) {
6730   state->print();
6731 };
6732 
6733 
6734 void MacroAssembler::print_CPU_state() {
6735   push_CPU_state();
6736   push(rsp);                // pass CPU state
6737   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6738   addptr(rsp, wordSize);       // discard argument
6739   pop_CPU_state();
6740 }
6741 
6742 
6743 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6744   static int counter = 0;
6745   FPU_State* fs = &state->_fpu_state;
6746   counter++;
6747   // For leaf calls, only verify that the top few elements remain empty.
6748   // We only need 1 empty at the top for C2 code.
6749   if( stack_depth < 0 ) {
6750     if( fs->tag_for_st(7) != 3 ) {
6751       printf("FPR7 not empty\n");
6752       state->print();
6753       assert(false, "error");
6754       return false;
6755     }
6756     return true;                // All other stack states do not matter
6757   }
6758 
6759   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6760          "bad FPU control word");
6761 
6762   // compute stack depth
6763   int i = 0;
6764   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6765   int d = i;
6766   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6767   // verify findings
6768   if (i != FPU_State::number_of_registers) {
6769     // stack not contiguous
6770     printf("%s: stack not contiguous at ST%d\n", s, i);
6771     state->print();
6772     assert(false, "error");
6773     return false;
6774   }
6775   // check if computed stack depth corresponds to expected stack depth
6776   if (stack_depth < 0) {
6777     // expected stack depth is -stack_depth or less
6778     if (d > -stack_depth) {
6779       // too many elements on the stack
6780       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6781       state->print();
6782       assert(false, "error");
6783       return false;
6784     }
6785   } else {
6786     // expected stack depth is stack_depth
6787     if (d != stack_depth) {
6788       // wrong stack depth
6789       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6790       state->print();
6791       assert(false, "error");
6792       return false;
6793     }
6794   }
6795   // everything is cool
6796   return true;
6797 }
6798 
6799 
6800 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6801   if (!VerifyFPU) return;
6802   push_CPU_state();
6803   push(rsp);                // pass CPU state
6804   ExternalAddress msg((address) s);
6805   // pass message string s
6806   pushptr(msg.addr());
6807   push(stack_depth);        // pass stack depth
6808   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6809   addptr(rsp, 3 * wordSize);   // discard arguments
6810   // check for error
6811   { Label L;
6812     testl(rax, rax);
6813     jcc(Assembler::notZero, L);
6814     int3();                  // break if error condition
6815     bind(L);
6816   }
6817   pop_CPU_state();
6818 }
6819 
6820 void MacroAssembler::restore_cpu_control_state_after_jni() {
6821   // Either restore the MXCSR register after returning from the JNI Call
6822   // or verify that it wasn't changed (with -Xcheck:jni flag).
6823   if (VM_Version::supports_sse()) {
6824     if (RestoreMXCSROnJNICalls) {
6825       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6826     } else if (CheckJNICalls) {
6827       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6828     }
6829   }
6830   if (VM_Version::supports_avx()) {
6831     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6832     vzeroupper();
6833   }
6834 
6835 #ifndef _LP64
6836   // Either restore the x87 floating pointer control word after returning
6837   // from the JNI call or verify that it wasn't changed.
6838   if (CheckJNICalls) {
6839     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6840   }
6841 #endif // _LP64
6842 }
6843 
6844 void MacroAssembler::load_mirror(Register mirror, Register method) {
6845   // get mirror
6846   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6847   movptr(mirror, Address(method, Method::const_offset()));
6848   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6849   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6850   movptr(mirror, Address(mirror, mirror_offset));
6851 }
6852 
6853 void MacroAssembler::load_klass(Register dst, Register src) {
6854   if (ShenandoahVerifyReadsToFromSpace) {
6855     oopDesc::bs()->interpreter_read_barrier(this, src);
6856   }
6857 #ifdef _LP64
6858   if (UseCompressedClassPointers) {
6859     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6860     decode_klass_not_null(dst);
6861   } else
6862 #endif
6863     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6864 }
6865 
6866 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6867   load_klass(dst, src);
6868   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6869 }
6870 
6871 void MacroAssembler::store_klass(Register dst, Register src) {
6872 #ifdef _LP64
6873   if (UseCompressedClassPointers) {
6874     encode_klass_not_null(src);
6875     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6876   } else
6877 #endif
6878     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6879 }
6880 
6881 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6882 #ifdef _LP64
6883   // FIXME: Must change all places where we try to load the klass.
6884   if (UseCompressedOops) {
6885     movl(dst, src);
6886     decode_heap_oop(dst);
6887   } else
6888 #endif
6889     movptr(dst, src);
6890 }
6891 
6892 // Doesn't do verfication, generates fixed size code
6893 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6894 #ifdef _LP64
6895   if (UseCompressedOops) {
6896     movl(dst, src);
6897     decode_heap_oop_not_null(dst);
6898   } else
6899 #endif
6900     movptr(dst, src);
6901 }
6902 
6903 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6904 #ifdef _LP64
6905   if (UseCompressedOops) {
6906     assert(!dst.uses(src), "not enough registers");
6907     encode_heap_oop(src);
6908     movl(dst, src);
6909   } else
6910 #endif
6911     movptr(dst, src);
6912 }
6913 
6914 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6915   assert_different_registers(src1, tmp);
6916 #ifdef _LP64
6917   if (UseCompressedOops) {
6918     bool did_push = false;
6919     if (tmp == noreg) {
6920       tmp = rax;
6921       push(tmp);
6922       did_push = true;
6923       assert(!src2.uses(rsp), "can't push");
6924     }
6925     load_heap_oop(tmp, src2);
6926     cmpptr(src1, tmp);
6927     if (did_push)  pop(tmp);
6928   } else
6929 #endif
6930     cmpptr(src1, src2);
6931 }
6932 
6933 // Used for storing NULLs.
6934 void MacroAssembler::store_heap_oop_null(Address dst) {
6935 #ifdef _LP64
6936   if (UseCompressedOops) {
6937     movl(dst, (int32_t)NULL_WORD);
6938   } else {
6939     movslq(dst, (int32_t)NULL_WORD);
6940   }
6941 #else
6942   movl(dst, (int32_t)NULL_WORD);
6943 #endif
6944 }
6945 
6946 #ifdef _LP64
6947 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6948   if (UseCompressedClassPointers) {
6949     // Store to klass gap in destination
6950     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6951   }
6952 }
6953 
6954 #ifdef ASSERT
6955 void MacroAssembler::verify_heapbase(const char* msg) {
6956   assert (UseCompressedOops, "should be compressed");
6957   assert (Universe::heap() != NULL, "java heap should be initialized");
6958   if (CheckCompressedOops) {
6959     Label ok;
6960     push(rscratch1); // cmpptr trashes rscratch1
6961     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6962     jcc(Assembler::equal, ok);
6963     STOP(msg);
6964     bind(ok);
6965     pop(rscratch1);
6966   }
6967 }
6968 #endif
6969 
6970 // Algorithm must match oop.inline.hpp encode_heap_oop.
6971 void MacroAssembler::encode_heap_oop(Register r) {
6972 #ifdef ASSERT
6973   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6974 #endif
6975   verify_oop(r, "broken oop in encode_heap_oop");
6976   if (Universe::narrow_oop_base() == NULL) {
6977     if (Universe::narrow_oop_shift() != 0) {
6978       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6979       shrq(r, LogMinObjAlignmentInBytes);
6980     }
6981     return;
6982   }
6983   testq(r, r);
6984   cmovq(Assembler::equal, r, r12_heapbase);
6985   subq(r, r12_heapbase);
6986   shrq(r, LogMinObjAlignmentInBytes);
6987 }
6988 
6989 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6990 #ifdef ASSERT
6991   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6992   if (CheckCompressedOops) {
6993     Label ok;
6994     testq(r, r);
6995     jcc(Assembler::notEqual, ok);
6996     STOP("null oop passed to encode_heap_oop_not_null");
6997     bind(ok);
6998   }
6999 #endif
7000   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7001   if (Universe::narrow_oop_base() != NULL) {
7002     subq(r, r12_heapbase);
7003   }
7004   if (Universe::narrow_oop_shift() != 0) {
7005     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7006     shrq(r, LogMinObjAlignmentInBytes);
7007   }
7008 }
7009 
7010 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7011 #ifdef ASSERT
7012   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7013   if (CheckCompressedOops) {
7014     Label ok;
7015     testq(src, src);
7016     jcc(Assembler::notEqual, ok);
7017     STOP("null oop passed to encode_heap_oop_not_null2");
7018     bind(ok);
7019   }
7020 #endif
7021   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7022   if (dst != src) {
7023     movq(dst, src);
7024   }
7025   if (Universe::narrow_oop_base() != NULL) {
7026     subq(dst, r12_heapbase);
7027   }
7028   if (Universe::narrow_oop_shift() != 0) {
7029     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7030     shrq(dst, LogMinObjAlignmentInBytes);
7031   }
7032 }
7033 
7034 void  MacroAssembler::decode_heap_oop(Register r) {
7035 #ifdef ASSERT
7036   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7037 #endif
7038   if (Universe::narrow_oop_base() == NULL) {
7039     if (Universe::narrow_oop_shift() != 0) {
7040       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7041       shlq(r, LogMinObjAlignmentInBytes);
7042     }
7043   } else {
7044     Label done;
7045     shlq(r, LogMinObjAlignmentInBytes);
7046     jccb(Assembler::equal, done);
7047     addq(r, r12_heapbase);
7048     bind(done);
7049   }
7050   verify_oop(r, "broken oop in decode_heap_oop");
7051 }
7052 
7053 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7054   // Note: it will change flags
7055   assert (UseCompressedOops, "should only be used for compressed headers");
7056   assert (Universe::heap() != NULL, "java heap should be initialized");
7057   // Cannot assert, unverified entry point counts instructions (see .ad file)
7058   // vtableStubs also counts instructions in pd_code_size_limit.
7059   // Also do not verify_oop as this is called by verify_oop.
7060   if (Universe::narrow_oop_shift() != 0) {
7061     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7062     shlq(r, LogMinObjAlignmentInBytes);
7063     if (Universe::narrow_oop_base() != NULL) {
7064       addq(r, r12_heapbase);
7065     }
7066   } else {
7067     assert (Universe::narrow_oop_base() == NULL, "sanity");
7068   }
7069 }
7070 
7071 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7072   // Note: it will change flags
7073   assert (UseCompressedOops, "should only be used for compressed headers");
7074   assert (Universe::heap() != NULL, "java heap should be initialized");
7075   // Cannot assert, unverified entry point counts instructions (see .ad file)
7076   // vtableStubs also counts instructions in pd_code_size_limit.
7077   // Also do not verify_oop as this is called by verify_oop.
7078   if (Universe::narrow_oop_shift() != 0) {
7079     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7080     if (LogMinObjAlignmentInBytes == Address::times_8) {
7081       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7082     } else {
7083       if (dst != src) {
7084         movq(dst, src);
7085       }
7086       shlq(dst, LogMinObjAlignmentInBytes);
7087       if (Universe::narrow_oop_base() != NULL) {
7088         addq(dst, r12_heapbase);
7089       }
7090     }
7091   } else {
7092     assert (Universe::narrow_oop_base() == NULL, "sanity");
7093     if (dst != src) {
7094       movq(dst, src);
7095     }
7096   }
7097 }
7098 
7099 void MacroAssembler::encode_klass_not_null(Register r) {
7100   if (Universe::narrow_klass_base() != NULL) {
7101     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7102     assert(r != r12_heapbase, "Encoding a klass in r12");
7103     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7104     subq(r, r12_heapbase);
7105   }
7106   if (Universe::narrow_klass_shift() != 0) {
7107     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7108     shrq(r, LogKlassAlignmentInBytes);
7109   }
7110   if (Universe::narrow_klass_base() != NULL) {
7111     reinit_heapbase();
7112   }
7113 }
7114 
7115 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7116   if (dst == src) {
7117     encode_klass_not_null(src);
7118   } else {
7119     if (Universe::narrow_klass_base() != NULL) {
7120       mov64(dst, (int64_t)Universe::narrow_klass_base());
7121       negq(dst);
7122       addq(dst, src);
7123     } else {
7124       movptr(dst, src);
7125     }
7126     if (Universe::narrow_klass_shift() != 0) {
7127       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7128       shrq(dst, LogKlassAlignmentInBytes);
7129     }
7130   }
7131 }
7132 
7133 // Function instr_size_for_decode_klass_not_null() counts the instructions
7134 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7135 // when (Universe::heap() != NULL).  Hence, if the instructions they
7136 // generate change, then this method needs to be updated.
7137 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7138   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7139   if (Universe::narrow_klass_base() != NULL) {
7140     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7141     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7142   } else {
7143     // longest load decode klass function, mov64, leaq
7144     return 16;
7145   }
7146 }
7147 
7148 // !!! If the instructions that get generated here change then function
7149 // instr_size_for_decode_klass_not_null() needs to get updated.
7150 void  MacroAssembler::decode_klass_not_null(Register r) {
7151   // Note: it will change flags
7152   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7153   assert(r != r12_heapbase, "Decoding a klass in r12");
7154   // Cannot assert, unverified entry point counts instructions (see .ad file)
7155   // vtableStubs also counts instructions in pd_code_size_limit.
7156   // Also do not verify_oop as this is called by verify_oop.
7157   if (Universe::narrow_klass_shift() != 0) {
7158     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7159     shlq(r, LogKlassAlignmentInBytes);
7160   }
7161   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7162   if (Universe::narrow_klass_base() != NULL) {
7163     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7164     addq(r, r12_heapbase);
7165     reinit_heapbase();
7166   }
7167 }
7168 
7169 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7170   // Note: it will change flags
7171   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7172   if (dst == src) {
7173     decode_klass_not_null(dst);
7174   } else {
7175     // Cannot assert, unverified entry point counts instructions (see .ad file)
7176     // vtableStubs also counts instructions in pd_code_size_limit.
7177     // Also do not verify_oop as this is called by verify_oop.
7178     mov64(dst, (int64_t)Universe::narrow_klass_base());
7179     if (Universe::narrow_klass_shift() != 0) {
7180       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7181       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7182       leaq(dst, Address(dst, src, Address::times_8, 0));
7183     } else {
7184       addq(dst, src);
7185     }
7186   }
7187 }
7188 
7189 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7190   assert (UseCompressedOops, "should only be used for compressed headers");
7191   assert (Universe::heap() != NULL, "java heap should be initialized");
7192   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7193   int oop_index = oop_recorder()->find_index(obj);
7194   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7195   mov_narrow_oop(dst, oop_index, rspec);
7196 }
7197 
7198 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7199   assert (UseCompressedOops, "should only be used for compressed headers");
7200   assert (Universe::heap() != NULL, "java heap should be initialized");
7201   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7202   int oop_index = oop_recorder()->find_index(obj);
7203   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7204   mov_narrow_oop(dst, oop_index, rspec);
7205 }
7206 
7207 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7208   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7209   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7210   int klass_index = oop_recorder()->find_index(k);
7211   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7212   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7213 }
7214 
7215 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7216   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7217   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7218   int klass_index = oop_recorder()->find_index(k);
7219   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7220   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7221 }
7222 
7223 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7224   assert (UseCompressedOops, "should only be used for compressed headers");
7225   assert (Universe::heap() != NULL, "java heap should be initialized");
7226   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7227   int oop_index = oop_recorder()->find_index(obj);
7228   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7229   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7230 }
7231 
7232 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7233   assert (UseCompressedOops, "should only be used for compressed headers");
7234   assert (Universe::heap() != NULL, "java heap should be initialized");
7235   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7236   int oop_index = oop_recorder()->find_index(obj);
7237   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7238   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7239 }
7240 
7241 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7242   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7243   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7244   int klass_index = oop_recorder()->find_index(k);
7245   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7246   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7247 }
7248 
7249 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7250   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7251   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7252   int klass_index = oop_recorder()->find_index(k);
7253   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7254   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7255 }
7256 
7257 void MacroAssembler::reinit_heapbase() {
7258   if (UseCompressedOops || UseCompressedClassPointers) {
7259     if (Universe::heap() != NULL) {
7260       if (Universe::narrow_oop_base() == NULL) {
7261         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7262       } else {
7263         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7264       }
7265     } else {
7266       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7267     }
7268   }
7269 }
7270 
7271 #endif // _LP64
7272 
7273 
7274 // C2 compiled method's prolog code.
7275 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7276 
7277   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7278   // NativeJump::patch_verified_entry will be able to patch out the entry
7279   // code safely. The push to verify stack depth is ok at 5 bytes,
7280   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7281   // stack bang then we must use the 6 byte frame allocation even if
7282   // we have no frame. :-(
7283   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7284 
7285   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7286   // Remove word for return addr
7287   framesize -= wordSize;
7288   stack_bang_size -= wordSize;
7289 
7290   // Calls to C2R adapters often do not accept exceptional returns.
7291   // We require that their callers must bang for them.  But be careful, because
7292   // some VM calls (such as call site linkage) can use several kilobytes of
7293   // stack.  But the stack safety zone should account for that.
7294   // See bugs 4446381, 4468289, 4497237.
7295   if (stack_bang_size > 0) {
7296     generate_stack_overflow_check(stack_bang_size);
7297 
7298     // We always push rbp, so that on return to interpreter rbp, will be
7299     // restored correctly and we can correct the stack.
7300     push(rbp);
7301     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7302     if (PreserveFramePointer) {
7303       mov(rbp, rsp);
7304     }
7305     // Remove word for ebp
7306     framesize -= wordSize;
7307 
7308     // Create frame
7309     if (framesize) {
7310       subptr(rsp, framesize);
7311     }
7312   } else {
7313     // Create frame (force generation of a 4 byte immediate value)
7314     subptr_imm32(rsp, framesize);
7315 
7316     // Save RBP register now.
7317     framesize -= wordSize;
7318     movptr(Address(rsp, framesize), rbp);
7319     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7320     if (PreserveFramePointer) {
7321       movptr(rbp, rsp);
7322       if (framesize > 0) {
7323         addptr(rbp, framesize);
7324       }
7325     }
7326   }
7327 
7328   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7329     framesize -= wordSize;
7330     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7331   }
7332 
7333 #ifndef _LP64
7334   // If method sets FPU control word do it now
7335   if (fp_mode_24b) {
7336     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7337   }
7338   if (UseSSE >= 2 && VerifyFPU) {
7339     verify_FPU(0, "FPU stack must be clean on entry");
7340   }
7341 #endif
7342 
7343 #ifdef ASSERT
7344   if (VerifyStackAtCalls) {
7345     Label L;
7346     push(rax);
7347     mov(rax, rsp);
7348     andptr(rax, StackAlignmentInBytes-1);
7349     cmpptr(rax, StackAlignmentInBytes-wordSize);
7350     pop(rax);
7351     jcc(Assembler::equal, L);
7352     STOP("Stack is not properly aligned!");
7353     bind(L);
7354   }
7355 #endif
7356 
7357 }
7358 
7359 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7360   // cnt - number of qwords (8-byte words).
7361   // base - start address, qword aligned.
7362   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7363   assert(base==rdi, "base register must be edi for rep stos");
7364   assert(tmp==rax,   "tmp register must be eax for rep stos");
7365   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7366   assert(InitArrayShortSize % BytesPerLong == 0,
7367     "InitArrayShortSize should be the multiple of BytesPerLong");
7368 
7369   Label DONE;
7370 
7371   xorptr(tmp, tmp);
7372 
7373   if (!is_large) {
7374     Label LOOP, LONG;
7375     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7376     jccb(Assembler::greater, LONG);
7377 
7378     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7379 
7380     decrement(cnt);
7381     jccb(Assembler::negative, DONE); // Zero length
7382 
7383     // Use individual pointer-sized stores for small counts:
7384     BIND(LOOP);
7385     movptr(Address(base, cnt, Address::times_ptr), tmp);
7386     decrement(cnt);
7387     jccb(Assembler::greaterEqual, LOOP);
7388     jmpb(DONE);
7389 
7390     BIND(LONG);
7391   }
7392 
7393   // Use longer rep-prefixed ops for non-small counts:
7394   if (UseFastStosb) {
7395     shlptr(cnt, 3); // convert to number of bytes
7396     rep_stosb();
7397   } else {
7398     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7399     rep_stos();
7400   }
7401 
7402   BIND(DONE);
7403 }
7404 
7405 #ifdef COMPILER2
7406 
7407 // IndexOf for constant substrings with size >= 8 chars
7408 // which don't need to be loaded through stack.
7409 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7410                                       Register cnt1, Register cnt2,
7411                                       int int_cnt2,  Register result,
7412                                       XMMRegister vec, Register tmp,
7413                                       int ae) {
7414   ShortBranchVerifier sbv(this);
7415   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7416   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7417 
7418   // This method uses the pcmpestri instruction with bound registers
7419   //   inputs:
7420   //     xmm - substring
7421   //     rax - substring length (elements count)
7422   //     mem - scanned string
7423   //     rdx - string length (elements count)
7424   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7425   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7426   //   outputs:
7427   //     rcx - matched index in string
7428   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7429   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7430   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7431   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7432   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7433 
7434   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7435         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7436         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7437 
7438   // Note, inline_string_indexOf() generates checks:
7439   // if (substr.count > string.count) return -1;
7440   // if (substr.count == 0) return 0;
7441   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7442 
7443   // Load substring.
7444   if (ae == StrIntrinsicNode::UL) {
7445     pmovzxbw(vec, Address(str2, 0));
7446   } else {
7447     movdqu(vec, Address(str2, 0));
7448   }
7449   movl(cnt2, int_cnt2);
7450   movptr(result, str1); // string addr
7451 
7452   if (int_cnt2 > stride) {
7453     jmpb(SCAN_TO_SUBSTR);
7454 
7455     // Reload substr for rescan, this code
7456     // is executed only for large substrings (> 8 chars)
7457     bind(RELOAD_SUBSTR);
7458     if (ae == StrIntrinsicNode::UL) {
7459       pmovzxbw(vec, Address(str2, 0));
7460     } else {
7461       movdqu(vec, Address(str2, 0));
7462     }
7463     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7464 
7465     bind(RELOAD_STR);
7466     // We came here after the beginning of the substring was
7467     // matched but the rest of it was not so we need to search
7468     // again. Start from the next element after the previous match.
7469 
7470     // cnt2 is number of substring reminding elements and
7471     // cnt1 is number of string reminding elements when cmp failed.
7472     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7473     subl(cnt1, cnt2);
7474     addl(cnt1, int_cnt2);
7475     movl(cnt2, int_cnt2); // Now restore cnt2
7476 
7477     decrementl(cnt1);     // Shift to next element
7478     cmpl(cnt1, cnt2);
7479     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7480 
7481     addptr(result, (1<<scale1));
7482 
7483   } // (int_cnt2 > 8)
7484 
7485   // Scan string for start of substr in 16-byte vectors
7486   bind(SCAN_TO_SUBSTR);
7487   pcmpestri(vec, Address(result, 0), mode);
7488   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7489   subl(cnt1, stride);
7490   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7491   cmpl(cnt1, cnt2);
7492   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7493   addptr(result, 16);
7494   jmpb(SCAN_TO_SUBSTR);
7495 
7496   // Found a potential substr
7497   bind(FOUND_CANDIDATE);
7498   // Matched whole vector if first element matched (tmp(rcx) == 0).
7499   if (int_cnt2 == stride) {
7500     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7501   } else { // int_cnt2 > 8
7502     jccb(Assembler::overflow, FOUND_SUBSTR);
7503   }
7504   // After pcmpestri tmp(rcx) contains matched element index
7505   // Compute start addr of substr
7506   lea(result, Address(result, tmp, scale1));
7507 
7508   // Make sure string is still long enough
7509   subl(cnt1, tmp);
7510   cmpl(cnt1, cnt2);
7511   if (int_cnt2 == stride) {
7512     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7513   } else { // int_cnt2 > 8
7514     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7515   }
7516   // Left less then substring.
7517 
7518   bind(RET_NOT_FOUND);
7519   movl(result, -1);
7520   jmp(EXIT);
7521 
7522   if (int_cnt2 > stride) {
7523     // This code is optimized for the case when whole substring
7524     // is matched if its head is matched.
7525     bind(MATCH_SUBSTR_HEAD);
7526     pcmpestri(vec, Address(result, 0), mode);
7527     // Reload only string if does not match
7528     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7529 
7530     Label CONT_SCAN_SUBSTR;
7531     // Compare the rest of substring (> 8 chars).
7532     bind(FOUND_SUBSTR);
7533     // First 8 chars are already matched.
7534     negptr(cnt2);
7535     addptr(cnt2, stride);
7536 
7537     bind(SCAN_SUBSTR);
7538     subl(cnt1, stride);
7539     cmpl(cnt2, -stride); // Do not read beyond substring
7540     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7541     // Back-up strings to avoid reading beyond substring:
7542     // cnt1 = cnt1 - cnt2 + 8
7543     addl(cnt1, cnt2); // cnt2 is negative
7544     addl(cnt1, stride);
7545     movl(cnt2, stride); negptr(cnt2);
7546     bind(CONT_SCAN_SUBSTR);
7547     if (int_cnt2 < (int)G) {
7548       int tail_off1 = int_cnt2<<scale1;
7549       int tail_off2 = int_cnt2<<scale2;
7550       if (ae == StrIntrinsicNode::UL) {
7551         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7552       } else {
7553         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7554       }
7555       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7556     } else {
7557       // calculate index in register to avoid integer overflow (int_cnt2*2)
7558       movl(tmp, int_cnt2);
7559       addptr(tmp, cnt2);
7560       if (ae == StrIntrinsicNode::UL) {
7561         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7562       } else {
7563         movdqu(vec, Address(str2, tmp, scale2, 0));
7564       }
7565       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7566     }
7567     // Need to reload strings pointers if not matched whole vector
7568     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7569     addptr(cnt2, stride);
7570     jcc(Assembler::negative, SCAN_SUBSTR);
7571     // Fall through if found full substring
7572 
7573   } // (int_cnt2 > 8)
7574 
7575   bind(RET_FOUND);
7576   // Found result if we matched full small substring.
7577   // Compute substr offset
7578   subptr(result, str1);
7579   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7580     shrl(result, 1); // index
7581   }
7582   bind(EXIT);
7583 
7584 } // string_indexofC8
7585 
7586 // Small strings are loaded through stack if they cross page boundary.
7587 void MacroAssembler::string_indexof(Register str1, Register str2,
7588                                     Register cnt1, Register cnt2,
7589                                     int int_cnt2,  Register result,
7590                                     XMMRegister vec, Register tmp,
7591                                     int ae) {
7592   ShortBranchVerifier sbv(this);
7593   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7594   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7595 
7596   //
7597   // int_cnt2 is length of small (< 8 chars) constant substring
7598   // or (-1) for non constant substring in which case its length
7599   // is in cnt2 register.
7600   //
7601   // Note, inline_string_indexOf() generates checks:
7602   // if (substr.count > string.count) return -1;
7603   // if (substr.count == 0) return 0;
7604   //
7605   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7606   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7607   // This method uses the pcmpestri instruction with bound registers
7608   //   inputs:
7609   //     xmm - substring
7610   //     rax - substring length (elements count)
7611   //     mem - scanned string
7612   //     rdx - string length (elements count)
7613   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7614   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7615   //   outputs:
7616   //     rcx - matched index in string
7617   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7618   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7619   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7620   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7621 
7622   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7623         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7624         FOUND_CANDIDATE;
7625 
7626   { //========================================================
7627     // We don't know where these strings are located
7628     // and we can't read beyond them. Load them through stack.
7629     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7630 
7631     movptr(tmp, rsp); // save old SP
7632 
7633     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7634       if (int_cnt2 == (1>>scale2)) { // One byte
7635         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7636         load_unsigned_byte(result, Address(str2, 0));
7637         movdl(vec, result); // move 32 bits
7638       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7639         // Not enough header space in 32-bit VM: 12+3 = 15.
7640         movl(result, Address(str2, -1));
7641         shrl(result, 8);
7642         movdl(vec, result); // move 32 bits
7643       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7644         load_unsigned_short(result, Address(str2, 0));
7645         movdl(vec, result); // move 32 bits
7646       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7647         movdl(vec, Address(str2, 0)); // move 32 bits
7648       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7649         movq(vec, Address(str2, 0));  // move 64 bits
7650       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7651         // Array header size is 12 bytes in 32-bit VM
7652         // + 6 bytes for 3 chars == 18 bytes,
7653         // enough space to load vec and shift.
7654         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7655         if (ae == StrIntrinsicNode::UL) {
7656           int tail_off = int_cnt2-8;
7657           pmovzxbw(vec, Address(str2, tail_off));
7658           psrldq(vec, -2*tail_off);
7659         }
7660         else {
7661           int tail_off = int_cnt2*(1<<scale2);
7662           movdqu(vec, Address(str2, tail_off-16));
7663           psrldq(vec, 16-tail_off);
7664         }
7665       }
7666     } else { // not constant substring
7667       cmpl(cnt2, stride);
7668       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7669 
7670       // We can read beyond string if srt+16 does not cross page boundary
7671       // since heaps are aligned and mapped by pages.
7672       assert(os::vm_page_size() < (int)G, "default page should be small");
7673       movl(result, str2); // We need only low 32 bits
7674       andl(result, (os::vm_page_size()-1));
7675       cmpl(result, (os::vm_page_size()-16));
7676       jccb(Assembler::belowEqual, CHECK_STR);
7677 
7678       // Move small strings to stack to allow load 16 bytes into vec.
7679       subptr(rsp, 16);
7680       int stk_offset = wordSize-(1<<scale2);
7681       push(cnt2);
7682 
7683       bind(COPY_SUBSTR);
7684       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7685         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7686         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7687       } else if (ae == StrIntrinsicNode::UU) {
7688         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7689         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7690       }
7691       decrement(cnt2);
7692       jccb(Assembler::notZero, COPY_SUBSTR);
7693 
7694       pop(cnt2);
7695       movptr(str2, rsp);  // New substring address
7696     } // non constant
7697 
7698     bind(CHECK_STR);
7699     cmpl(cnt1, stride);
7700     jccb(Assembler::aboveEqual, BIG_STRINGS);
7701 
7702     // Check cross page boundary.
7703     movl(result, str1); // We need only low 32 bits
7704     andl(result, (os::vm_page_size()-1));
7705     cmpl(result, (os::vm_page_size()-16));
7706     jccb(Assembler::belowEqual, BIG_STRINGS);
7707 
7708     subptr(rsp, 16);
7709     int stk_offset = -(1<<scale1);
7710     if (int_cnt2 < 0) { // not constant
7711       push(cnt2);
7712       stk_offset += wordSize;
7713     }
7714     movl(cnt2, cnt1);
7715 
7716     bind(COPY_STR);
7717     if (ae == StrIntrinsicNode::LL) {
7718       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7719       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7720     } else {
7721       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7722       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7723     }
7724     decrement(cnt2);
7725     jccb(Assembler::notZero, COPY_STR);
7726 
7727     if (int_cnt2 < 0) { // not constant
7728       pop(cnt2);
7729     }
7730     movptr(str1, rsp);  // New string address
7731 
7732     bind(BIG_STRINGS);
7733     // Load substring.
7734     if (int_cnt2 < 0) { // -1
7735       if (ae == StrIntrinsicNode::UL) {
7736         pmovzxbw(vec, Address(str2, 0));
7737       } else {
7738         movdqu(vec, Address(str2, 0));
7739       }
7740       push(cnt2);       // substr count
7741       push(str2);       // substr addr
7742       push(str1);       // string addr
7743     } else {
7744       // Small (< 8 chars) constant substrings are loaded already.
7745       movl(cnt2, int_cnt2);
7746     }
7747     push(tmp);  // original SP
7748 
7749   } // Finished loading
7750 
7751   //========================================================
7752   // Start search
7753   //
7754 
7755   movptr(result, str1); // string addr
7756 
7757   if (int_cnt2  < 0) {  // Only for non constant substring
7758     jmpb(SCAN_TO_SUBSTR);
7759 
7760     // SP saved at sp+0
7761     // String saved at sp+1*wordSize
7762     // Substr saved at sp+2*wordSize
7763     // Substr count saved at sp+3*wordSize
7764 
7765     // Reload substr for rescan, this code
7766     // is executed only for large substrings (> 8 chars)
7767     bind(RELOAD_SUBSTR);
7768     movptr(str2, Address(rsp, 2*wordSize));
7769     movl(cnt2, Address(rsp, 3*wordSize));
7770     if (ae == StrIntrinsicNode::UL) {
7771       pmovzxbw(vec, Address(str2, 0));
7772     } else {
7773       movdqu(vec, Address(str2, 0));
7774     }
7775     // We came here after the beginning of the substring was
7776     // matched but the rest of it was not so we need to search
7777     // again. Start from the next element after the previous match.
7778     subptr(str1, result); // Restore counter
7779     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7780       shrl(str1, 1);
7781     }
7782     addl(cnt1, str1);
7783     decrementl(cnt1);   // Shift to next element
7784     cmpl(cnt1, cnt2);
7785     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7786 
7787     addptr(result, (1<<scale1));
7788   } // non constant
7789 
7790   // Scan string for start of substr in 16-byte vectors
7791   bind(SCAN_TO_SUBSTR);
7792   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7793   pcmpestri(vec, Address(result, 0), mode);
7794   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7795   subl(cnt1, stride);
7796   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7797   cmpl(cnt1, cnt2);
7798   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7799   addptr(result, 16);
7800 
7801   bind(ADJUST_STR);
7802   cmpl(cnt1, stride); // Do not read beyond string
7803   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7804   // Back-up string to avoid reading beyond string.
7805   lea(result, Address(result, cnt1, scale1, -16));
7806   movl(cnt1, stride);
7807   jmpb(SCAN_TO_SUBSTR);
7808 
7809   // Found a potential substr
7810   bind(FOUND_CANDIDATE);
7811   // After pcmpestri tmp(rcx) contains matched element index
7812 
7813   // Make sure string is still long enough
7814   subl(cnt1, tmp);
7815   cmpl(cnt1, cnt2);
7816   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7817   // Left less then substring.
7818 
7819   bind(RET_NOT_FOUND);
7820   movl(result, -1);
7821   jmpb(CLEANUP);
7822 
7823   bind(FOUND_SUBSTR);
7824   // Compute start addr of substr
7825   lea(result, Address(result, tmp, scale1));
7826   if (int_cnt2 > 0) { // Constant substring
7827     // Repeat search for small substring (< 8 chars)
7828     // from new point without reloading substring.
7829     // Have to check that we don't read beyond string.
7830     cmpl(tmp, stride-int_cnt2);
7831     jccb(Assembler::greater, ADJUST_STR);
7832     // Fall through if matched whole substring.
7833   } else { // non constant
7834     assert(int_cnt2 == -1, "should be != 0");
7835 
7836     addl(tmp, cnt2);
7837     // Found result if we matched whole substring.
7838     cmpl(tmp, stride);
7839     jccb(Assembler::lessEqual, RET_FOUND);
7840 
7841     // Repeat search for small substring (<= 8 chars)
7842     // from new point 'str1' without reloading substring.
7843     cmpl(cnt2, stride);
7844     // Have to check that we don't read beyond string.
7845     jccb(Assembler::lessEqual, ADJUST_STR);
7846 
7847     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7848     // Compare the rest of substring (> 8 chars).
7849     movptr(str1, result);
7850 
7851     cmpl(tmp, cnt2);
7852     // First 8 chars are already matched.
7853     jccb(Assembler::equal, CHECK_NEXT);
7854 
7855     bind(SCAN_SUBSTR);
7856     pcmpestri(vec, Address(str1, 0), mode);
7857     // Need to reload strings pointers if not matched whole vector
7858     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7859 
7860     bind(CHECK_NEXT);
7861     subl(cnt2, stride);
7862     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7863     addptr(str1, 16);
7864     if (ae == StrIntrinsicNode::UL) {
7865       addptr(str2, 8);
7866     } else {
7867       addptr(str2, 16);
7868     }
7869     subl(cnt1, stride);
7870     cmpl(cnt2, stride); // Do not read beyond substring
7871     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7872     // Back-up strings to avoid reading beyond substring.
7873 
7874     if (ae == StrIntrinsicNode::UL) {
7875       lea(str2, Address(str2, cnt2, scale2, -8));
7876       lea(str1, Address(str1, cnt2, scale1, -16));
7877     } else {
7878       lea(str2, Address(str2, cnt2, scale2, -16));
7879       lea(str1, Address(str1, cnt2, scale1, -16));
7880     }
7881     subl(cnt1, cnt2);
7882     movl(cnt2, stride);
7883     addl(cnt1, stride);
7884     bind(CONT_SCAN_SUBSTR);
7885     if (ae == StrIntrinsicNode::UL) {
7886       pmovzxbw(vec, Address(str2, 0));
7887     } else {
7888       movdqu(vec, Address(str2, 0));
7889     }
7890     jmp(SCAN_SUBSTR);
7891 
7892     bind(RET_FOUND_LONG);
7893     movptr(str1, Address(rsp, wordSize));
7894   } // non constant
7895 
7896   bind(RET_FOUND);
7897   // Compute substr offset
7898   subptr(result, str1);
7899   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7900     shrl(result, 1); // index
7901   }
7902   bind(CLEANUP);
7903   pop(rsp); // restore SP
7904 
7905 } // string_indexof
7906 
7907 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7908                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7909   ShortBranchVerifier sbv(this);
7910   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7911 
7912   int stride = 8;
7913 
7914   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7915         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7916         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7917         FOUND_SEQ_CHAR, DONE_LABEL;
7918 
7919   movptr(result, str1);
7920   if (UseAVX >= 2) {
7921     cmpl(cnt1, stride);
7922     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7923     cmpl(cnt1, 2*stride);
7924     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7925     movdl(vec1, ch);
7926     vpbroadcastw(vec1, vec1);
7927     vpxor(vec2, vec2);
7928     movl(tmp, cnt1);
7929     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7930     andl(cnt1,0x0000000F);  //tail count (in chars)
7931 
7932     bind(SCAN_TO_16_CHAR_LOOP);
7933     vmovdqu(vec3, Address(result, 0));
7934     vpcmpeqw(vec3, vec3, vec1, 1);
7935     vptest(vec2, vec3);
7936     jcc(Assembler::carryClear, FOUND_CHAR);
7937     addptr(result, 32);
7938     subl(tmp, 2*stride);
7939     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7940     jmp(SCAN_TO_8_CHAR);
7941     bind(SCAN_TO_8_CHAR_INIT);
7942     movdl(vec1, ch);
7943     pshuflw(vec1, vec1, 0x00);
7944     pshufd(vec1, vec1, 0);
7945     pxor(vec2, vec2);
7946   }
7947   bind(SCAN_TO_8_CHAR);
7948   cmpl(cnt1, stride);
7949   if (UseAVX >= 2) {
7950     jcc(Assembler::less, SCAN_TO_CHAR);
7951   } else {
7952     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7953     movdl(vec1, ch);
7954     pshuflw(vec1, vec1, 0x00);
7955     pshufd(vec1, vec1, 0);
7956     pxor(vec2, vec2);
7957   }
7958   movl(tmp, cnt1);
7959   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7960   andl(cnt1,0x00000007);  //tail count (in chars)
7961 
7962   bind(SCAN_TO_8_CHAR_LOOP);
7963   movdqu(vec3, Address(result, 0));
7964   pcmpeqw(vec3, vec1);
7965   ptest(vec2, vec3);
7966   jcc(Assembler::carryClear, FOUND_CHAR);
7967   addptr(result, 16);
7968   subl(tmp, stride);
7969   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7970   bind(SCAN_TO_CHAR);
7971   testl(cnt1, cnt1);
7972   jcc(Assembler::zero, RET_NOT_FOUND);
7973   bind(SCAN_TO_CHAR_LOOP);
7974   load_unsigned_short(tmp, Address(result, 0));
7975   cmpl(ch, tmp);
7976   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7977   addptr(result, 2);
7978   subl(cnt1, 1);
7979   jccb(Assembler::zero, RET_NOT_FOUND);
7980   jmp(SCAN_TO_CHAR_LOOP);
7981 
7982   bind(RET_NOT_FOUND);
7983   movl(result, -1);
7984   jmpb(DONE_LABEL);
7985 
7986   bind(FOUND_CHAR);
7987   if (UseAVX >= 2) {
7988     vpmovmskb(tmp, vec3);
7989   } else {
7990     pmovmskb(tmp, vec3);
7991   }
7992   bsfl(ch, tmp);
7993   addl(result, ch);
7994 
7995   bind(FOUND_SEQ_CHAR);
7996   subptr(result, str1);
7997   shrl(result, 1);
7998 
7999   bind(DONE_LABEL);
8000 } // string_indexof_char
8001 
8002 // helper function for string_compare
8003 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
8004                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
8005                                         Address::ScaleFactor scale2, Register index, int ae) {
8006   if (ae == StrIntrinsicNode::LL) {
8007     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
8008     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
8009   } else if (ae == StrIntrinsicNode::UU) {
8010     load_unsigned_short(elem1, Address(str1, index, scale, 0));
8011     load_unsigned_short(elem2, Address(str2, index, scale, 0));
8012   } else {
8013     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
8014     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
8015   }
8016 }
8017 
8018 // Compare strings, used for char[] and byte[].
8019 void MacroAssembler::string_compare(Register str1, Register str2,
8020                                     Register cnt1, Register cnt2, Register result,
8021                                     XMMRegister vec1, int ae) {
8022   ShortBranchVerifier sbv(this);
8023   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
8024   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
8025   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8026   int stride2x2 = 0x40;
8027   Address::ScaleFactor scale = Address::no_scale;
8028   Address::ScaleFactor scale1 = Address::no_scale;
8029   Address::ScaleFactor scale2 = Address::no_scale;
8030 
8031   if (ae != StrIntrinsicNode::LL) {
8032     stride2x2 = 0x20;
8033   }
8034 
8035   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8036     shrl(cnt2, 1);
8037   }
8038   // Compute the minimum of the string lengths and the
8039   // difference of the string lengths (stack).
8040   // Do the conditional move stuff
8041   movl(result, cnt1);
8042   subl(cnt1, cnt2);
8043   push(cnt1);
8044   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
8045 
8046   // Is the minimum length zero?
8047   testl(cnt2, cnt2);
8048   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8049   if (ae == StrIntrinsicNode::LL) {
8050     // Load first bytes
8051     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
8052     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
8053   } else if (ae == StrIntrinsicNode::UU) {
8054     // Load first characters
8055     load_unsigned_short(result, Address(str1, 0));
8056     load_unsigned_short(cnt1, Address(str2, 0));
8057   } else {
8058     load_unsigned_byte(result, Address(str1, 0));
8059     load_unsigned_short(cnt1, Address(str2, 0));
8060   }
8061   subl(result, cnt1);
8062   jcc(Assembler::notZero,  POP_LABEL);
8063 
8064   if (ae == StrIntrinsicNode::UU) {
8065     // Divide length by 2 to get number of chars
8066     shrl(cnt2, 1);
8067   }
8068   cmpl(cnt2, 1);
8069   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8070 
8071   // Check if the strings start at the same location and setup scale and stride
8072   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8073     cmpptr(str1, str2);
8074     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8075     if (ae == StrIntrinsicNode::LL) {
8076       scale = Address::times_1;
8077       stride = 16;
8078     } else {
8079       scale = Address::times_2;
8080       stride = 8;
8081     }
8082   } else {
8083     scale1 = Address::times_1;
8084     scale2 = Address::times_2;
8085     // scale not used
8086     stride = 8;
8087   }
8088 
8089   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8090     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8091     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8092     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
8093     Label COMPARE_TAIL_LONG;
8094     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
8095 
8096     int pcmpmask = 0x19;
8097     if (ae == StrIntrinsicNode::LL) {
8098       pcmpmask &= ~0x01;
8099     }
8100 
8101     // Setup to compare 16-chars (32-bytes) vectors,
8102     // start from first character again because it has aligned address.
8103     if (ae == StrIntrinsicNode::LL) {
8104       stride2 = 32;
8105     } else {
8106       stride2 = 16;
8107     }
8108     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8109       adr_stride = stride << scale;
8110     } else {
8111       adr_stride1 = 8;  //stride << scale1;
8112       adr_stride2 = 16; //stride << scale2;
8113     }
8114 
8115     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8116     // rax and rdx are used by pcmpestri as elements counters
8117     movl(result, cnt2);
8118     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8119     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8120 
8121     // fast path : compare first 2 8-char vectors.
8122     bind(COMPARE_16_CHARS);
8123     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8124       movdqu(vec1, Address(str1, 0));
8125     } else {
8126       pmovzxbw(vec1, Address(str1, 0));
8127     }
8128     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8129     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8130 
8131     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8132       movdqu(vec1, Address(str1, adr_stride));
8133       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8134     } else {
8135       pmovzxbw(vec1, Address(str1, adr_stride1));
8136       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8137     }
8138     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8139     addl(cnt1, stride);
8140 
8141     // Compare the characters at index in cnt1
8142     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8143     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8144     subl(result, cnt2);
8145     jmp(POP_LABEL);
8146 
8147     // Setup the registers to start vector comparison loop
8148     bind(COMPARE_WIDE_VECTORS);
8149     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8150       lea(str1, Address(str1, result, scale));
8151       lea(str2, Address(str2, result, scale));
8152     } else {
8153       lea(str1, Address(str1, result, scale1));
8154       lea(str2, Address(str2, result, scale2));
8155     }
8156     subl(result, stride2);
8157     subl(cnt2, stride2);
8158     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8159     negptr(result);
8160 
8161     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8162     bind(COMPARE_WIDE_VECTORS_LOOP);
8163 
8164 #ifdef _LP64
8165     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8166       cmpl(cnt2, stride2x2);
8167       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8168       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8169       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8170 
8171       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8172       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8173         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8174         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8175       } else {
8176         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8177         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8178       }
8179       kortestql(k7, k7);
8180       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8181       addptr(result, stride2x2);  // update since we already compared at this addr
8182       subl(cnt2, stride2x2);      // and sub the size too
8183       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8184 
8185       vpxor(vec1, vec1);
8186       jmpb(COMPARE_WIDE_TAIL);
8187     }//if (VM_Version::supports_avx512vlbw())
8188 #endif // _LP64
8189 
8190 
8191     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8192     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8193       vmovdqu(vec1, Address(str1, result, scale));
8194       vpxor(vec1, Address(str2, result, scale));
8195     } else {
8196       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8197       vpxor(vec1, Address(str2, result, scale2));
8198     }
8199     vptest(vec1, vec1);
8200     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8201     addptr(result, stride2);
8202     subl(cnt2, stride2);
8203     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8204     // clean upper bits of YMM registers
8205     vpxor(vec1, vec1);
8206 
8207     // compare wide vectors tail
8208     bind(COMPARE_WIDE_TAIL);
8209     testptr(result, result);
8210     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8211 
8212     movl(result, stride2);
8213     movl(cnt2, result);
8214     negptr(result);
8215     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8216 
8217     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8218     bind(VECTOR_NOT_EQUAL);
8219     // clean upper bits of YMM registers
8220     vpxor(vec1, vec1);
8221     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8222       lea(str1, Address(str1, result, scale));
8223       lea(str2, Address(str2, result, scale));
8224     } else {
8225       lea(str1, Address(str1, result, scale1));
8226       lea(str2, Address(str2, result, scale2));
8227     }
8228     jmp(COMPARE_16_CHARS);
8229 
8230     // Compare tail chars, length between 1 to 15 chars
8231     bind(COMPARE_TAIL_LONG);
8232     movl(cnt2, result);
8233     cmpl(cnt2, stride);
8234     jcc(Assembler::less, COMPARE_SMALL_STR);
8235 
8236     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8237       movdqu(vec1, Address(str1, 0));
8238     } else {
8239       pmovzxbw(vec1, Address(str1, 0));
8240     }
8241     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8242     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8243     subptr(cnt2, stride);
8244     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8245     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8246       lea(str1, Address(str1, result, scale));
8247       lea(str2, Address(str2, result, scale));
8248     } else {
8249       lea(str1, Address(str1, result, scale1));
8250       lea(str2, Address(str2, result, scale2));
8251     }
8252     negptr(cnt2);
8253     jmpb(WHILE_HEAD_LABEL);
8254 
8255     bind(COMPARE_SMALL_STR);
8256   } else if (UseSSE42Intrinsics) {
8257     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8258     int pcmpmask = 0x19;
8259     // Setup to compare 8-char (16-byte) vectors,
8260     // start from first character again because it has aligned address.
8261     movl(result, cnt2);
8262     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8263     if (ae == StrIntrinsicNode::LL) {
8264       pcmpmask &= ~0x01;
8265     }
8266     jcc(Assembler::zero, COMPARE_TAIL);
8267     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8268       lea(str1, Address(str1, result, scale));
8269       lea(str2, Address(str2, result, scale));
8270     } else {
8271       lea(str1, Address(str1, result, scale1));
8272       lea(str2, Address(str2, result, scale2));
8273     }
8274     negptr(result);
8275 
8276     // pcmpestri
8277     //   inputs:
8278     //     vec1- substring
8279     //     rax - negative string length (elements count)
8280     //     mem - scanned string
8281     //     rdx - string length (elements count)
8282     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8283     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8284     //   outputs:
8285     //     rcx - first mismatched element index
8286     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8287 
8288     bind(COMPARE_WIDE_VECTORS);
8289     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8290       movdqu(vec1, Address(str1, result, scale));
8291       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8292     } else {
8293       pmovzxbw(vec1, Address(str1, result, scale1));
8294       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8295     }
8296     // After pcmpestri cnt1(rcx) contains mismatched element index
8297 
8298     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8299     addptr(result, stride);
8300     subptr(cnt2, stride);
8301     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8302 
8303     // compare wide vectors tail
8304     testptr(result, result);
8305     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8306 
8307     movl(cnt2, stride);
8308     movl(result, stride);
8309     negptr(result);
8310     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8311       movdqu(vec1, Address(str1, result, scale));
8312       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8313     } else {
8314       pmovzxbw(vec1, Address(str1, result, scale1));
8315       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8316     }
8317     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8318 
8319     // Mismatched characters in the vectors
8320     bind(VECTOR_NOT_EQUAL);
8321     addptr(cnt1, result);
8322     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8323     subl(result, cnt2);
8324     jmpb(POP_LABEL);
8325 
8326     bind(COMPARE_TAIL); // limit is zero
8327     movl(cnt2, result);
8328     // Fallthru to tail compare
8329   }
8330   // Shift str2 and str1 to the end of the arrays, negate min
8331   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8332     lea(str1, Address(str1, cnt2, scale));
8333     lea(str2, Address(str2, cnt2, scale));
8334   } else {
8335     lea(str1, Address(str1, cnt2, scale1));
8336     lea(str2, Address(str2, cnt2, scale2));
8337   }
8338   decrementl(cnt2);  // first character was compared already
8339   negptr(cnt2);
8340 
8341   // Compare the rest of the elements
8342   bind(WHILE_HEAD_LABEL);
8343   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8344   subl(result, cnt1);
8345   jccb(Assembler::notZero, POP_LABEL);
8346   increment(cnt2);
8347   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8348 
8349   // Strings are equal up to min length.  Return the length difference.
8350   bind(LENGTH_DIFF_LABEL);
8351   pop(result);
8352   if (ae == StrIntrinsicNode::UU) {
8353     // Divide diff by 2 to get number of chars
8354     sarl(result, 1);
8355   }
8356   jmpb(DONE_LABEL);
8357 
8358 #ifdef _LP64
8359   if (VM_Version::supports_avx512vlbw()) {
8360 
8361     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8362 
8363     kmovql(cnt1, k7);
8364     notq(cnt1);
8365     bsfq(cnt2, cnt1);
8366     if (ae != StrIntrinsicNode::LL) {
8367       // Divide diff by 2 to get number of chars
8368       sarl(cnt2, 1);
8369     }
8370     addq(result, cnt2);
8371     if (ae == StrIntrinsicNode::LL) {
8372       load_unsigned_byte(cnt1, Address(str2, result));
8373       load_unsigned_byte(result, Address(str1, result));
8374     } else if (ae == StrIntrinsicNode::UU) {
8375       load_unsigned_short(cnt1, Address(str2, result, scale));
8376       load_unsigned_short(result, Address(str1, result, scale));
8377     } else {
8378       load_unsigned_short(cnt1, Address(str2, result, scale2));
8379       load_unsigned_byte(result, Address(str1, result, scale1));
8380     }
8381     subl(result, cnt1);
8382     jmpb(POP_LABEL);
8383   }//if (VM_Version::supports_avx512vlbw())
8384 #endif // _LP64
8385 
8386   // Discard the stored length difference
8387   bind(POP_LABEL);
8388   pop(cnt1);
8389 
8390   // That's it
8391   bind(DONE_LABEL);
8392   if(ae == StrIntrinsicNode::UL) {
8393     negl(result);
8394   }
8395 
8396 }
8397 
8398 // Search for Non-ASCII character (Negative byte value) in a byte array,
8399 // return true if it has any and false otherwise.
8400 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8401 //   @HotSpotIntrinsicCandidate
8402 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8403 //     for (int i = off; i < off + len; i++) {
8404 //       if (ba[i] < 0) {
8405 //         return true;
8406 //       }
8407 //     }
8408 //     return false;
8409 //   }
8410 void MacroAssembler::has_negatives(Register ary1, Register len,
8411   Register result, Register tmp1,
8412   XMMRegister vec1, XMMRegister vec2) {
8413   // rsi: byte array
8414   // rcx: len
8415   // rax: result
8416   ShortBranchVerifier sbv(this);
8417   assert_different_registers(ary1, len, result, tmp1);
8418   assert_different_registers(vec1, vec2);
8419   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8420 
8421   // len == 0
8422   testl(len, len);
8423   jcc(Assembler::zero, FALSE_LABEL);
8424 
8425   if ((UseAVX > 2) && // AVX512
8426     VM_Version::supports_avx512vlbw() &&
8427     VM_Version::supports_bmi2()) {
8428 
8429     set_vector_masking();  // opening of the stub context for programming mask registers
8430 
8431     Label test_64_loop, test_tail;
8432     Register tmp3_aliased = len;
8433 
8434     movl(tmp1, len);
8435     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8436 
8437     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8438     andl(len, ~(64 - 1));    // vector count (in chars)
8439     jccb(Assembler::zero, test_tail);
8440 
8441     lea(ary1, Address(ary1, len, Address::times_1));
8442     negptr(len);
8443 
8444     bind(test_64_loop);
8445     // Check whether our 64 elements of size byte contain negatives
8446     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8447     kortestql(k2, k2);
8448     jcc(Assembler::notZero, TRUE_LABEL);
8449 
8450     addptr(len, 64);
8451     jccb(Assembler::notZero, test_64_loop);
8452 
8453 
8454     bind(test_tail);
8455     // bail out when there is nothing to be done
8456     testl(tmp1, -1);
8457     jcc(Assembler::zero, FALSE_LABEL);
8458 
8459     // Save k1
8460     kmovql(k3, k1);
8461 
8462     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8463 #ifdef _LP64
8464     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8465     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8466     notq(tmp3_aliased);
8467     kmovql(k1, tmp3_aliased);
8468 #else
8469     Label k_init;
8470     jmp(k_init);
8471 
8472     // We could not read 64-bits from a general purpose register thus we move
8473     // data required to compose 64 1's to the instruction stream
8474     // We emit 64 byte wide series of elements from 0..63 which later on would
8475     // be used as a compare targets with tail count contained in tmp1 register.
8476     // Result would be a k1 register having tmp1 consecutive number or 1
8477     // counting from least significant bit.
8478     address tmp = pc();
8479     emit_int64(0x0706050403020100);
8480     emit_int64(0x0F0E0D0C0B0A0908);
8481     emit_int64(0x1716151413121110);
8482     emit_int64(0x1F1E1D1C1B1A1918);
8483     emit_int64(0x2726252423222120);
8484     emit_int64(0x2F2E2D2C2B2A2928);
8485     emit_int64(0x3736353433323130);
8486     emit_int64(0x3F3E3D3C3B3A3938);
8487 
8488     bind(k_init);
8489     lea(len, InternalAddress(tmp));
8490     // create mask to test for negative byte inside a vector
8491     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8492     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8493 
8494 #endif
8495     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8496     ktestq(k2, k1);
8497     // Restore k1
8498     kmovql(k1, k3);
8499     jcc(Assembler::notZero, TRUE_LABEL);
8500 
8501     jmp(FALSE_LABEL);
8502 
8503     clear_vector_masking();   // closing of the stub context for programming mask registers
8504   } else {
8505     movl(result, len); // copy
8506 
8507     if (UseAVX == 2 && UseSSE >= 2) {
8508       // With AVX2, use 32-byte vector compare
8509       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8510 
8511       // Compare 32-byte vectors
8512       andl(result, 0x0000001f);  //   tail count (in bytes)
8513       andl(len, 0xffffffe0);   // vector count (in bytes)
8514       jccb(Assembler::zero, COMPARE_TAIL);
8515 
8516       lea(ary1, Address(ary1, len, Address::times_1));
8517       negptr(len);
8518 
8519       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8520       movdl(vec2, tmp1);
8521       vpbroadcastd(vec2, vec2);
8522 
8523       bind(COMPARE_WIDE_VECTORS);
8524       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8525       vptest(vec1, vec2);
8526       jccb(Assembler::notZero, TRUE_LABEL);
8527       addptr(len, 32);
8528       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8529 
8530       testl(result, result);
8531       jccb(Assembler::zero, FALSE_LABEL);
8532 
8533       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8534       vptest(vec1, vec2);
8535       jccb(Assembler::notZero, TRUE_LABEL);
8536       jmpb(FALSE_LABEL);
8537 
8538       bind(COMPARE_TAIL); // len is zero
8539       movl(len, result);
8540       // Fallthru to tail compare
8541     } else if (UseSSE42Intrinsics) {
8542       // With SSE4.2, use double quad vector compare
8543       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8544 
8545       // Compare 16-byte vectors
8546       andl(result, 0x0000000f);  //   tail count (in bytes)
8547       andl(len, 0xfffffff0);   // vector count (in bytes)
8548       jccb(Assembler::zero, COMPARE_TAIL);
8549 
8550       lea(ary1, Address(ary1, len, Address::times_1));
8551       negptr(len);
8552 
8553       movl(tmp1, 0x80808080);
8554       movdl(vec2, tmp1);
8555       pshufd(vec2, vec2, 0);
8556 
8557       bind(COMPARE_WIDE_VECTORS);
8558       movdqu(vec1, Address(ary1, len, Address::times_1));
8559       ptest(vec1, vec2);
8560       jccb(Assembler::notZero, TRUE_LABEL);
8561       addptr(len, 16);
8562       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8563 
8564       testl(result, result);
8565       jccb(Assembler::zero, FALSE_LABEL);
8566 
8567       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8568       ptest(vec1, vec2);
8569       jccb(Assembler::notZero, TRUE_LABEL);
8570       jmpb(FALSE_LABEL);
8571 
8572       bind(COMPARE_TAIL); // len is zero
8573       movl(len, result);
8574       // Fallthru to tail compare
8575     }
8576   }
8577   // Compare 4-byte vectors
8578   andl(len, 0xfffffffc); // vector count (in bytes)
8579   jccb(Assembler::zero, COMPARE_CHAR);
8580 
8581   lea(ary1, Address(ary1, len, Address::times_1));
8582   negptr(len);
8583 
8584   bind(COMPARE_VECTORS);
8585   movl(tmp1, Address(ary1, len, Address::times_1));
8586   andl(tmp1, 0x80808080);
8587   jccb(Assembler::notZero, TRUE_LABEL);
8588   addptr(len, 4);
8589   jcc(Assembler::notZero, COMPARE_VECTORS);
8590 
8591   // Compare trailing char (final 2 bytes), if any
8592   bind(COMPARE_CHAR);
8593   testl(result, 0x2);   // tail  char
8594   jccb(Assembler::zero, COMPARE_BYTE);
8595   load_unsigned_short(tmp1, Address(ary1, 0));
8596   andl(tmp1, 0x00008080);
8597   jccb(Assembler::notZero, TRUE_LABEL);
8598   subptr(result, 2);
8599   lea(ary1, Address(ary1, 2));
8600 
8601   bind(COMPARE_BYTE);
8602   testl(result, 0x1);   // tail  byte
8603   jccb(Assembler::zero, FALSE_LABEL);
8604   load_unsigned_byte(tmp1, Address(ary1, 0));
8605   andl(tmp1, 0x00000080);
8606   jccb(Assembler::notEqual, TRUE_LABEL);
8607   jmpb(FALSE_LABEL);
8608 
8609   bind(TRUE_LABEL);
8610   movl(result, 1);   // return true
8611   jmpb(DONE);
8612 
8613   bind(FALSE_LABEL);
8614   xorl(result, result); // return false
8615 
8616   // That's it
8617   bind(DONE);
8618   if (UseAVX >= 2 && UseSSE >= 2) {
8619     // clean upper bits of YMM registers
8620     vpxor(vec1, vec1);
8621     vpxor(vec2, vec2);
8622   }
8623 }
8624 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8625 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8626                                    Register limit, Register result, Register chr,
8627                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8628   ShortBranchVerifier sbv(this);
8629   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8630 
8631   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8632   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8633 
8634   if (is_array_equ) {
8635     // Check the input args
8636     cmpptr(ary1, ary2);
8637     oopDesc::bs()->asm_acmp_barrier(this, ary1, ary2);
8638     jcc(Assembler::equal, TRUE_LABEL);
8639 
8640     // Need additional checks for arrays_equals.
8641     testptr(ary1, ary1);
8642     jcc(Assembler::zero, FALSE_LABEL);
8643     testptr(ary2, ary2);
8644     jcc(Assembler::zero, FALSE_LABEL);
8645 
8646     // Check the lengths
8647     movl(limit, Address(ary1, length_offset));
8648     cmpl(limit, Address(ary2, length_offset));
8649     jcc(Assembler::notEqual, FALSE_LABEL);
8650   }
8651 
8652   // count == 0
8653   testl(limit, limit);
8654   jcc(Assembler::zero, TRUE_LABEL);
8655 
8656   if (is_array_equ) {
8657     // Load array address
8658     lea(ary1, Address(ary1, base_offset));
8659     lea(ary2, Address(ary2, base_offset));
8660   }
8661 
8662   if (is_array_equ && is_char) {
8663     // arrays_equals when used for char[].
8664     shll(limit, 1);      // byte count != 0
8665   }
8666   movl(result, limit); // copy
8667 
8668   if (UseAVX >= 2) {
8669     // With AVX2, use 32-byte vector compare
8670     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8671 
8672     // Compare 32-byte vectors
8673     andl(result, 0x0000001f);  //   tail count (in bytes)
8674     andl(limit, 0xffffffe0);   // vector count (in bytes)
8675     jcc(Assembler::zero, COMPARE_TAIL);
8676 
8677     lea(ary1, Address(ary1, limit, Address::times_1));
8678     lea(ary2, Address(ary2, limit, Address::times_1));
8679     negptr(limit);
8680 
8681     bind(COMPARE_WIDE_VECTORS);
8682 
8683 #ifdef _LP64
8684     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8685       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8686 
8687       cmpl(limit, -64);
8688       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8689 
8690       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8691 
8692       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8693       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8694       kortestql(k7, k7);
8695       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8696       addptr(limit, 64);  // update since we already compared at this addr
8697       cmpl(limit, -64);
8698       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8699 
8700       // At this point we may still need to compare -limit+result bytes.
8701       // We could execute the next two instruction and just continue via non-wide path:
8702       //  cmpl(limit, 0);
8703       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8704       // But since we stopped at the points ary{1,2}+limit which are
8705       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8706       // (|limit| <= 32 and result < 32),
8707       // we may just compare the last 64 bytes.
8708       //
8709       addptr(result, -64);   // it is safe, bc we just came from this area
8710       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8711       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8712       kortestql(k7, k7);
8713       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8714 
8715       jmp(TRUE_LABEL);
8716 
8717       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8718 
8719     }//if (VM_Version::supports_avx512vlbw())
8720 #endif //_LP64
8721 
8722     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8723     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8724     vpxor(vec1, vec2);
8725 
8726     vptest(vec1, vec1);
8727     jcc(Assembler::notZero, FALSE_LABEL);
8728     addptr(limit, 32);
8729     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8730 
8731     testl(result, result);
8732     jcc(Assembler::zero, TRUE_LABEL);
8733 
8734     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8735     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8736     vpxor(vec1, vec2);
8737 
8738     vptest(vec1, vec1);
8739     jccb(Assembler::notZero, FALSE_LABEL);
8740     jmpb(TRUE_LABEL);
8741 
8742     bind(COMPARE_TAIL); // limit is zero
8743     movl(limit, result);
8744     // Fallthru to tail compare
8745   } else if (UseSSE42Intrinsics) {
8746     // With SSE4.2, use double quad vector compare
8747     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8748 
8749     // Compare 16-byte vectors
8750     andl(result, 0x0000000f);  //   tail count (in bytes)
8751     andl(limit, 0xfffffff0);   // vector count (in bytes)
8752     jcc(Assembler::zero, COMPARE_TAIL);
8753 
8754     lea(ary1, Address(ary1, limit, Address::times_1));
8755     lea(ary2, Address(ary2, limit, Address::times_1));
8756     negptr(limit);
8757 
8758     bind(COMPARE_WIDE_VECTORS);
8759     movdqu(vec1, Address(ary1, limit, Address::times_1));
8760     movdqu(vec2, Address(ary2, limit, Address::times_1));
8761     pxor(vec1, vec2);
8762 
8763     ptest(vec1, vec1);
8764     jcc(Assembler::notZero, FALSE_LABEL);
8765     addptr(limit, 16);
8766     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8767 
8768     testl(result, result);
8769     jcc(Assembler::zero, TRUE_LABEL);
8770 
8771     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8772     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8773     pxor(vec1, vec2);
8774 
8775     ptest(vec1, vec1);
8776     jccb(Assembler::notZero, FALSE_LABEL);
8777     jmpb(TRUE_LABEL);
8778 
8779     bind(COMPARE_TAIL); // limit is zero
8780     movl(limit, result);
8781     // Fallthru to tail compare
8782   }
8783 
8784   // Compare 4-byte vectors
8785   andl(limit, 0xfffffffc); // vector count (in bytes)
8786   jccb(Assembler::zero, COMPARE_CHAR);
8787 
8788   lea(ary1, Address(ary1, limit, Address::times_1));
8789   lea(ary2, Address(ary2, limit, Address::times_1));
8790   negptr(limit);
8791 
8792   bind(COMPARE_VECTORS);
8793   movl(chr, Address(ary1, limit, Address::times_1));
8794   cmpl(chr, Address(ary2, limit, Address::times_1));
8795   jccb(Assembler::notEqual, FALSE_LABEL);
8796   addptr(limit, 4);
8797   jcc(Assembler::notZero, COMPARE_VECTORS);
8798 
8799   // Compare trailing char (final 2 bytes), if any
8800   bind(COMPARE_CHAR);
8801   testl(result, 0x2);   // tail  char
8802   jccb(Assembler::zero, COMPARE_BYTE);
8803   load_unsigned_short(chr, Address(ary1, 0));
8804   load_unsigned_short(limit, Address(ary2, 0));
8805   cmpl(chr, limit);
8806   jccb(Assembler::notEqual, FALSE_LABEL);
8807 
8808   if (is_array_equ && is_char) {
8809     bind(COMPARE_BYTE);
8810   } else {
8811     lea(ary1, Address(ary1, 2));
8812     lea(ary2, Address(ary2, 2));
8813 
8814     bind(COMPARE_BYTE);
8815     testl(result, 0x1);   // tail  byte
8816     jccb(Assembler::zero, TRUE_LABEL);
8817     load_unsigned_byte(chr, Address(ary1, 0));
8818     load_unsigned_byte(limit, Address(ary2, 0));
8819     cmpl(chr, limit);
8820     jccb(Assembler::notEqual, FALSE_LABEL);
8821   }
8822   bind(TRUE_LABEL);
8823   movl(result, 1);   // return true
8824   jmpb(DONE);
8825 
8826   bind(FALSE_LABEL);
8827   xorl(result, result); // return false
8828 
8829   // That's it
8830   bind(DONE);
8831   if (UseAVX >= 2) {
8832     // clean upper bits of YMM registers
8833     vpxor(vec1, vec1);
8834     vpxor(vec2, vec2);
8835   }
8836 }
8837 
8838 #endif
8839 
8840 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8841                                    Register to, Register value, Register count,
8842                                    Register rtmp, XMMRegister xtmp) {
8843   ShortBranchVerifier sbv(this);
8844   assert_different_registers(to, value, count, rtmp);
8845   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8846   Label L_fill_2_bytes, L_fill_4_bytes;
8847 
8848   int shift = -1;
8849   switch (t) {
8850     case T_BYTE:
8851       shift = 2;
8852       break;
8853     case T_SHORT:
8854       shift = 1;
8855       break;
8856     case T_INT:
8857       shift = 0;
8858       break;
8859     default: ShouldNotReachHere();
8860   }
8861 
8862   if (t == T_BYTE) {
8863     andl(value, 0xff);
8864     movl(rtmp, value);
8865     shll(rtmp, 8);
8866     orl(value, rtmp);
8867   }
8868   if (t == T_SHORT) {
8869     andl(value, 0xffff);
8870   }
8871   if (t == T_BYTE || t == T_SHORT) {
8872     movl(rtmp, value);
8873     shll(rtmp, 16);
8874     orl(value, rtmp);
8875   }
8876 
8877   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8878   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8879   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8880     // align source address at 4 bytes address boundary
8881     if (t == T_BYTE) {
8882       // One byte misalignment happens only for byte arrays
8883       testptr(to, 1);
8884       jccb(Assembler::zero, L_skip_align1);
8885       movb(Address(to, 0), value);
8886       increment(to);
8887       decrement(count);
8888       BIND(L_skip_align1);
8889     }
8890     // Two bytes misalignment happens only for byte and short (char) arrays
8891     testptr(to, 2);
8892     jccb(Assembler::zero, L_skip_align2);
8893     movw(Address(to, 0), value);
8894     addptr(to, 2);
8895     subl(count, 1<<(shift-1));
8896     BIND(L_skip_align2);
8897   }
8898   if (UseSSE < 2) {
8899     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8900     // Fill 32-byte chunks
8901     subl(count, 8 << shift);
8902     jcc(Assembler::less, L_check_fill_8_bytes);
8903     align(16);
8904 
8905     BIND(L_fill_32_bytes_loop);
8906 
8907     for (int i = 0; i < 32; i += 4) {
8908       movl(Address(to, i), value);
8909     }
8910 
8911     addptr(to, 32);
8912     subl(count, 8 << shift);
8913     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8914     BIND(L_check_fill_8_bytes);
8915     addl(count, 8 << shift);
8916     jccb(Assembler::zero, L_exit);
8917     jmpb(L_fill_8_bytes);
8918 
8919     //
8920     // length is too short, just fill qwords
8921     //
8922     BIND(L_fill_8_bytes_loop);
8923     movl(Address(to, 0), value);
8924     movl(Address(to, 4), value);
8925     addptr(to, 8);
8926     BIND(L_fill_8_bytes);
8927     subl(count, 1 << (shift + 1));
8928     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8929     // fall through to fill 4 bytes
8930   } else {
8931     Label L_fill_32_bytes;
8932     if (!UseUnalignedLoadStores) {
8933       // align to 8 bytes, we know we are 4 byte aligned to start
8934       testptr(to, 4);
8935       jccb(Assembler::zero, L_fill_32_bytes);
8936       movl(Address(to, 0), value);
8937       addptr(to, 4);
8938       subl(count, 1<<shift);
8939     }
8940     BIND(L_fill_32_bytes);
8941     {
8942       assert( UseSSE >= 2, "supported cpu only" );
8943       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8944       if (UseAVX > 2) {
8945         movl(rtmp, 0xffff);
8946         kmovwl(k1, rtmp);
8947       }
8948       movdl(xtmp, value);
8949       if (UseAVX > 2 && UseUnalignedLoadStores) {
8950         // Fill 64-byte chunks
8951         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8952         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8953 
8954         subl(count, 16 << shift);
8955         jcc(Assembler::less, L_check_fill_32_bytes);
8956         align(16);
8957 
8958         BIND(L_fill_64_bytes_loop);
8959         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8960         addptr(to, 64);
8961         subl(count, 16 << shift);
8962         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8963 
8964         BIND(L_check_fill_32_bytes);
8965         addl(count, 8 << shift);
8966         jccb(Assembler::less, L_check_fill_8_bytes);
8967         vmovdqu(Address(to, 0), xtmp);
8968         addptr(to, 32);
8969         subl(count, 8 << shift);
8970 
8971         BIND(L_check_fill_8_bytes);
8972       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8973         // Fill 64-byte chunks
8974         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8975         vpbroadcastd(xtmp, xtmp);
8976 
8977         subl(count, 16 << shift);
8978         jcc(Assembler::less, L_check_fill_32_bytes);
8979         align(16);
8980 
8981         BIND(L_fill_64_bytes_loop);
8982         vmovdqu(Address(to, 0), xtmp);
8983         vmovdqu(Address(to, 32), xtmp);
8984         addptr(to, 64);
8985         subl(count, 16 << shift);
8986         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8987 
8988         BIND(L_check_fill_32_bytes);
8989         addl(count, 8 << shift);
8990         jccb(Assembler::less, L_check_fill_8_bytes);
8991         vmovdqu(Address(to, 0), xtmp);
8992         addptr(to, 32);
8993         subl(count, 8 << shift);
8994 
8995         BIND(L_check_fill_8_bytes);
8996         // clean upper bits of YMM registers
8997         movdl(xtmp, value);
8998         pshufd(xtmp, xtmp, 0);
8999       } else {
9000         // Fill 32-byte chunks
9001         pshufd(xtmp, xtmp, 0);
9002 
9003         subl(count, 8 << shift);
9004         jcc(Assembler::less, L_check_fill_8_bytes);
9005         align(16);
9006 
9007         BIND(L_fill_32_bytes_loop);
9008 
9009         if (UseUnalignedLoadStores) {
9010           movdqu(Address(to, 0), xtmp);
9011           movdqu(Address(to, 16), xtmp);
9012         } else {
9013           movq(Address(to, 0), xtmp);
9014           movq(Address(to, 8), xtmp);
9015           movq(Address(to, 16), xtmp);
9016           movq(Address(to, 24), xtmp);
9017         }
9018 
9019         addptr(to, 32);
9020         subl(count, 8 << shift);
9021         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9022 
9023         BIND(L_check_fill_8_bytes);
9024       }
9025       addl(count, 8 << shift);
9026       jccb(Assembler::zero, L_exit);
9027       jmpb(L_fill_8_bytes);
9028 
9029       //
9030       // length is too short, just fill qwords
9031       //
9032       BIND(L_fill_8_bytes_loop);
9033       movq(Address(to, 0), xtmp);
9034       addptr(to, 8);
9035       BIND(L_fill_8_bytes);
9036       subl(count, 1 << (shift + 1));
9037       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9038     }
9039   }
9040   // fill trailing 4 bytes
9041   BIND(L_fill_4_bytes);
9042   testl(count, 1<<shift);
9043   jccb(Assembler::zero, L_fill_2_bytes);
9044   movl(Address(to, 0), value);
9045   if (t == T_BYTE || t == T_SHORT) {
9046     addptr(to, 4);
9047     BIND(L_fill_2_bytes);
9048     // fill trailing 2 bytes
9049     testl(count, 1<<(shift-1));
9050     jccb(Assembler::zero, L_fill_byte);
9051     movw(Address(to, 0), value);
9052     if (t == T_BYTE) {
9053       addptr(to, 2);
9054       BIND(L_fill_byte);
9055       // fill trailing byte
9056       testl(count, 1);
9057       jccb(Assembler::zero, L_exit);
9058       movb(Address(to, 0), value);
9059     } else {
9060       BIND(L_fill_byte);
9061     }
9062   } else {
9063     BIND(L_fill_2_bytes);
9064   }
9065   BIND(L_exit);
9066 }
9067 
9068 // encode char[] to byte[] in ISO_8859_1
9069    //@HotSpotIntrinsicCandidate
9070    //private static int implEncodeISOArray(byte[] sa, int sp,
9071    //byte[] da, int dp, int len) {
9072    //  int i = 0;
9073    //  for (; i < len; i++) {
9074    //    char c = StringUTF16.getChar(sa, sp++);
9075    //    if (c > '\u00FF')
9076    //      break;
9077    //    da[dp++] = (byte)c;
9078    //  }
9079    //  return i;
9080    //}
9081 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
9082   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9083   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9084   Register tmp5, Register result) {
9085 
9086   // rsi: src
9087   // rdi: dst
9088   // rdx: len
9089   // rcx: tmp5
9090   // rax: result
9091   ShortBranchVerifier sbv(this);
9092   assert_different_registers(src, dst, len, tmp5, result);
9093   Label L_done, L_copy_1_char, L_copy_1_char_exit;
9094 
9095   // set result
9096   xorl(result, result);
9097   // check for zero length
9098   testl(len, len);
9099   jcc(Assembler::zero, L_done);
9100 
9101   movl(result, len);
9102 
9103   // Setup pointers
9104   lea(src, Address(src, len, Address::times_2)); // char[]
9105   lea(dst, Address(dst, len, Address::times_1)); // byte[]
9106   negptr(len);
9107 
9108   if (UseSSE42Intrinsics || UseAVX >= 2) {
9109     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
9110     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
9111 
9112     if (UseAVX >= 2) {
9113       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
9114       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9115       movdl(tmp1Reg, tmp5);
9116       vpbroadcastd(tmp1Reg, tmp1Reg);
9117       jmp(L_chars_32_check);
9118 
9119       bind(L_copy_32_chars);
9120       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
9121       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
9122       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9123       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9124       jccb(Assembler::notZero, L_copy_32_chars_exit);
9125       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9126       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
9127       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
9128 
9129       bind(L_chars_32_check);
9130       addptr(len, 32);
9131       jcc(Assembler::lessEqual, L_copy_32_chars);
9132 
9133       bind(L_copy_32_chars_exit);
9134       subptr(len, 16);
9135       jccb(Assembler::greater, L_copy_16_chars_exit);
9136 
9137     } else if (UseSSE42Intrinsics) {
9138       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9139       movdl(tmp1Reg, tmp5);
9140       pshufd(tmp1Reg, tmp1Reg, 0);
9141       jmpb(L_chars_16_check);
9142     }
9143 
9144     bind(L_copy_16_chars);
9145     if (UseAVX >= 2) {
9146       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9147       vptest(tmp2Reg, tmp1Reg);
9148       jcc(Assembler::notZero, L_copy_16_chars_exit);
9149       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9150       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9151     } else {
9152       if (UseAVX > 0) {
9153         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9154         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9155         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9156       } else {
9157         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9158         por(tmp2Reg, tmp3Reg);
9159         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9160         por(tmp2Reg, tmp4Reg);
9161       }
9162       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9163       jccb(Assembler::notZero, L_copy_16_chars_exit);
9164       packuswb(tmp3Reg, tmp4Reg);
9165     }
9166     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9167 
9168     bind(L_chars_16_check);
9169     addptr(len, 16);
9170     jcc(Assembler::lessEqual, L_copy_16_chars);
9171 
9172     bind(L_copy_16_chars_exit);
9173     if (UseAVX >= 2) {
9174       // clean upper bits of YMM registers
9175       vpxor(tmp2Reg, tmp2Reg);
9176       vpxor(tmp3Reg, tmp3Reg);
9177       vpxor(tmp4Reg, tmp4Reg);
9178       movdl(tmp1Reg, tmp5);
9179       pshufd(tmp1Reg, tmp1Reg, 0);
9180     }
9181     subptr(len, 8);
9182     jccb(Assembler::greater, L_copy_8_chars_exit);
9183 
9184     bind(L_copy_8_chars);
9185     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9186     ptest(tmp3Reg, tmp1Reg);
9187     jccb(Assembler::notZero, L_copy_8_chars_exit);
9188     packuswb(tmp3Reg, tmp1Reg);
9189     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9190     addptr(len, 8);
9191     jccb(Assembler::lessEqual, L_copy_8_chars);
9192 
9193     bind(L_copy_8_chars_exit);
9194     subptr(len, 8);
9195     jccb(Assembler::zero, L_done);
9196   }
9197 
9198   bind(L_copy_1_char);
9199   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9200   testl(tmp5, 0xff00);      // check if Unicode char
9201   jccb(Assembler::notZero, L_copy_1_char_exit);
9202   movb(Address(dst, len, Address::times_1, 0), tmp5);
9203   addptr(len, 1);
9204   jccb(Assembler::less, L_copy_1_char);
9205 
9206   bind(L_copy_1_char_exit);
9207   addptr(result, len); // len is negative count of not processed elements
9208 
9209   bind(L_done);
9210 }
9211 
9212 #ifdef _LP64
9213 /**
9214  * Helper for multiply_to_len().
9215  */
9216 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9217   addq(dest_lo, src1);
9218   adcq(dest_hi, 0);
9219   addq(dest_lo, src2);
9220   adcq(dest_hi, 0);
9221 }
9222 
9223 /**
9224  * Multiply 64 bit by 64 bit first loop.
9225  */
9226 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9227                                            Register y, Register y_idx, Register z,
9228                                            Register carry, Register product,
9229                                            Register idx, Register kdx) {
9230   //
9231   //  jlong carry, x[], y[], z[];
9232   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9233   //    huge_128 product = y[idx] * x[xstart] + carry;
9234   //    z[kdx] = (jlong)product;
9235   //    carry  = (jlong)(product >>> 64);
9236   //  }
9237   //  z[xstart] = carry;
9238   //
9239 
9240   Label L_first_loop, L_first_loop_exit;
9241   Label L_one_x, L_one_y, L_multiply;
9242 
9243   decrementl(xstart);
9244   jcc(Assembler::negative, L_one_x);
9245 
9246   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9247   rorq(x_xstart, 32); // convert big-endian to little-endian
9248 
9249   bind(L_first_loop);
9250   decrementl(idx);
9251   jcc(Assembler::negative, L_first_loop_exit);
9252   decrementl(idx);
9253   jcc(Assembler::negative, L_one_y);
9254   movq(y_idx, Address(y, idx, Address::times_4,  0));
9255   rorq(y_idx, 32); // convert big-endian to little-endian
9256   bind(L_multiply);
9257   movq(product, x_xstart);
9258   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9259   addq(product, carry);
9260   adcq(rdx, 0);
9261   subl(kdx, 2);
9262   movl(Address(z, kdx, Address::times_4,  4), product);
9263   shrq(product, 32);
9264   movl(Address(z, kdx, Address::times_4,  0), product);
9265   movq(carry, rdx);
9266   jmp(L_first_loop);
9267 
9268   bind(L_one_y);
9269   movl(y_idx, Address(y,  0));
9270   jmp(L_multiply);
9271 
9272   bind(L_one_x);
9273   movl(x_xstart, Address(x,  0));
9274   jmp(L_first_loop);
9275 
9276   bind(L_first_loop_exit);
9277 }
9278 
9279 /**
9280  * Multiply 64 bit by 64 bit and add 128 bit.
9281  */
9282 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9283                                             Register yz_idx, Register idx,
9284                                             Register carry, Register product, int offset) {
9285   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9286   //     z[kdx] = (jlong)product;
9287 
9288   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9289   rorq(yz_idx, 32); // convert big-endian to little-endian
9290   movq(product, x_xstart);
9291   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9292   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9293   rorq(yz_idx, 32); // convert big-endian to little-endian
9294 
9295   add2_with_carry(rdx, product, carry, yz_idx);
9296 
9297   movl(Address(z, idx, Address::times_4,  offset+4), product);
9298   shrq(product, 32);
9299   movl(Address(z, idx, Address::times_4,  offset), product);
9300 
9301 }
9302 
9303 /**
9304  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9305  */
9306 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9307                                              Register yz_idx, Register idx, Register jdx,
9308                                              Register carry, Register product,
9309                                              Register carry2) {
9310   //   jlong carry, x[], y[], z[];
9311   //   int kdx = ystart+1;
9312   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9313   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9314   //     z[kdx+idx+1] = (jlong)product;
9315   //     jlong carry2  = (jlong)(product >>> 64);
9316   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9317   //     z[kdx+idx] = (jlong)product;
9318   //     carry  = (jlong)(product >>> 64);
9319   //   }
9320   //   idx += 2;
9321   //   if (idx > 0) {
9322   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9323   //     z[kdx+idx] = (jlong)product;
9324   //     carry  = (jlong)(product >>> 64);
9325   //   }
9326   //
9327 
9328   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9329 
9330   movl(jdx, idx);
9331   andl(jdx, 0xFFFFFFFC);
9332   shrl(jdx, 2);
9333 
9334   bind(L_third_loop);
9335   subl(jdx, 1);
9336   jcc(Assembler::negative, L_third_loop_exit);
9337   subl(idx, 4);
9338 
9339   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9340   movq(carry2, rdx);
9341 
9342   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9343   movq(carry, rdx);
9344   jmp(L_third_loop);
9345 
9346   bind (L_third_loop_exit);
9347 
9348   andl (idx, 0x3);
9349   jcc(Assembler::zero, L_post_third_loop_done);
9350 
9351   Label L_check_1;
9352   subl(idx, 2);
9353   jcc(Assembler::negative, L_check_1);
9354 
9355   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9356   movq(carry, rdx);
9357 
9358   bind (L_check_1);
9359   addl (idx, 0x2);
9360   andl (idx, 0x1);
9361   subl(idx, 1);
9362   jcc(Assembler::negative, L_post_third_loop_done);
9363 
9364   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9365   movq(product, x_xstart);
9366   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9367   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9368 
9369   add2_with_carry(rdx, product, yz_idx, carry);
9370 
9371   movl(Address(z, idx, Address::times_4,  0), product);
9372   shrq(product, 32);
9373 
9374   shlq(rdx, 32);
9375   orq(product, rdx);
9376   movq(carry, product);
9377 
9378   bind(L_post_third_loop_done);
9379 }
9380 
9381 /**
9382  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9383  *
9384  */
9385 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9386                                                   Register carry, Register carry2,
9387                                                   Register idx, Register jdx,
9388                                                   Register yz_idx1, Register yz_idx2,
9389                                                   Register tmp, Register tmp3, Register tmp4) {
9390   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9391 
9392   //   jlong carry, x[], y[], z[];
9393   //   int kdx = ystart+1;
9394   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9395   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9396   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9397   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9398   //     carry  = (jlong)(tmp4 >>> 64);
9399   //     z[kdx+idx+1] = (jlong)tmp3;
9400   //     z[kdx+idx] = (jlong)tmp4;
9401   //   }
9402   //   idx += 2;
9403   //   if (idx > 0) {
9404   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9405   //     z[kdx+idx] = (jlong)yz_idx1;
9406   //     carry  = (jlong)(yz_idx1 >>> 64);
9407   //   }
9408   //
9409 
9410   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9411 
9412   movl(jdx, idx);
9413   andl(jdx, 0xFFFFFFFC);
9414   shrl(jdx, 2);
9415 
9416   bind(L_third_loop);
9417   subl(jdx, 1);
9418   jcc(Assembler::negative, L_third_loop_exit);
9419   subl(idx, 4);
9420 
9421   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9422   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9423   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9424   rorxq(yz_idx2, yz_idx2, 32);
9425 
9426   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9427   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9428 
9429   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9430   rorxq(yz_idx1, yz_idx1, 32);
9431   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9432   rorxq(yz_idx2, yz_idx2, 32);
9433 
9434   if (VM_Version::supports_adx()) {
9435     adcxq(tmp3, carry);
9436     adoxq(tmp3, yz_idx1);
9437 
9438     adcxq(tmp4, tmp);
9439     adoxq(tmp4, yz_idx2);
9440 
9441     movl(carry, 0); // does not affect flags
9442     adcxq(carry2, carry);
9443     adoxq(carry2, carry);
9444   } else {
9445     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9446     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9447   }
9448   movq(carry, carry2);
9449 
9450   movl(Address(z, idx, Address::times_4, 12), tmp3);
9451   shrq(tmp3, 32);
9452   movl(Address(z, idx, Address::times_4,  8), tmp3);
9453 
9454   movl(Address(z, idx, Address::times_4,  4), tmp4);
9455   shrq(tmp4, 32);
9456   movl(Address(z, idx, Address::times_4,  0), tmp4);
9457 
9458   jmp(L_third_loop);
9459 
9460   bind (L_third_loop_exit);
9461 
9462   andl (idx, 0x3);
9463   jcc(Assembler::zero, L_post_third_loop_done);
9464 
9465   Label L_check_1;
9466   subl(idx, 2);
9467   jcc(Assembler::negative, L_check_1);
9468 
9469   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9470   rorxq(yz_idx1, yz_idx1, 32);
9471   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9472   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9473   rorxq(yz_idx2, yz_idx2, 32);
9474 
9475   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9476 
9477   movl(Address(z, idx, Address::times_4,  4), tmp3);
9478   shrq(tmp3, 32);
9479   movl(Address(z, idx, Address::times_4,  0), tmp3);
9480   movq(carry, tmp4);
9481 
9482   bind (L_check_1);
9483   addl (idx, 0x2);
9484   andl (idx, 0x1);
9485   subl(idx, 1);
9486   jcc(Assembler::negative, L_post_third_loop_done);
9487   movl(tmp4, Address(y, idx, Address::times_4,  0));
9488   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9489   movl(tmp4, Address(z, idx, Address::times_4,  0));
9490 
9491   add2_with_carry(carry2, tmp3, tmp4, carry);
9492 
9493   movl(Address(z, idx, Address::times_4,  0), tmp3);
9494   shrq(tmp3, 32);
9495 
9496   shlq(carry2, 32);
9497   orq(tmp3, carry2);
9498   movq(carry, tmp3);
9499 
9500   bind(L_post_third_loop_done);
9501 }
9502 
9503 /**
9504  * Code for BigInteger::multiplyToLen() instrinsic.
9505  *
9506  * rdi: x
9507  * rax: xlen
9508  * rsi: y
9509  * rcx: ylen
9510  * r8:  z
9511  * r11: zlen
9512  * r12: tmp1
9513  * r13: tmp2
9514  * r14: tmp3
9515  * r15: tmp4
9516  * rbx: tmp5
9517  *
9518  */
9519 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9520                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9521   ShortBranchVerifier sbv(this);
9522   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9523 
9524   push(tmp1);
9525   push(tmp2);
9526   push(tmp3);
9527   push(tmp4);
9528   push(tmp5);
9529 
9530   push(xlen);
9531   push(zlen);
9532 
9533   const Register idx = tmp1;
9534   const Register kdx = tmp2;
9535   const Register xstart = tmp3;
9536 
9537   const Register y_idx = tmp4;
9538   const Register carry = tmp5;
9539   const Register product  = xlen;
9540   const Register x_xstart = zlen;  // reuse register
9541 
9542   // First Loop.
9543   //
9544   //  final static long LONG_MASK = 0xffffffffL;
9545   //  int xstart = xlen - 1;
9546   //  int ystart = ylen - 1;
9547   //  long carry = 0;
9548   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9549   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9550   //    z[kdx] = (int)product;
9551   //    carry = product >>> 32;
9552   //  }
9553   //  z[xstart] = (int)carry;
9554   //
9555 
9556   movl(idx, ylen);      // idx = ylen;
9557   movl(kdx, zlen);      // kdx = xlen+ylen;
9558   xorq(carry, carry);   // carry = 0;
9559 
9560   Label L_done;
9561 
9562   movl(xstart, xlen);
9563   decrementl(xstart);
9564   jcc(Assembler::negative, L_done);
9565 
9566   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9567 
9568   Label L_second_loop;
9569   testl(kdx, kdx);
9570   jcc(Assembler::zero, L_second_loop);
9571 
9572   Label L_carry;
9573   subl(kdx, 1);
9574   jcc(Assembler::zero, L_carry);
9575 
9576   movl(Address(z, kdx, Address::times_4,  0), carry);
9577   shrq(carry, 32);
9578   subl(kdx, 1);
9579 
9580   bind(L_carry);
9581   movl(Address(z, kdx, Address::times_4,  0), carry);
9582 
9583   // Second and third (nested) loops.
9584   //
9585   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9586   //   carry = 0;
9587   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9588   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9589   //                    (z[k] & LONG_MASK) + carry;
9590   //     z[k] = (int)product;
9591   //     carry = product >>> 32;
9592   //   }
9593   //   z[i] = (int)carry;
9594   // }
9595   //
9596   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9597 
9598   const Register jdx = tmp1;
9599 
9600   bind(L_second_loop);
9601   xorl(carry, carry);    // carry = 0;
9602   movl(jdx, ylen);       // j = ystart+1
9603 
9604   subl(xstart, 1);       // i = xstart-1;
9605   jcc(Assembler::negative, L_done);
9606 
9607   push (z);
9608 
9609   Label L_last_x;
9610   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9611   subl(xstart, 1);       // i = xstart-1;
9612   jcc(Assembler::negative, L_last_x);
9613 
9614   if (UseBMI2Instructions) {
9615     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9616     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9617   } else {
9618     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9619     rorq(x_xstart, 32);  // convert big-endian to little-endian
9620   }
9621 
9622   Label L_third_loop_prologue;
9623   bind(L_third_loop_prologue);
9624 
9625   push (x);
9626   push (xstart);
9627   push (ylen);
9628 
9629 
9630   if (UseBMI2Instructions) {
9631     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9632   } else { // !UseBMI2Instructions
9633     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9634   }
9635 
9636   pop(ylen);
9637   pop(xlen);
9638   pop(x);
9639   pop(z);
9640 
9641   movl(tmp3, xlen);
9642   addl(tmp3, 1);
9643   movl(Address(z, tmp3, Address::times_4,  0), carry);
9644   subl(tmp3, 1);
9645   jccb(Assembler::negative, L_done);
9646 
9647   shrq(carry, 32);
9648   movl(Address(z, tmp3, Address::times_4,  0), carry);
9649   jmp(L_second_loop);
9650 
9651   // Next infrequent code is moved outside loops.
9652   bind(L_last_x);
9653   if (UseBMI2Instructions) {
9654     movl(rdx, Address(x,  0));
9655   } else {
9656     movl(x_xstart, Address(x,  0));
9657   }
9658   jmp(L_third_loop_prologue);
9659 
9660   bind(L_done);
9661 
9662   pop(zlen);
9663   pop(xlen);
9664 
9665   pop(tmp5);
9666   pop(tmp4);
9667   pop(tmp3);
9668   pop(tmp2);
9669   pop(tmp1);
9670 }
9671 
9672 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9673   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9674   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9675   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9676   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9677   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9678   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9679   Label SAME_TILL_END, DONE;
9680   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9681 
9682   //scale is in rcx in both Win64 and Unix
9683   ShortBranchVerifier sbv(this);
9684 
9685   shlq(length);
9686   xorq(result, result);
9687 
9688   if ((UseAVX > 2) &&
9689       VM_Version::supports_avx512vlbw()) {
9690     set_vector_masking();  // opening of the stub context for programming mask registers
9691     cmpq(length, 64);
9692     jcc(Assembler::less, VECTOR32_TAIL);
9693     movq(tmp1, length);
9694     andq(tmp1, 0x3F);      // tail count
9695     andq(length, ~(0x3F)); //vector count
9696 
9697     bind(VECTOR64_LOOP);
9698     // AVX512 code to compare 64 byte vectors.
9699     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9700     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9701     kortestql(k7, k7);
9702     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9703     addq(result, 64);
9704     subq(length, 64);
9705     jccb(Assembler::notZero, VECTOR64_LOOP);
9706 
9707     //bind(VECTOR64_TAIL);
9708     testq(tmp1, tmp1);
9709     jcc(Assembler::zero, SAME_TILL_END);
9710 
9711     bind(VECTOR64_TAIL);
9712     // AVX512 code to compare upto 63 byte vectors.
9713     // Save k1
9714     kmovql(k3, k1);
9715     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9716     shlxq(tmp2, tmp2, tmp1);
9717     notq(tmp2);
9718     kmovql(k1, tmp2);
9719 
9720     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9721     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9722 
9723     ktestql(k7, k1);
9724     // Restore k1
9725     kmovql(k1, k3);
9726     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9727 
9728     bind(VECTOR64_NOT_EQUAL);
9729     kmovql(tmp1, k7);
9730     notq(tmp1);
9731     tzcntq(tmp1, tmp1);
9732     addq(result, tmp1);
9733     shrq(result);
9734     jmp(DONE);
9735     bind(VECTOR32_TAIL);
9736     clear_vector_masking();   // closing of the stub context for programming mask registers
9737   }
9738 
9739   cmpq(length, 8);
9740   jcc(Assembler::equal, VECTOR8_LOOP);
9741   jcc(Assembler::less, VECTOR4_TAIL);
9742 
9743   if (UseAVX >= 2) {
9744 
9745     cmpq(length, 16);
9746     jcc(Assembler::equal, VECTOR16_LOOP);
9747     jcc(Assembler::less, VECTOR8_LOOP);
9748 
9749     cmpq(length, 32);
9750     jccb(Assembler::less, VECTOR16_TAIL);
9751 
9752     subq(length, 32);
9753     bind(VECTOR32_LOOP);
9754     vmovdqu(rymm0, Address(obja, result));
9755     vmovdqu(rymm1, Address(objb, result));
9756     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9757     vptest(rymm2, rymm2);
9758     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9759     addq(result, 32);
9760     subq(length, 32);
9761     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9762     addq(length, 32);
9763     jcc(Assembler::equal, SAME_TILL_END);
9764     //falling through if less than 32 bytes left //close the branch here.
9765 
9766     bind(VECTOR16_TAIL);
9767     cmpq(length, 16);
9768     jccb(Assembler::less, VECTOR8_TAIL);
9769     bind(VECTOR16_LOOP);
9770     movdqu(rymm0, Address(obja, result));
9771     movdqu(rymm1, Address(objb, result));
9772     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9773     ptest(rymm2, rymm2);
9774     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9775     addq(result, 16);
9776     subq(length, 16);
9777     jcc(Assembler::equal, SAME_TILL_END);
9778     //falling through if less than 16 bytes left
9779   } else {//regular intrinsics
9780 
9781     cmpq(length, 16);
9782     jccb(Assembler::less, VECTOR8_TAIL);
9783 
9784     subq(length, 16);
9785     bind(VECTOR16_LOOP);
9786     movdqu(rymm0, Address(obja, result));
9787     movdqu(rymm1, Address(objb, result));
9788     pxor(rymm0, rymm1);
9789     ptest(rymm0, rymm0);
9790     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9791     addq(result, 16);
9792     subq(length, 16);
9793     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9794     addq(length, 16);
9795     jcc(Assembler::equal, SAME_TILL_END);
9796     //falling through if less than 16 bytes left
9797   }
9798 
9799   bind(VECTOR8_TAIL);
9800   cmpq(length, 8);
9801   jccb(Assembler::less, VECTOR4_TAIL);
9802   bind(VECTOR8_LOOP);
9803   movq(tmp1, Address(obja, result));
9804   movq(tmp2, Address(objb, result));
9805   xorq(tmp1, tmp2);
9806   testq(tmp1, tmp1);
9807   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9808   addq(result, 8);
9809   subq(length, 8);
9810   jcc(Assembler::equal, SAME_TILL_END);
9811   //falling through if less than 8 bytes left
9812 
9813   bind(VECTOR4_TAIL);
9814   cmpq(length, 4);
9815   jccb(Assembler::less, BYTES_TAIL);
9816   bind(VECTOR4_LOOP);
9817   movl(tmp1, Address(obja, result));
9818   xorl(tmp1, Address(objb, result));
9819   testl(tmp1, tmp1);
9820   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9821   addq(result, 4);
9822   subq(length, 4);
9823   jcc(Assembler::equal, SAME_TILL_END);
9824   //falling through if less than 4 bytes left
9825 
9826   bind(BYTES_TAIL);
9827   bind(BYTES_LOOP);
9828   load_unsigned_byte(tmp1, Address(obja, result));
9829   load_unsigned_byte(tmp2, Address(objb, result));
9830   xorl(tmp1, tmp2);
9831   testl(tmp1, tmp1);
9832   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9833   decq(length);
9834   jccb(Assembler::zero, SAME_TILL_END);
9835   incq(result);
9836   load_unsigned_byte(tmp1, Address(obja, result));
9837   load_unsigned_byte(tmp2, Address(objb, result));
9838   xorl(tmp1, tmp2);
9839   testl(tmp1, tmp1);
9840   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9841   decq(length);
9842   jccb(Assembler::zero, SAME_TILL_END);
9843   incq(result);
9844   load_unsigned_byte(tmp1, Address(obja, result));
9845   load_unsigned_byte(tmp2, Address(objb, result));
9846   xorl(tmp1, tmp2);
9847   testl(tmp1, tmp1);
9848   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9849   jmpb(SAME_TILL_END);
9850 
9851   if (UseAVX >= 2) {
9852     bind(VECTOR32_NOT_EQUAL);
9853     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9854     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9855     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9856     vpmovmskb(tmp1, rymm0);
9857     bsfq(tmp1, tmp1);
9858     addq(result, tmp1);
9859     shrq(result);
9860     jmpb(DONE);
9861   }
9862 
9863   bind(VECTOR16_NOT_EQUAL);
9864   if (UseAVX >= 2) {
9865     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9866     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9867     pxor(rymm0, rymm2);
9868   } else {
9869     pcmpeqb(rymm2, rymm2);
9870     pxor(rymm0, rymm1);
9871     pcmpeqb(rymm0, rymm1);
9872     pxor(rymm0, rymm2);
9873   }
9874   pmovmskb(tmp1, rymm0);
9875   bsfq(tmp1, tmp1);
9876   addq(result, tmp1);
9877   shrq(result);
9878   jmpb(DONE);
9879 
9880   bind(VECTOR8_NOT_EQUAL);
9881   bind(VECTOR4_NOT_EQUAL);
9882   bsfq(tmp1, tmp1);
9883   shrq(tmp1, 3);
9884   addq(result, tmp1);
9885   bind(BYTES_NOT_EQUAL);
9886   shrq(result);
9887   jmpb(DONE);
9888 
9889   bind(SAME_TILL_END);
9890   mov64(result, -1);
9891 
9892   bind(DONE);
9893 }
9894 
9895 //Helper functions for square_to_len()
9896 
9897 /**
9898  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9899  * Preserves x and z and modifies rest of the registers.
9900  */
9901 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9902   // Perform square and right shift by 1
9903   // Handle odd xlen case first, then for even xlen do the following
9904   // jlong carry = 0;
9905   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9906   //     huge_128 product = x[j:j+1] * x[j:j+1];
9907   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9908   //     z[i+2:i+3] = (jlong)(product >>> 1);
9909   //     carry = (jlong)product;
9910   // }
9911 
9912   xorq(tmp5, tmp5);     // carry
9913   xorq(rdxReg, rdxReg);
9914   xorl(tmp1, tmp1);     // index for x
9915   xorl(tmp4, tmp4);     // index for z
9916 
9917   Label L_first_loop, L_first_loop_exit;
9918 
9919   testl(xlen, 1);
9920   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9921 
9922   // Square and right shift by 1 the odd element using 32 bit multiply
9923   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9924   imulq(raxReg, raxReg);
9925   shrq(raxReg, 1);
9926   adcq(tmp5, 0);
9927   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9928   incrementl(tmp1);
9929   addl(tmp4, 2);
9930 
9931   // Square and  right shift by 1 the rest using 64 bit multiply
9932   bind(L_first_loop);
9933   cmpptr(tmp1, xlen);
9934   jccb(Assembler::equal, L_first_loop_exit);
9935 
9936   // Square
9937   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9938   rorq(raxReg, 32);    // convert big-endian to little-endian
9939   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9940 
9941   // Right shift by 1 and save carry
9942   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9943   rcrq(rdxReg, 1);
9944   rcrq(raxReg, 1);
9945   adcq(tmp5, 0);
9946 
9947   // Store result in z
9948   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9949   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9950 
9951   // Update indices for x and z
9952   addl(tmp1, 2);
9953   addl(tmp4, 4);
9954   jmp(L_first_loop);
9955 
9956   bind(L_first_loop_exit);
9957 }
9958 
9959 
9960 /**
9961  * Perform the following multiply add operation using BMI2 instructions
9962  * carry:sum = sum + op1*op2 + carry
9963  * op2 should be in rdx
9964  * op2 is preserved, all other registers are modified
9965  */
9966 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9967   // assert op2 is rdx
9968   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9969   addq(sum, carry);
9970   adcq(tmp2, 0);
9971   addq(sum, op1);
9972   adcq(tmp2, 0);
9973   movq(carry, tmp2);
9974 }
9975 
9976 /**
9977  * Perform the following multiply add operation:
9978  * carry:sum = sum + op1*op2 + carry
9979  * Preserves op1, op2 and modifies rest of registers
9980  */
9981 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9982   // rdx:rax = op1 * op2
9983   movq(raxReg, op2);
9984   mulq(op1);
9985 
9986   //  rdx:rax = sum + carry + rdx:rax
9987   addq(sum, carry);
9988   adcq(rdxReg, 0);
9989   addq(sum, raxReg);
9990   adcq(rdxReg, 0);
9991 
9992   // carry:sum = rdx:sum
9993   movq(carry, rdxReg);
9994 }
9995 
9996 /**
9997  * Add 64 bit long carry into z[] with carry propogation.
9998  * Preserves z and carry register values and modifies rest of registers.
9999  *
10000  */
10001 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
10002   Label L_fourth_loop, L_fourth_loop_exit;
10003 
10004   movl(tmp1, 1);
10005   subl(zlen, 2);
10006   addq(Address(z, zlen, Address::times_4, 0), carry);
10007 
10008   bind(L_fourth_loop);
10009   jccb(Assembler::carryClear, L_fourth_loop_exit);
10010   subl(zlen, 2);
10011   jccb(Assembler::negative, L_fourth_loop_exit);
10012   addq(Address(z, zlen, Address::times_4, 0), tmp1);
10013   jmp(L_fourth_loop);
10014   bind(L_fourth_loop_exit);
10015 }
10016 
10017 /**
10018  * Shift z[] left by 1 bit.
10019  * Preserves x, len, z and zlen registers and modifies rest of the registers.
10020  *
10021  */
10022 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
10023 
10024   Label L_fifth_loop, L_fifth_loop_exit;
10025 
10026   // Fifth loop
10027   // Perform primitiveLeftShift(z, zlen, 1)
10028 
10029   const Register prev_carry = tmp1;
10030   const Register new_carry = tmp4;
10031   const Register value = tmp2;
10032   const Register zidx = tmp3;
10033 
10034   // int zidx, carry;
10035   // long value;
10036   // carry = 0;
10037   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
10038   //    (carry:value)  = (z[i] << 1) | carry ;
10039   //    z[i] = value;
10040   // }
10041 
10042   movl(zidx, zlen);
10043   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
10044 
10045   bind(L_fifth_loop);
10046   decl(zidx);  // Use decl to preserve carry flag
10047   decl(zidx);
10048   jccb(Assembler::negative, L_fifth_loop_exit);
10049 
10050   if (UseBMI2Instructions) {
10051      movq(value, Address(z, zidx, Address::times_4, 0));
10052      rclq(value, 1);
10053      rorxq(value, value, 32);
10054      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10055   }
10056   else {
10057     // clear new_carry
10058     xorl(new_carry, new_carry);
10059 
10060     // Shift z[i] by 1, or in previous carry and save new carry
10061     movq(value, Address(z, zidx, Address::times_4, 0));
10062     shlq(value, 1);
10063     adcl(new_carry, 0);
10064 
10065     orq(value, prev_carry);
10066     rorq(value, 0x20);
10067     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10068 
10069     // Set previous carry = new carry
10070     movl(prev_carry, new_carry);
10071   }
10072   jmp(L_fifth_loop);
10073 
10074   bind(L_fifth_loop_exit);
10075 }
10076 
10077 
10078 /**
10079  * Code for BigInteger::squareToLen() intrinsic
10080  *
10081  * rdi: x
10082  * rsi: len
10083  * r8:  z
10084  * rcx: zlen
10085  * r12: tmp1
10086  * r13: tmp2
10087  * r14: tmp3
10088  * r15: tmp4
10089  * rbx: tmp5
10090  *
10091  */
10092 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) {
10093 
10094   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;
10095   push(tmp1);
10096   push(tmp2);
10097   push(tmp3);
10098   push(tmp4);
10099   push(tmp5);
10100 
10101   // First loop
10102   // Store the squares, right shifted one bit (i.e., divided by 2).
10103   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
10104 
10105   // Add in off-diagonal sums.
10106   //
10107   // Second, third (nested) and fourth loops.
10108   // zlen +=2;
10109   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
10110   //    carry = 0;
10111   //    long op2 = x[xidx:xidx+1];
10112   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
10113   //       k -= 2;
10114   //       long op1 = x[j:j+1];
10115   //       long sum = z[k:k+1];
10116   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
10117   //       z[k:k+1] = sum;
10118   //    }
10119   //    add_one_64(z, k, carry, tmp_regs);
10120   // }
10121 
10122   const Register carry = tmp5;
10123   const Register sum = tmp3;
10124   const Register op1 = tmp4;
10125   Register op2 = tmp2;
10126 
10127   push(zlen);
10128   push(len);
10129   addl(zlen,2);
10130   bind(L_second_loop);
10131   xorq(carry, carry);
10132   subl(zlen, 4);
10133   subl(len, 2);
10134   push(zlen);
10135   push(len);
10136   cmpl(len, 0);
10137   jccb(Assembler::lessEqual, L_second_loop_exit);
10138 
10139   // Multiply an array by one 64 bit long.
10140   if (UseBMI2Instructions) {
10141     op2 = rdxReg;
10142     movq(op2, Address(x, len, Address::times_4,  0));
10143     rorxq(op2, op2, 32);
10144   }
10145   else {
10146     movq(op2, Address(x, len, Address::times_4,  0));
10147     rorq(op2, 32);
10148   }
10149 
10150   bind(L_third_loop);
10151   decrementl(len);
10152   jccb(Assembler::negative, L_third_loop_exit);
10153   decrementl(len);
10154   jccb(Assembler::negative, L_last_x);
10155 
10156   movq(op1, Address(x, len, Address::times_4,  0));
10157   rorq(op1, 32);
10158 
10159   bind(L_multiply);
10160   subl(zlen, 2);
10161   movq(sum, Address(z, zlen, Address::times_4,  0));
10162 
10163   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10164   if (UseBMI2Instructions) {
10165     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10166   }
10167   else {
10168     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10169   }
10170 
10171   movq(Address(z, zlen, Address::times_4, 0), sum);
10172 
10173   jmp(L_third_loop);
10174   bind(L_third_loop_exit);
10175 
10176   // Fourth loop
10177   // Add 64 bit long carry into z with carry propogation.
10178   // Uses offsetted zlen.
10179   add_one_64(z, zlen, carry, tmp1);
10180 
10181   pop(len);
10182   pop(zlen);
10183   jmp(L_second_loop);
10184 
10185   // Next infrequent code is moved outside loops.
10186   bind(L_last_x);
10187   movl(op1, Address(x, 0));
10188   jmp(L_multiply);
10189 
10190   bind(L_second_loop_exit);
10191   pop(len);
10192   pop(zlen);
10193   pop(len);
10194   pop(zlen);
10195 
10196   // Fifth loop
10197   // Shift z left 1 bit.
10198   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10199 
10200   // z[zlen-1] |= x[len-1] & 1;
10201   movl(tmp3, Address(x, len, Address::times_4, -4));
10202   andl(tmp3, 1);
10203   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10204 
10205   pop(tmp5);
10206   pop(tmp4);
10207   pop(tmp3);
10208   pop(tmp2);
10209   pop(tmp1);
10210 }
10211 
10212 /**
10213  * Helper function for mul_add()
10214  * Multiply the in[] by int k and add to out[] starting at offset offs using
10215  * 128 bit by 32 bit multiply and return the carry in tmp5.
10216  * Only quad int aligned length of in[] is operated on in this function.
10217  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10218  * This function preserves out, in and k registers.
10219  * len and offset point to the appropriate index in "in" & "out" correspondingly
10220  * tmp5 has the carry.
10221  * other registers are temporary and are modified.
10222  *
10223  */
10224 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10225   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10226   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10227 
10228   Label L_first_loop, L_first_loop_exit;
10229 
10230   movl(tmp1, len);
10231   shrl(tmp1, 2);
10232 
10233   bind(L_first_loop);
10234   subl(tmp1, 1);
10235   jccb(Assembler::negative, L_first_loop_exit);
10236 
10237   subl(len, 4);
10238   subl(offset, 4);
10239 
10240   Register op2 = tmp2;
10241   const Register sum = tmp3;
10242   const Register op1 = tmp4;
10243   const Register carry = tmp5;
10244 
10245   if (UseBMI2Instructions) {
10246     op2 = rdxReg;
10247   }
10248 
10249   movq(op1, Address(in, len, Address::times_4,  8));
10250   rorq(op1, 32);
10251   movq(sum, Address(out, offset, Address::times_4,  8));
10252   rorq(sum, 32);
10253   if (UseBMI2Instructions) {
10254     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10255   }
10256   else {
10257     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10258   }
10259   // Store back in big endian from little endian
10260   rorq(sum, 0x20);
10261   movq(Address(out, offset, Address::times_4,  8), sum);
10262 
10263   movq(op1, Address(in, len, Address::times_4,  0));
10264   rorq(op1, 32);
10265   movq(sum, Address(out, offset, Address::times_4,  0));
10266   rorq(sum, 32);
10267   if (UseBMI2Instructions) {
10268     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10269   }
10270   else {
10271     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10272   }
10273   // Store back in big endian from little endian
10274   rorq(sum, 0x20);
10275   movq(Address(out, offset, Address::times_4,  0), sum);
10276 
10277   jmp(L_first_loop);
10278   bind(L_first_loop_exit);
10279 }
10280 
10281 /**
10282  * Code for BigInteger::mulAdd() intrinsic
10283  *
10284  * rdi: out
10285  * rsi: in
10286  * r11: offs (out.length - offset)
10287  * rcx: len
10288  * r8:  k
10289  * r12: tmp1
10290  * r13: tmp2
10291  * r14: tmp3
10292  * r15: tmp4
10293  * rbx: tmp5
10294  * Multiply the in[] by word k and add to out[], return the carry in rax
10295  */
10296 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10297    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10298    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10299 
10300   Label L_carry, L_last_in, L_done;
10301 
10302 // carry = 0;
10303 // for (int j=len-1; j >= 0; j--) {
10304 //    long product = (in[j] & LONG_MASK) * kLong +
10305 //                   (out[offs] & LONG_MASK) + carry;
10306 //    out[offs--] = (int)product;
10307 //    carry = product >>> 32;
10308 // }
10309 //
10310   push(tmp1);
10311   push(tmp2);
10312   push(tmp3);
10313   push(tmp4);
10314   push(tmp5);
10315 
10316   Register op2 = tmp2;
10317   const Register sum = tmp3;
10318   const Register op1 = tmp4;
10319   const Register carry =  tmp5;
10320 
10321   if (UseBMI2Instructions) {
10322     op2 = rdxReg;
10323     movl(op2, k);
10324   }
10325   else {
10326     movl(op2, k);
10327   }
10328 
10329   xorq(carry, carry);
10330 
10331   //First loop
10332 
10333   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10334   //The carry is in tmp5
10335   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10336 
10337   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10338   decrementl(len);
10339   jccb(Assembler::negative, L_carry);
10340   decrementl(len);
10341   jccb(Assembler::negative, L_last_in);
10342 
10343   movq(op1, Address(in, len, Address::times_4,  0));
10344   rorq(op1, 32);
10345 
10346   subl(offs, 2);
10347   movq(sum, Address(out, offs, Address::times_4,  0));
10348   rorq(sum, 32);
10349 
10350   if (UseBMI2Instructions) {
10351     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10352   }
10353   else {
10354     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10355   }
10356 
10357   // Store back in big endian from little endian
10358   rorq(sum, 0x20);
10359   movq(Address(out, offs, Address::times_4,  0), sum);
10360 
10361   testl(len, len);
10362   jccb(Assembler::zero, L_carry);
10363 
10364   //Multiply the last in[] entry, if any
10365   bind(L_last_in);
10366   movl(op1, Address(in, 0));
10367   movl(sum, Address(out, offs, Address::times_4,  -4));
10368 
10369   movl(raxReg, k);
10370   mull(op1); //tmp4 * eax -> edx:eax
10371   addl(sum, carry);
10372   adcl(rdxReg, 0);
10373   addl(sum, raxReg);
10374   adcl(rdxReg, 0);
10375   movl(carry, rdxReg);
10376 
10377   movl(Address(out, offs, Address::times_4,  -4), sum);
10378 
10379   bind(L_carry);
10380   //return tmp5/carry as carry in rax
10381   movl(rax, carry);
10382 
10383   bind(L_done);
10384   pop(tmp5);
10385   pop(tmp4);
10386   pop(tmp3);
10387   pop(tmp2);
10388   pop(tmp1);
10389 }
10390 #endif
10391 
10392 /**
10393  * Emits code to update CRC-32 with a byte value according to constants in table
10394  *
10395  * @param [in,out]crc   Register containing the crc.
10396  * @param [in]val       Register containing the byte to fold into the CRC.
10397  * @param [in]table     Register containing the table of crc constants.
10398  *
10399  * uint32_t crc;
10400  * val = crc_table[(val ^ crc) & 0xFF];
10401  * crc = val ^ (crc >> 8);
10402  *
10403  */
10404 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10405   xorl(val, crc);
10406   andl(val, 0xFF);
10407   shrl(crc, 8); // unsigned shift
10408   xorl(crc, Address(table, val, Address::times_4, 0));
10409 }
10410 
10411 /**
10412  * Fold 128-bit data chunk
10413  */
10414 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10415   if (UseAVX > 0) {
10416     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10417     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10418     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10419     pxor(xcrc, xtmp);
10420   } else {
10421     movdqa(xtmp, xcrc);
10422     pclmulhdq(xtmp, xK);   // [123:64]
10423     pclmulldq(xcrc, xK);   // [63:0]
10424     pxor(xcrc, xtmp);
10425     movdqu(xtmp, Address(buf, offset));
10426     pxor(xcrc, xtmp);
10427   }
10428 }
10429 
10430 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10431   if (UseAVX > 0) {
10432     vpclmulhdq(xtmp, xK, xcrc);
10433     vpclmulldq(xcrc, xK, xcrc);
10434     pxor(xcrc, xbuf);
10435     pxor(xcrc, xtmp);
10436   } else {
10437     movdqa(xtmp, xcrc);
10438     pclmulhdq(xtmp, xK);
10439     pclmulldq(xcrc, xK);
10440     pxor(xcrc, xbuf);
10441     pxor(xcrc, xtmp);
10442   }
10443 }
10444 
10445 /**
10446  * 8-bit folds to compute 32-bit CRC
10447  *
10448  * uint64_t xcrc;
10449  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10450  */
10451 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10452   movdl(tmp, xcrc);
10453   andl(tmp, 0xFF);
10454   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10455   psrldq(xcrc, 1); // unsigned shift one byte
10456   pxor(xcrc, xtmp);
10457 }
10458 
10459 /**
10460  * uint32_t crc;
10461  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10462  */
10463 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10464   movl(tmp, crc);
10465   andl(tmp, 0xFF);
10466   shrl(crc, 8);
10467   xorl(crc, Address(table, tmp, Address::times_4, 0));
10468 }
10469 
10470 /**
10471  * @param crc   register containing existing CRC (32-bit)
10472  * @param buf   register pointing to input byte buffer (byte*)
10473  * @param len   register containing number of bytes
10474  * @param table register that will contain address of CRC table
10475  * @param tmp   scratch register
10476  */
10477 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10478   assert_different_registers(crc, buf, len, table, tmp, rax);
10479 
10480   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10481   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10482 
10483   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10484   // context for the registers used, where all instructions below are using 128-bit mode
10485   // On EVEX without VL and BW, these instructions will all be AVX.
10486   if (VM_Version::supports_avx512vlbw()) {
10487     movl(tmp, 0xffff);
10488     kmovwl(k1, tmp);
10489   }
10490 
10491   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10492   notl(crc); // ~crc
10493   cmpl(len, 16);
10494   jcc(Assembler::less, L_tail);
10495 
10496   // Align buffer to 16 bytes
10497   movl(tmp, buf);
10498   andl(tmp, 0xF);
10499   jccb(Assembler::zero, L_aligned);
10500   subl(tmp,  16);
10501   addl(len, tmp);
10502 
10503   align(4);
10504   BIND(L_align_loop);
10505   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10506   update_byte_crc32(crc, rax, table);
10507   increment(buf);
10508   incrementl(tmp);
10509   jccb(Assembler::less, L_align_loop);
10510 
10511   BIND(L_aligned);
10512   movl(tmp, len); // save
10513   shrl(len, 4);
10514   jcc(Assembler::zero, L_tail_restore);
10515 
10516   // Fold crc into first bytes of vector
10517   movdqa(xmm1, Address(buf, 0));
10518   movdl(rax, xmm1);
10519   xorl(crc, rax);
10520   if (VM_Version::supports_sse4_1()) {
10521     pinsrd(xmm1, crc, 0);
10522   } else {
10523     pinsrw(xmm1, crc, 0);
10524     shrl(crc, 16);
10525     pinsrw(xmm1, crc, 1);
10526   }
10527   addptr(buf, 16);
10528   subl(len, 4); // len > 0
10529   jcc(Assembler::less, L_fold_tail);
10530 
10531   movdqa(xmm2, Address(buf,  0));
10532   movdqa(xmm3, Address(buf, 16));
10533   movdqa(xmm4, Address(buf, 32));
10534   addptr(buf, 48);
10535   subl(len, 3);
10536   jcc(Assembler::lessEqual, L_fold_512b);
10537 
10538   // Fold total 512 bits of polynomial on each iteration,
10539   // 128 bits per each of 4 parallel streams.
10540   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10541 
10542   align(32);
10543   BIND(L_fold_512b_loop);
10544   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10545   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10546   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10547   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10548   addptr(buf, 64);
10549   subl(len, 4);
10550   jcc(Assembler::greater, L_fold_512b_loop);
10551 
10552   // Fold 512 bits to 128 bits.
10553   BIND(L_fold_512b);
10554   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10555   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10556   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10557   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10558 
10559   // Fold the rest of 128 bits data chunks
10560   BIND(L_fold_tail);
10561   addl(len, 3);
10562   jccb(Assembler::lessEqual, L_fold_128b);
10563   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10564 
10565   BIND(L_fold_tail_loop);
10566   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10567   addptr(buf, 16);
10568   decrementl(len);
10569   jccb(Assembler::greater, L_fold_tail_loop);
10570 
10571   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10572   BIND(L_fold_128b);
10573   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10574   if (UseAVX > 0) {
10575     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10576     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10577     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10578   } else {
10579     movdqa(xmm2, xmm0);
10580     pclmulqdq(xmm2, xmm1, 0x1);
10581     movdqa(xmm3, xmm0);
10582     pand(xmm3, xmm2);
10583     pclmulqdq(xmm0, xmm3, 0x1);
10584   }
10585   psrldq(xmm1, 8);
10586   psrldq(xmm2, 4);
10587   pxor(xmm0, xmm1);
10588   pxor(xmm0, xmm2);
10589 
10590   // 8 8-bit folds to compute 32-bit CRC.
10591   for (int j = 0; j < 4; j++) {
10592     fold_8bit_crc32(xmm0, table, xmm1, rax);
10593   }
10594   movdl(crc, xmm0); // mov 32 bits to general register
10595   for (int j = 0; j < 4; j++) {
10596     fold_8bit_crc32(crc, table, rax);
10597   }
10598 
10599   BIND(L_tail_restore);
10600   movl(len, tmp); // restore
10601   BIND(L_tail);
10602   andl(len, 0xf);
10603   jccb(Assembler::zero, L_exit);
10604 
10605   // Fold the rest of bytes
10606   align(4);
10607   BIND(L_tail_loop);
10608   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10609   update_byte_crc32(crc, rax, table);
10610   increment(buf);
10611   decrementl(len);
10612   jccb(Assembler::greater, L_tail_loop);
10613 
10614   BIND(L_exit);
10615   notl(crc); // ~c
10616 }
10617 
10618 #ifdef _LP64
10619 // S. Gueron / Information Processing Letters 112 (2012) 184
10620 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10621 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10622 // Output: the 64-bit carry-less product of B * CONST
10623 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10624                                      Register tmp1, Register tmp2, Register tmp3) {
10625   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10626   if (n > 0) {
10627     addq(tmp3, n * 256 * 8);
10628   }
10629   //    Q1 = TABLEExt[n][B & 0xFF];
10630   movl(tmp1, in);
10631   andl(tmp1, 0x000000FF);
10632   shll(tmp1, 3);
10633   addq(tmp1, tmp3);
10634   movq(tmp1, Address(tmp1, 0));
10635 
10636   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10637   movl(tmp2, in);
10638   shrl(tmp2, 8);
10639   andl(tmp2, 0x000000FF);
10640   shll(tmp2, 3);
10641   addq(tmp2, tmp3);
10642   movq(tmp2, Address(tmp2, 0));
10643 
10644   shlq(tmp2, 8);
10645   xorq(tmp1, tmp2);
10646 
10647   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10648   movl(tmp2, in);
10649   shrl(tmp2, 16);
10650   andl(tmp2, 0x000000FF);
10651   shll(tmp2, 3);
10652   addq(tmp2, tmp3);
10653   movq(tmp2, Address(tmp2, 0));
10654 
10655   shlq(tmp2, 16);
10656   xorq(tmp1, tmp2);
10657 
10658   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10659   shrl(in, 24);
10660   andl(in, 0x000000FF);
10661   shll(in, 3);
10662   addq(in, tmp3);
10663   movq(in, Address(in, 0));
10664 
10665   shlq(in, 24);
10666   xorq(in, tmp1);
10667   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10668 }
10669 
10670 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10671                                       Register in_out,
10672                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10673                                       XMMRegister w_xtmp2,
10674                                       Register tmp1,
10675                                       Register n_tmp2, Register n_tmp3) {
10676   if (is_pclmulqdq_supported) {
10677     movdl(w_xtmp1, in_out); // modified blindly
10678 
10679     movl(tmp1, const_or_pre_comp_const_index);
10680     movdl(w_xtmp2, tmp1);
10681     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10682 
10683     movdq(in_out, w_xtmp1);
10684   } else {
10685     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10686   }
10687 }
10688 
10689 // Recombination Alternative 2: No bit-reflections
10690 // T1 = (CRC_A * U1) << 1
10691 // T2 = (CRC_B * U2) << 1
10692 // C1 = T1 >> 32
10693 // C2 = T2 >> 32
10694 // T1 = T1 & 0xFFFFFFFF
10695 // T2 = T2 & 0xFFFFFFFF
10696 // T1 = CRC32(0, T1)
10697 // T2 = CRC32(0, T2)
10698 // C1 = C1 ^ T1
10699 // C2 = C2 ^ T2
10700 // CRC = C1 ^ C2 ^ CRC_C
10701 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,
10702                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10703                                      Register tmp1, Register tmp2,
10704                                      Register n_tmp3) {
10705   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10706   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10707   shlq(in_out, 1);
10708   movl(tmp1, in_out);
10709   shrq(in_out, 32);
10710   xorl(tmp2, tmp2);
10711   crc32(tmp2, tmp1, 4);
10712   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10713   shlq(in1, 1);
10714   movl(tmp1, in1);
10715   shrq(in1, 32);
10716   xorl(tmp2, tmp2);
10717   crc32(tmp2, tmp1, 4);
10718   xorl(in1, tmp2);
10719   xorl(in_out, in1);
10720   xorl(in_out, in2);
10721 }
10722 
10723 // Set N to predefined value
10724 // Subtract from a lenght of a buffer
10725 // execute in a loop:
10726 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10727 // for i = 1 to N do
10728 //  CRC_A = CRC32(CRC_A, A[i])
10729 //  CRC_B = CRC32(CRC_B, B[i])
10730 //  CRC_C = CRC32(CRC_C, C[i])
10731 // end for
10732 // Recombine
10733 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,
10734                                        Register in_out1, Register in_out2, Register in_out3,
10735                                        Register tmp1, Register tmp2, Register tmp3,
10736                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10737                                        Register tmp4, Register tmp5,
10738                                        Register n_tmp6) {
10739   Label L_processPartitions;
10740   Label L_processPartition;
10741   Label L_exit;
10742 
10743   bind(L_processPartitions);
10744   cmpl(in_out1, 3 * size);
10745   jcc(Assembler::less, L_exit);
10746     xorl(tmp1, tmp1);
10747     xorl(tmp2, tmp2);
10748     movq(tmp3, in_out2);
10749     addq(tmp3, size);
10750 
10751     bind(L_processPartition);
10752       crc32(in_out3, Address(in_out2, 0), 8);
10753       crc32(tmp1, Address(in_out2, size), 8);
10754       crc32(tmp2, Address(in_out2, size * 2), 8);
10755       addq(in_out2, 8);
10756       cmpq(in_out2, tmp3);
10757       jcc(Assembler::less, L_processPartition);
10758     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10759             w_xtmp1, w_xtmp2, w_xtmp3,
10760             tmp4, tmp5,
10761             n_tmp6);
10762     addq(in_out2, 2 * size);
10763     subl(in_out1, 3 * size);
10764     jmp(L_processPartitions);
10765 
10766   bind(L_exit);
10767 }
10768 #else
10769 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10770                                      Register tmp1, Register tmp2, Register tmp3,
10771                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10772   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10773   if (n > 0) {
10774     addl(tmp3, n * 256 * 8);
10775   }
10776   //    Q1 = TABLEExt[n][B & 0xFF];
10777   movl(tmp1, in_out);
10778   andl(tmp1, 0x000000FF);
10779   shll(tmp1, 3);
10780   addl(tmp1, tmp3);
10781   movq(xtmp1, Address(tmp1, 0));
10782 
10783   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10784   movl(tmp2, in_out);
10785   shrl(tmp2, 8);
10786   andl(tmp2, 0x000000FF);
10787   shll(tmp2, 3);
10788   addl(tmp2, tmp3);
10789   movq(xtmp2, Address(tmp2, 0));
10790 
10791   psllq(xtmp2, 8);
10792   pxor(xtmp1, xtmp2);
10793 
10794   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10795   movl(tmp2, in_out);
10796   shrl(tmp2, 16);
10797   andl(tmp2, 0x000000FF);
10798   shll(tmp2, 3);
10799   addl(tmp2, tmp3);
10800   movq(xtmp2, Address(tmp2, 0));
10801 
10802   psllq(xtmp2, 16);
10803   pxor(xtmp1, xtmp2);
10804 
10805   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10806   shrl(in_out, 24);
10807   andl(in_out, 0x000000FF);
10808   shll(in_out, 3);
10809   addl(in_out, tmp3);
10810   movq(xtmp2, Address(in_out, 0));
10811 
10812   psllq(xtmp2, 24);
10813   pxor(xtmp1, xtmp2); // Result in CXMM
10814   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10815 }
10816 
10817 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10818                                       Register in_out,
10819                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10820                                       XMMRegister w_xtmp2,
10821                                       Register tmp1,
10822                                       Register n_tmp2, Register n_tmp3) {
10823   if (is_pclmulqdq_supported) {
10824     movdl(w_xtmp1, in_out);
10825 
10826     movl(tmp1, const_or_pre_comp_const_index);
10827     movdl(w_xtmp2, tmp1);
10828     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10829     // Keep result in XMM since GPR is 32 bit in length
10830   } else {
10831     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10832   }
10833 }
10834 
10835 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,
10836                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10837                                      Register tmp1, Register tmp2,
10838                                      Register n_tmp3) {
10839   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10840   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10841 
10842   psllq(w_xtmp1, 1);
10843   movdl(tmp1, w_xtmp1);
10844   psrlq(w_xtmp1, 32);
10845   movdl(in_out, w_xtmp1);
10846 
10847   xorl(tmp2, tmp2);
10848   crc32(tmp2, tmp1, 4);
10849   xorl(in_out, tmp2);
10850 
10851   psllq(w_xtmp2, 1);
10852   movdl(tmp1, w_xtmp2);
10853   psrlq(w_xtmp2, 32);
10854   movdl(in1, w_xtmp2);
10855 
10856   xorl(tmp2, tmp2);
10857   crc32(tmp2, tmp1, 4);
10858   xorl(in1, tmp2);
10859   xorl(in_out, in1);
10860   xorl(in_out, in2);
10861 }
10862 
10863 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,
10864                                        Register in_out1, Register in_out2, Register in_out3,
10865                                        Register tmp1, Register tmp2, Register tmp3,
10866                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10867                                        Register tmp4, Register tmp5,
10868                                        Register n_tmp6) {
10869   Label L_processPartitions;
10870   Label L_processPartition;
10871   Label L_exit;
10872 
10873   bind(L_processPartitions);
10874   cmpl(in_out1, 3 * size);
10875   jcc(Assembler::less, L_exit);
10876     xorl(tmp1, tmp1);
10877     xorl(tmp2, tmp2);
10878     movl(tmp3, in_out2);
10879     addl(tmp3, size);
10880 
10881     bind(L_processPartition);
10882       crc32(in_out3, Address(in_out2, 0), 4);
10883       crc32(tmp1, Address(in_out2, size), 4);
10884       crc32(tmp2, Address(in_out2, size*2), 4);
10885       crc32(in_out3, Address(in_out2, 0+4), 4);
10886       crc32(tmp1, Address(in_out2, size+4), 4);
10887       crc32(tmp2, Address(in_out2, size*2+4), 4);
10888       addl(in_out2, 8);
10889       cmpl(in_out2, tmp3);
10890       jcc(Assembler::less, L_processPartition);
10891 
10892         push(tmp3);
10893         push(in_out1);
10894         push(in_out2);
10895         tmp4 = tmp3;
10896         tmp5 = in_out1;
10897         n_tmp6 = in_out2;
10898 
10899       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10900             w_xtmp1, w_xtmp2, w_xtmp3,
10901             tmp4, tmp5,
10902             n_tmp6);
10903 
10904         pop(in_out2);
10905         pop(in_out1);
10906         pop(tmp3);
10907 
10908     addl(in_out2, 2 * size);
10909     subl(in_out1, 3 * size);
10910     jmp(L_processPartitions);
10911 
10912   bind(L_exit);
10913 }
10914 #endif //LP64
10915 
10916 #ifdef _LP64
10917 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10918 // Input: A buffer I of L bytes.
10919 // Output: the CRC32C value of the buffer.
10920 // Notations:
10921 // Write L = 24N + r, with N = floor (L/24).
10922 // r = L mod 24 (0 <= r < 24).
10923 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10924 // N quadwords, and R consists of r bytes.
10925 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10926 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10927 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10928 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10929 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10930                                           Register tmp1, Register tmp2, Register tmp3,
10931                                           Register tmp4, Register tmp5, Register tmp6,
10932                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10933                                           bool is_pclmulqdq_supported) {
10934   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10935   Label L_wordByWord;
10936   Label L_byteByByteProlog;
10937   Label L_byteByByte;
10938   Label L_exit;
10939 
10940   if (is_pclmulqdq_supported ) {
10941     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10942     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10943 
10944     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10945     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10946 
10947     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10948     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10949     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10950   } else {
10951     const_or_pre_comp_const_index[0] = 1;
10952     const_or_pre_comp_const_index[1] = 0;
10953 
10954     const_or_pre_comp_const_index[2] = 3;
10955     const_or_pre_comp_const_index[3] = 2;
10956 
10957     const_or_pre_comp_const_index[4] = 5;
10958     const_or_pre_comp_const_index[5] = 4;
10959    }
10960   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10961                     in2, in1, in_out,
10962                     tmp1, tmp2, tmp3,
10963                     w_xtmp1, w_xtmp2, w_xtmp3,
10964                     tmp4, tmp5,
10965                     tmp6);
10966   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10967                     in2, in1, in_out,
10968                     tmp1, tmp2, tmp3,
10969                     w_xtmp1, w_xtmp2, w_xtmp3,
10970                     tmp4, tmp5,
10971                     tmp6);
10972   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10973                     in2, in1, in_out,
10974                     tmp1, tmp2, tmp3,
10975                     w_xtmp1, w_xtmp2, w_xtmp3,
10976                     tmp4, tmp5,
10977                     tmp6);
10978   movl(tmp1, in2);
10979   andl(tmp1, 0x00000007);
10980   negl(tmp1);
10981   addl(tmp1, in2);
10982   addq(tmp1, in1);
10983 
10984   BIND(L_wordByWord);
10985   cmpq(in1, tmp1);
10986   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10987     crc32(in_out, Address(in1, 0), 4);
10988     addq(in1, 4);
10989     jmp(L_wordByWord);
10990 
10991   BIND(L_byteByByteProlog);
10992   andl(in2, 0x00000007);
10993   movl(tmp2, 1);
10994 
10995   BIND(L_byteByByte);
10996   cmpl(tmp2, in2);
10997   jccb(Assembler::greater, L_exit);
10998     crc32(in_out, Address(in1, 0), 1);
10999     incq(in1);
11000     incl(tmp2);
11001     jmp(L_byteByByte);
11002 
11003   BIND(L_exit);
11004 }
11005 #else
11006 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11007                                           Register tmp1, Register  tmp2, Register tmp3,
11008                                           Register tmp4, Register  tmp5, Register tmp6,
11009                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11010                                           bool is_pclmulqdq_supported) {
11011   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11012   Label L_wordByWord;
11013   Label L_byteByByteProlog;
11014   Label L_byteByByte;
11015   Label L_exit;
11016 
11017   if (is_pclmulqdq_supported) {
11018     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11019     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
11020 
11021     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11022     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11023 
11024     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11025     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11026   } else {
11027     const_or_pre_comp_const_index[0] = 1;
11028     const_or_pre_comp_const_index[1] = 0;
11029 
11030     const_or_pre_comp_const_index[2] = 3;
11031     const_or_pre_comp_const_index[3] = 2;
11032 
11033     const_or_pre_comp_const_index[4] = 5;
11034     const_or_pre_comp_const_index[5] = 4;
11035   }
11036   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11037                     in2, in1, in_out,
11038                     tmp1, tmp2, tmp3,
11039                     w_xtmp1, w_xtmp2, w_xtmp3,
11040                     tmp4, tmp5,
11041                     tmp6);
11042   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11043                     in2, in1, in_out,
11044                     tmp1, tmp2, tmp3,
11045                     w_xtmp1, w_xtmp2, w_xtmp3,
11046                     tmp4, tmp5,
11047                     tmp6);
11048   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11049                     in2, in1, in_out,
11050                     tmp1, tmp2, tmp3,
11051                     w_xtmp1, w_xtmp2, w_xtmp3,
11052                     tmp4, tmp5,
11053                     tmp6);
11054   movl(tmp1, in2);
11055   andl(tmp1, 0x00000007);
11056   negl(tmp1);
11057   addl(tmp1, in2);
11058   addl(tmp1, in1);
11059 
11060   BIND(L_wordByWord);
11061   cmpl(in1, tmp1);
11062   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11063     crc32(in_out, Address(in1,0), 4);
11064     addl(in1, 4);
11065     jmp(L_wordByWord);
11066 
11067   BIND(L_byteByByteProlog);
11068   andl(in2, 0x00000007);
11069   movl(tmp2, 1);
11070 
11071   BIND(L_byteByByte);
11072   cmpl(tmp2, in2);
11073   jccb(Assembler::greater, L_exit);
11074     movb(tmp1, Address(in1, 0));
11075     crc32(in_out, tmp1, 1);
11076     incl(in1);
11077     incl(tmp2);
11078     jmp(L_byteByByte);
11079 
11080   BIND(L_exit);
11081 }
11082 #endif // LP64
11083 #undef BIND
11084 #undef BLOCK_COMMENT
11085 
11086 // Compress char[] array to byte[].
11087 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
11088 //   @HotSpotIntrinsicCandidate
11089 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
11090 //     for (int i = 0; i < len; i++) {
11091 //       int c = src[srcOff++];
11092 //       if (c >>> 8 != 0) {
11093 //         return 0;
11094 //       }
11095 //       dst[dstOff++] = (byte)c;
11096 //     }
11097 //     return len;
11098 //   }
11099 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
11100   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
11101   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
11102   Register tmp5, Register result) {
11103   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
11104 
11105   // rsi: src
11106   // rdi: dst
11107   // rdx: len
11108   // rcx: tmp5
11109   // rax: result
11110 
11111   // rsi holds start addr of source char[] to be compressed
11112   // rdi holds start addr of destination byte[]
11113   // rdx holds length
11114 
11115   assert(len != result, "");
11116 
11117   // save length for return
11118   push(len);
11119 
11120   if ((UseAVX > 2) && // AVX512
11121     VM_Version::supports_avx512vlbw() &&
11122     VM_Version::supports_bmi2()) {
11123 
11124     set_vector_masking();  // opening of the stub context for programming mask registers
11125 
11126     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
11127 
11128     // alignement
11129     Label post_alignement;
11130 
11131     // if length of the string is less than 16, handle it in an old fashioned
11132     // way
11133     testl(len, -32);
11134     jcc(Assembler::zero, below_threshold);
11135 
11136     // First check whether a character is compressable ( <= 0xFF).
11137     // Create mask to test for Unicode chars inside zmm vector
11138     movl(result, 0x00FF);
11139     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
11140 
11141     // Save k1
11142     kmovql(k3, k1);
11143 
11144     testl(len, -64);
11145     jcc(Assembler::zero, post_alignement);
11146 
11147     movl(tmp5, dst);
11148     andl(tmp5, (32 - 1));
11149     negl(tmp5);
11150     andl(tmp5, (32 - 1));
11151 
11152     // bail out when there is nothing to be done
11153     testl(tmp5, 0xFFFFFFFF);
11154     jcc(Assembler::zero, post_alignement);
11155 
11156     // ~(~0 << len), where len is the # of remaining elements to process
11157     movl(result, 0xFFFFFFFF);
11158     shlxl(result, result, tmp5);
11159     notl(result);
11160     kmovdl(k1, result);
11161 
11162     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11163     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11164     ktestd(k2, k1);
11165     jcc(Assembler::carryClear, restore_k1_return_zero);
11166 
11167     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11168 
11169     addptr(src, tmp5);
11170     addptr(src, tmp5);
11171     addptr(dst, tmp5);
11172     subl(len, tmp5);
11173 
11174     bind(post_alignement);
11175     // end of alignement
11176 
11177     movl(tmp5, len);
11178     andl(tmp5, (32 - 1));    // tail count (in chars)
11179     andl(len, ~(32 - 1));    // vector count (in chars)
11180     jcc(Assembler::zero, copy_loop_tail);
11181 
11182     lea(src, Address(src, len, Address::times_2));
11183     lea(dst, Address(dst, len, Address::times_1));
11184     negptr(len);
11185 
11186     bind(copy_32_loop);
11187     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11188     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11189     kortestdl(k2, k2);
11190     jcc(Assembler::carryClear, restore_k1_return_zero);
11191 
11192     // All elements in current processed chunk are valid candidates for
11193     // compression. Write a truncated byte elements to the memory.
11194     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11195     addptr(len, 32);
11196     jcc(Assembler::notZero, copy_32_loop);
11197 
11198     bind(copy_loop_tail);
11199     // bail out when there is nothing to be done
11200     testl(tmp5, 0xFFFFFFFF);
11201     // Restore k1
11202     kmovql(k1, k3);
11203     jcc(Assembler::zero, return_length);
11204 
11205     movl(len, tmp5);
11206 
11207     // ~(~0 << len), where len is the # of remaining elements to process
11208     movl(result, 0xFFFFFFFF);
11209     shlxl(result, result, len);
11210     notl(result);
11211 
11212     kmovdl(k1, result);
11213 
11214     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11215     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11216     ktestd(k2, k1);
11217     jcc(Assembler::carryClear, restore_k1_return_zero);
11218 
11219     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11220     // Restore k1
11221     kmovql(k1, k3);
11222     jmp(return_length);
11223 
11224     bind(restore_k1_return_zero);
11225     // Restore k1
11226     kmovql(k1, k3);
11227     jmp(return_zero);
11228 
11229     clear_vector_masking();   // closing of the stub context for programming mask registers
11230   }
11231   if (UseSSE42Intrinsics) {
11232     Label copy_32_loop, copy_16, copy_tail;
11233 
11234     bind(below_threshold);
11235 
11236     movl(result, len);
11237 
11238     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11239 
11240     // vectored compression
11241     andl(len, 0xfffffff0);    // vector count (in chars)
11242     andl(result, 0x0000000f);    // tail count (in chars)
11243     testl(len, len);
11244     jccb(Assembler::zero, copy_16);
11245 
11246     // compress 16 chars per iter
11247     movdl(tmp1Reg, tmp5);
11248     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11249     pxor(tmp4Reg, tmp4Reg);
11250 
11251     lea(src, Address(src, len, Address::times_2));
11252     lea(dst, Address(dst, len, Address::times_1));
11253     negptr(len);
11254 
11255     bind(copy_32_loop);
11256     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11257     por(tmp4Reg, tmp2Reg);
11258     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11259     por(tmp4Reg, tmp3Reg);
11260     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11261     jcc(Assembler::notZero, return_zero);
11262     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11263     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11264     addptr(len, 16);
11265     jcc(Assembler::notZero, copy_32_loop);
11266 
11267     // compress next vector of 8 chars (if any)
11268     bind(copy_16);
11269     movl(len, result);
11270     andl(len, 0xfffffff8);    // vector count (in chars)
11271     andl(result, 0x00000007);    // tail count (in chars)
11272     testl(len, len);
11273     jccb(Assembler::zero, copy_tail);
11274 
11275     movdl(tmp1Reg, tmp5);
11276     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11277     pxor(tmp3Reg, tmp3Reg);
11278 
11279     movdqu(tmp2Reg, Address(src, 0));
11280     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11281     jccb(Assembler::notZero, return_zero);
11282     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11283     movq(Address(dst, 0), tmp2Reg);
11284     addptr(src, 16);
11285     addptr(dst, 8);
11286 
11287     bind(copy_tail);
11288     movl(len, result);
11289   }
11290   // compress 1 char per iter
11291   testl(len, len);
11292   jccb(Assembler::zero, return_length);
11293   lea(src, Address(src, len, Address::times_2));
11294   lea(dst, Address(dst, len, Address::times_1));
11295   negptr(len);
11296 
11297   bind(copy_chars_loop);
11298   load_unsigned_short(result, Address(src, len, Address::times_2));
11299   testl(result, 0xff00);      // check if Unicode char
11300   jccb(Assembler::notZero, return_zero);
11301   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11302   increment(len);
11303   jcc(Assembler::notZero, copy_chars_loop);
11304 
11305   // if compression succeeded, return length
11306   bind(return_length);
11307   pop(result);
11308   jmpb(done);
11309 
11310   // if compression failed, return 0
11311   bind(return_zero);
11312   xorl(result, result);
11313   addptr(rsp, wordSize);
11314 
11315   bind(done);
11316 }
11317 
11318 // Inflate byte[] array to char[].
11319 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11320 //   @HotSpotIntrinsicCandidate
11321 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11322 //     for (int i = 0; i < len; i++) {
11323 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11324 //     }
11325 //   }
11326 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11327   XMMRegister tmp1, Register tmp2) {
11328   Label copy_chars_loop, done, below_threshold;
11329   // rsi: src
11330   // rdi: dst
11331   // rdx: len
11332   // rcx: tmp2
11333 
11334   // rsi holds start addr of source byte[] to be inflated
11335   // rdi holds start addr of destination char[]
11336   // rdx holds length
11337   assert_different_registers(src, dst, len, tmp2);
11338 
11339   if ((UseAVX > 2) && // AVX512
11340     VM_Version::supports_avx512vlbw() &&
11341     VM_Version::supports_bmi2()) {
11342 
11343     set_vector_masking();  // opening of the stub context for programming mask registers
11344 
11345     Label copy_32_loop, copy_tail;
11346     Register tmp3_aliased = len;
11347 
11348     // if length of the string is less than 16, handle it in an old fashioned
11349     // way
11350     testl(len, -16);
11351     jcc(Assembler::zero, below_threshold);
11352 
11353     // In order to use only one arithmetic operation for the main loop we use
11354     // this pre-calculation
11355     movl(tmp2, len);
11356     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11357     andl(len, -32);     // vector count
11358     jccb(Assembler::zero, copy_tail);
11359 
11360     lea(src, Address(src, len, Address::times_1));
11361     lea(dst, Address(dst, len, Address::times_2));
11362     negptr(len);
11363 
11364 
11365     // inflate 32 chars per iter
11366     bind(copy_32_loop);
11367     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11368     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11369     addptr(len, 32);
11370     jcc(Assembler::notZero, copy_32_loop);
11371 
11372     bind(copy_tail);
11373     // bail out when there is nothing to be done
11374     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11375     jcc(Assembler::zero, done);
11376 
11377     // Save k1
11378     kmovql(k2, k1);
11379 
11380     // ~(~0 << length), where length is the # of remaining elements to process
11381     movl(tmp3_aliased, -1);
11382     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11383     notl(tmp3_aliased);
11384     kmovdl(k1, tmp3_aliased);
11385     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11386     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11387 
11388     // Restore k1
11389     kmovql(k1, k2);
11390     jmp(done);
11391 
11392     clear_vector_masking();   // closing of the stub context for programming mask registers
11393   }
11394   if (UseSSE42Intrinsics) {
11395     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11396 
11397     movl(tmp2, len);
11398 
11399     if (UseAVX > 1) {
11400       andl(tmp2, (16 - 1));
11401       andl(len, -16);
11402       jccb(Assembler::zero, copy_new_tail);
11403     } else {
11404       andl(tmp2, 0x00000007);   // tail count (in chars)
11405       andl(len, 0xfffffff8);    // vector count (in chars)
11406       jccb(Assembler::zero, copy_tail);
11407     }
11408 
11409     // vectored inflation
11410     lea(src, Address(src, len, Address::times_1));
11411     lea(dst, Address(dst, len, Address::times_2));
11412     negptr(len);
11413 
11414     if (UseAVX > 1) {
11415       bind(copy_16_loop);
11416       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11417       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11418       addptr(len, 16);
11419       jcc(Assembler::notZero, copy_16_loop);
11420 
11421       bind(below_threshold);
11422       bind(copy_new_tail);
11423       if ((UseAVX > 2) &&
11424         VM_Version::supports_avx512vlbw() &&
11425         VM_Version::supports_bmi2()) {
11426         movl(tmp2, len);
11427       } else {
11428         movl(len, tmp2);
11429       }
11430       andl(tmp2, 0x00000007);
11431       andl(len, 0xFFFFFFF8);
11432       jccb(Assembler::zero, copy_tail);
11433 
11434       pmovzxbw(tmp1, Address(src, 0));
11435       movdqu(Address(dst, 0), tmp1);
11436       addptr(src, 8);
11437       addptr(dst, 2 * 8);
11438 
11439       jmp(copy_tail, true);
11440     }
11441 
11442     // inflate 8 chars per iter
11443     bind(copy_8_loop);
11444     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11445     movdqu(Address(dst, len, Address::times_2), tmp1);
11446     addptr(len, 8);
11447     jcc(Assembler::notZero, copy_8_loop);
11448 
11449     bind(copy_tail);
11450     movl(len, tmp2);
11451 
11452     cmpl(len, 4);
11453     jccb(Assembler::less, copy_bytes);
11454 
11455     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11456     pmovzxbw(tmp1, tmp1);
11457     movq(Address(dst, 0), tmp1);
11458     subptr(len, 4);
11459     addptr(src, 4);
11460     addptr(dst, 8);
11461 
11462     bind(copy_bytes);
11463   }
11464   testl(len, len);
11465   jccb(Assembler::zero, done);
11466   lea(src, Address(src, len, Address::times_1));
11467   lea(dst, Address(dst, len, Address::times_2));
11468   negptr(len);
11469 
11470   // inflate 1 char per iter
11471   bind(copy_chars_loop);
11472   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11473   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11474   increment(len);
11475   jcc(Assembler::notZero, copy_chars_loop);
11476 
11477   bind(done);
11478 }
11479 
11480 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11481   switch (cond) {
11482     // Note some conditions are synonyms for others
11483     case Assembler::zero:         return Assembler::notZero;
11484     case Assembler::notZero:      return Assembler::zero;
11485     case Assembler::less:         return Assembler::greaterEqual;
11486     case Assembler::lessEqual:    return Assembler::greater;
11487     case Assembler::greater:      return Assembler::lessEqual;
11488     case Assembler::greaterEqual: return Assembler::less;
11489     case Assembler::below:        return Assembler::aboveEqual;
11490     case Assembler::belowEqual:   return Assembler::above;
11491     case Assembler::above:        return Assembler::belowEqual;
11492     case Assembler::aboveEqual:   return Assembler::below;
11493     case Assembler::overflow:     return Assembler::noOverflow;
11494     case Assembler::noOverflow:   return Assembler::overflow;
11495     case Assembler::negative:     return Assembler::positive;
11496     case Assembler::positive:     return Assembler::negative;
11497     case Assembler::parity:       return Assembler::noParity;
11498     case Assembler::noParity:     return Assembler::parity;
11499   }
11500   ShouldNotReachHere(); return Assembler::overflow;
11501 }
11502 
11503 SkipIfEqual::SkipIfEqual(
11504     MacroAssembler* masm, const bool* flag_addr, bool value) {
11505   _masm = masm;
11506   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11507   _masm->jcc(Assembler::equal, _label);
11508 }
11509 
11510 SkipIfEqual::~SkipIfEqual() {
11511   _masm->bind(_label);
11512 }
11513 
11514 // 32-bit Windows has its own fast-path implementation
11515 // of get_thread
11516 #if !defined(WIN32) || defined(_LP64)
11517 
11518 // This is simply a call to Thread::current()
11519 void MacroAssembler::get_thread(Register thread) {
11520   if (thread != rax) {
11521     push(rax);
11522   }
11523   LP64_ONLY(push(rdi);)
11524   LP64_ONLY(push(rsi);)
11525   push(rdx);
11526   push(rcx);
11527 #ifdef _LP64
11528   push(r8);
11529   push(r9);
11530   push(r10);
11531   push(r11);
11532 #endif
11533 
11534   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11535 
11536 #ifdef _LP64
11537   pop(r11);
11538   pop(r10);
11539   pop(r9);
11540   pop(r8);
11541 #endif
11542   pop(rcx);
11543   pop(rdx);
11544   LP64_ONLY(pop(rsi);)
11545   LP64_ONLY(pop(rdi);)
11546   if (thread != rax) {
11547     mov(thread, rax);
11548     pop(rax);
11549   }
11550 }
11551 
11552 #endif
11553 
11554 void MacroAssembler::save_vector_registers() {
11555   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11556   if (UseAVX > 2) {
11557     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11558   }
11559 
11560   if (UseSSE == 1)  {
11561     subptr(rsp, sizeof(jdouble)*8);
11562     for (int n = 0; n < 8; n++) {
11563       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11564     }
11565   } else if (UseSSE >= 2)  {
11566     if (UseAVX > 2) {
11567       push(rbx);
11568       movl(rbx, 0xffff);
11569       kmovwl(k1, rbx);
11570       pop(rbx);
11571     }
11572 #ifdef COMPILER2
11573     if (MaxVectorSize > 16) {
11574       if(UseAVX > 2) {
11575         // Save upper half of ZMM registers
11576         subptr(rsp, 32*num_xmm_regs);
11577         for (int n = 0; n < num_xmm_regs; n++) {
11578           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11579         }
11580       }
11581       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11582       // Save upper half of YMM registers
11583       subptr(rsp, 16*num_xmm_regs);
11584       for (int n = 0; n < num_xmm_regs; n++) {
11585         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11586       }
11587     }
11588 #endif
11589     // Save whole 128bit (16 bytes) XMM registers
11590     subptr(rsp, 16*num_xmm_regs);
11591 #ifdef _LP64
11592     if (VM_Version::supports_evex()) {
11593       for (int n = 0; n < num_xmm_regs; n++) {
11594         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11595       }
11596     } else {
11597       for (int n = 0; n < num_xmm_regs; n++) {
11598         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11599       }
11600     }
11601 #else
11602     for (int n = 0; n < num_xmm_regs; n++) {
11603       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11604     }
11605 #endif
11606   }
11607 }
11608 
11609 void MacroAssembler::restore_vector_registers() {
11610   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11611   if (UseAVX > 2) {
11612     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11613   }
11614   if (UseSSE == 1)  {
11615     for (int n = 0; n < 8; n++) {
11616       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11617     }
11618     addptr(rsp, sizeof(jdouble)*8);
11619   } else if (UseSSE >= 2)  {
11620     // Restore whole 128bit (16 bytes) XMM registers
11621 #ifdef _LP64
11622   if (VM_Version::supports_evex()) {
11623     for (int n = 0; n < num_xmm_regs; n++) {
11624       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11625     }
11626   } else {
11627     for (int n = 0; n < num_xmm_regs; n++) {
11628       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11629     }
11630   }
11631 #else
11632   for (int n = 0; n < num_xmm_regs; n++) {
11633     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11634   }
11635 #endif
11636     addptr(rsp, 16*num_xmm_regs);
11637 
11638 #ifdef COMPILER2
11639     if (MaxVectorSize > 16) {
11640       // Restore upper half of YMM registers.
11641       for (int n = 0; n < num_xmm_regs; n++) {
11642         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11643       }
11644       addptr(rsp, 16*num_xmm_regs);
11645       if(UseAVX > 2) {
11646         for (int n = 0; n < num_xmm_regs; n++) {
11647           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11648         }
11649         addptr(rsp, 32*num_xmm_regs);
11650       }
11651     }
11652 #endif
11653   }
11654 }