1 /*
   2  * Copyright (c) 1997, 2017, 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/barrierSet.hpp"
  30 #include "gc/shared/cardTableModRefBS.hpp"
  31 #include "gc/shared/collectedHeap.inline.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/klass.inline.hpp"
  36 #include "oops/oop.hpp"
  37 #include "prims/jvm.h"
  38 #include "prims/methodHandles.hpp"
  39 #include "runtime/biasedLocking.hpp"
  40 #include "runtime/interfaceSupport.hpp"
  41 #include "runtime/objectMonitor.hpp"
  42 #include "runtime/os.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "runtime/stubRoutines.hpp"
  45 #include "runtime/thread.hpp"
  46 #include "utilities/macros.hpp"
  47 #if INCLUDE_ALL_GCS
  48 #include "gc/g1/g1CollectedHeap.inline.hpp"
  49 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  50 #include "gc/g1/heapRegion.hpp"
  51 #include "gc/shenandoah/shenandoahConnectionMatrix.inline.hpp"
  52 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  53 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  54 #endif // INCLUDE_ALL_GCS
  55 #include "crc32c.h"
  56 #ifdef COMPILER2
  57 #include "opto/intrinsicnode.hpp"
  58 #endif
  59 
  60 #ifdef PRODUCT
  61 #define BLOCK_COMMENT(str) /* nothing */
  62 #define STOP(error) stop(error)
  63 #else
  64 #define BLOCK_COMMENT(str) block_comment(str)
  65 #define STOP(error) block_comment(error); stop(error)
  66 #endif
  67 
  68 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  69 
  70 #ifdef ASSERT
  71 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  72 #endif
  73 
  74 static Assembler::Condition reverse[] = {
  75     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  76     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  77     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  78     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  79     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  80     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  81     Assembler::above          /* belowEqual    = 0x6 */ ,
  82     Assembler::belowEqual     /* above         = 0x7 */ ,
  83     Assembler::positive       /* negative      = 0x8 */ ,
  84     Assembler::negative       /* positive      = 0x9 */ ,
  85     Assembler::noParity       /* parity        = 0xa */ ,
  86     Assembler::parity         /* noParity      = 0xb */ ,
  87     Assembler::greaterEqual   /* less          = 0xc */ ,
  88     Assembler::less           /* greaterEqual  = 0xd */ ,
  89     Assembler::greater        /* lessEqual     = 0xe */ ,
  90     Assembler::lessEqual      /* greater       = 0xf, */
  91 
  92 };
  93 
  94 
  95 // Implementation of MacroAssembler
  96 
  97 // First all the versions that have distinct versions depending on 32/64 bit
  98 // Unless the difference is trivial (1 line or so).
  99 
 100 #ifndef _LP64
 101 
 102 // 32bit versions
 103 
 104 Address MacroAssembler::as_Address(AddressLiteral adr) {
 105   return Address(adr.target(), adr.rspec());
 106 }
 107 
 108 Address MacroAssembler::as_Address(ArrayAddress adr) {
 109   return Address::make_array(adr);
 110 }
 111 
 112 void MacroAssembler::call_VM_leaf_base(address entry_point,
 113                                        int number_of_arguments) {
 114   call(RuntimeAddress(entry_point));
 115   increment(rsp, number_of_arguments * wordSize);
 116 }
 117 
 118 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 119   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 120 }
 121 
 122 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 123   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 124 }
 125 
 126 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 127   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 128 }
 129 
 130 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 131   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 132 }
 133 
 134 void MacroAssembler::extend_sign(Register hi, Register lo) {
 135   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 136   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 137     cdql();
 138   } else {
 139     movl(hi, lo);
 140     sarl(hi, 31);
 141   }
 142 }
 143 
 144 void MacroAssembler::jC2(Register tmp, Label& L) {
 145   // set parity bit if FPU flag C2 is set (via rax)
 146   save_rax(tmp);
 147   fwait(); fnstsw_ax();
 148   sahf();
 149   restore_rax(tmp);
 150   // branch
 151   jcc(Assembler::parity, L);
 152 }
 153 
 154 void MacroAssembler::jnC2(Register tmp, Label& L) {
 155   // set parity bit if FPU flag C2 is set (via rax)
 156   save_rax(tmp);
 157   fwait(); fnstsw_ax();
 158   sahf();
 159   restore_rax(tmp);
 160   // branch
 161   jcc(Assembler::noParity, L);
 162 }
 163 
 164 // 32bit can do a case table jump in one instruction but we no longer allow the base
 165 // to be installed in the Address class
 166 void MacroAssembler::jump(ArrayAddress entry) {
 167   jmp(as_Address(entry));
 168 }
 169 
 170 // Note: y_lo will be destroyed
 171 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 172   // Long compare for Java (semantics as described in JVM spec.)
 173   Label high, low, done;
 174 
 175   cmpl(x_hi, y_hi);
 176   jcc(Assembler::less, low);
 177   jcc(Assembler::greater, high);
 178   // x_hi is the return register
 179   xorl(x_hi, x_hi);
 180   cmpl(x_lo, y_lo);
 181   jcc(Assembler::below, low);
 182   jcc(Assembler::equal, done);
 183 
 184   bind(high);
 185   xorl(x_hi, x_hi);
 186   increment(x_hi);
 187   jmp(done);
 188 
 189   bind(low);
 190   xorl(x_hi, x_hi);
 191   decrementl(x_hi);
 192 
 193   bind(done);
 194 }
 195 
 196 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 197     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 198 }
 199 
 200 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 201   // leal(dst, as_Address(adr));
 202   // see note in movl as to why we must use a move
 203   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 204 }
 205 
 206 void MacroAssembler::leave() {
 207   mov(rsp, rbp);
 208   pop(rbp);
 209 }
 210 
 211 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 212   // Multiplication of two Java long values stored on the stack
 213   // as illustrated below. Result is in rdx:rax.
 214   //
 215   // rsp ---> [  ??  ] \               \
 216   //            ....    | y_rsp_offset  |
 217   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 218   //          [ y_hi ]                  | (in bytes)
 219   //            ....                    |
 220   //          [ x_lo ]                 /
 221   //          [ x_hi ]
 222   //            ....
 223   //
 224   // Basic idea: lo(result) = lo(x_lo * y_lo)
 225   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 226   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 227   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 228   Label quick;
 229   // load x_hi, y_hi and check if quick
 230   // multiplication is possible
 231   movl(rbx, x_hi);
 232   movl(rcx, y_hi);
 233   movl(rax, rbx);
 234   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 235   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 236   // do full multiplication
 237   // 1st step
 238   mull(y_lo);                                    // x_hi * y_lo
 239   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 240   // 2nd step
 241   movl(rax, x_lo);
 242   mull(rcx);                                     // x_lo * y_hi
 243   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 244   // 3rd step
 245   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 246   movl(rax, x_lo);
 247   mull(y_lo);                                    // x_lo * y_lo
 248   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 249 }
 250 
 251 void MacroAssembler::lneg(Register hi, Register lo) {
 252   negl(lo);
 253   adcl(hi, 0);
 254   negl(hi);
 255 }
 256 
 257 void MacroAssembler::lshl(Register hi, Register lo) {
 258   // Java shift left long support (semantics as described in JVM spec., p.305)
 259   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 260   // shift value is in rcx !
 261   assert(hi != rcx, "must not use rcx");
 262   assert(lo != rcx, "must not use rcx");
 263   const Register s = rcx;                        // shift count
 264   const int      n = BitsPerWord;
 265   Label L;
 266   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 267   cmpl(s, n);                                    // if (s < n)
 268   jcc(Assembler::less, L);                       // else (s >= n)
 269   movl(hi, lo);                                  // x := x << n
 270   xorl(lo, lo);
 271   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 272   bind(L);                                       // s (mod n) < n
 273   shldl(hi, lo);                                 // x := x << s
 274   shll(lo);
 275 }
 276 
 277 
 278 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 279   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 280   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 281   assert(hi != rcx, "must not use rcx");
 282   assert(lo != rcx, "must not use rcx");
 283   const Register s = rcx;                        // shift count
 284   const int      n = BitsPerWord;
 285   Label L;
 286   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 287   cmpl(s, n);                                    // if (s < n)
 288   jcc(Assembler::less, L);                       // else (s >= n)
 289   movl(lo, hi);                                  // x := x >> n
 290   if (sign_extension) sarl(hi, 31);
 291   else                xorl(hi, hi);
 292   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 293   bind(L);                                       // s (mod n) < n
 294   shrdl(lo, hi);                                 // x := x >> s
 295   if (sign_extension) sarl(hi);
 296   else                shrl(hi);
 297 }
 298 
 299 void MacroAssembler::movoop(Register dst, jobject obj) {
 300   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 301 }
 302 
 303 void MacroAssembler::movoop(Address dst, jobject obj) {
 304   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 305 }
 306 
 307 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 308   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 309 }
 310 
 311 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 312   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 313 }
 314 
 315 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 316   // scratch register is not used,
 317   // it is defined to match parameters of 64-bit version of this method.
 318   if (src.is_lval()) {
 319     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 320   } else {
 321     movl(dst, as_Address(src));
 322   }
 323 }
 324 
 325 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 326   movl(as_Address(dst), src);
 327 }
 328 
 329 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 330   movl(dst, as_Address(src));
 331 }
 332 
 333 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 334 void MacroAssembler::movptr(Address dst, intptr_t src) {
 335   movl(dst, src);
 336 }
 337 
 338 
 339 void MacroAssembler::pop_callee_saved_registers() {
 340   pop(rcx);
 341   pop(rdx);
 342   pop(rdi);
 343   pop(rsi);
 344 }
 345 
 346 void MacroAssembler::pop_fTOS() {
 347   fld_d(Address(rsp, 0));
 348   addl(rsp, 2 * wordSize);
 349 }
 350 
 351 void MacroAssembler::push_callee_saved_registers() {
 352   push(rsi);
 353   push(rdi);
 354   push(rdx);
 355   push(rcx);
 356 }
 357 
 358 void MacroAssembler::push_fTOS() {
 359   subl(rsp, 2 * wordSize);
 360   fstp_d(Address(rsp, 0));
 361 }
 362 
 363 
 364 void MacroAssembler::pushoop(jobject obj) {
 365   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 366 }
 367 
 368 void MacroAssembler::pushklass(Metadata* obj) {
 369   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 370 }
 371 
 372 void MacroAssembler::pushptr(AddressLiteral src) {
 373   if (src.is_lval()) {
 374     push_literal32((int32_t)src.target(), src.rspec());
 375   } else {
 376     pushl(as_Address(src));
 377   }
 378 }
 379 
 380 void MacroAssembler::set_word_if_not_zero(Register dst) {
 381   xorl(dst, dst);
 382   set_byte_if_not_zero(dst);
 383 }
 384 
 385 static void pass_arg0(MacroAssembler* masm, Register arg) {
 386   masm->push(arg);
 387 }
 388 
 389 static void pass_arg1(MacroAssembler* masm, Register arg) {
 390   masm->push(arg);
 391 }
 392 
 393 static void pass_arg2(MacroAssembler* masm, Register arg) {
 394   masm->push(arg);
 395 }
 396 
 397 static void pass_arg3(MacroAssembler* masm, Register arg) {
 398   masm->push(arg);
 399 }
 400 
 401 #ifndef PRODUCT
 402 extern "C" void findpc(intptr_t x);
 403 #endif
 404 
 405 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 406   // In order to get locks to work, we need to fake a in_VM state
 407   JavaThread* thread = JavaThread::current();
 408   JavaThreadState saved_state = thread->thread_state();
 409   thread->set_thread_state(_thread_in_vm);
 410   if (ShowMessageBoxOnError) {
 411     JavaThread* thread = JavaThread::current();
 412     JavaThreadState saved_state = thread->thread_state();
 413     thread->set_thread_state(_thread_in_vm);
 414     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 415       ttyLocker ttyl;
 416       BytecodeCounter::print();
 417     }
 418     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 419     // This is the value of eip which points to where verify_oop will return.
 420     if (os::message_box(msg, "Execution stopped, print registers?")) {
 421       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 422       BREAKPOINT;
 423     }
 424   } else {
 425     ttyLocker ttyl;
 426     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 427   }
 428   // Don't assert holding the ttyLock
 429     assert(false, "DEBUG MESSAGE: %s", msg);
 430   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 431 }
 432 
 433 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 434   ttyLocker ttyl;
 435   FlagSetting fs(Debugging, true);
 436   tty->print_cr("eip = 0x%08x", eip);
 437 #ifndef PRODUCT
 438   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 439     tty->cr();
 440     findpc(eip);
 441     tty->cr();
 442   }
 443 #endif
 444 #define PRINT_REG(rax) \
 445   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 446   PRINT_REG(rax);
 447   PRINT_REG(rbx);
 448   PRINT_REG(rcx);
 449   PRINT_REG(rdx);
 450   PRINT_REG(rdi);
 451   PRINT_REG(rsi);
 452   PRINT_REG(rbp);
 453   PRINT_REG(rsp);
 454 #undef PRINT_REG
 455   // Print some words near top of staack.
 456   int* dump_sp = (int*) rsp;
 457   for (int col1 = 0; col1 < 8; col1++) {
 458     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 459     os::print_location(tty, *dump_sp++);
 460   }
 461   for (int row = 0; row < 16; row++) {
 462     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 463     for (int col = 0; col < 8; col++) {
 464       tty->print(" 0x%08x", *dump_sp++);
 465     }
 466     tty->cr();
 467   }
 468   // Print some instructions around pc:
 469   Disassembler::decode((address)eip-64, (address)eip);
 470   tty->print_cr("--------");
 471   Disassembler::decode((address)eip, (address)eip+32);
 472 }
 473 
 474 void MacroAssembler::stop(const char* msg) {
 475   ExternalAddress message((address)msg);
 476   // push address of message
 477   pushptr(message.addr());
 478   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 479   pusha();                                            // push registers
 480   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 481   hlt();
 482 }
 483 
 484 void MacroAssembler::warn(const char* msg) {
 485   push_CPU_state();
 486 
 487   ExternalAddress message((address) msg);
 488   // push address of message
 489   pushptr(message.addr());
 490 
 491   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 492   addl(rsp, wordSize);       // discard argument
 493   pop_CPU_state();
 494 }
 495 
 496 void MacroAssembler::print_state() {
 497   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 498   pusha();                                            // push registers
 499 
 500   push_CPU_state();
 501   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 502   pop_CPU_state();
 503 
 504   popa();
 505   addl(rsp, wordSize);
 506 }
 507 
 508 #else // _LP64
 509 
 510 // 64 bit versions
 511 
 512 Address MacroAssembler::as_Address(AddressLiteral adr) {
 513   // amd64 always does this as a pc-rel
 514   // we can be absolute or disp based on the instruction type
 515   // jmp/call are displacements others are absolute
 516   assert(!adr.is_lval(), "must be rval");
 517   assert(reachable(adr), "must be");
 518   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 519 
 520 }
 521 
 522 Address MacroAssembler::as_Address(ArrayAddress adr) {
 523   AddressLiteral base = adr.base();
 524   lea(rscratch1, base);
 525   Address index = adr.index();
 526   assert(index._disp == 0, "must not have disp"); // maybe it can?
 527   Address array(rscratch1, index._index, index._scale, index._disp);
 528   return array;
 529 }
 530 
 531 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 532   Label L, E;
 533 
 534 #ifdef _WIN64
 535   // Windows always allocates space for it's register args
 536   assert(num_args <= 4, "only register arguments supported");
 537   subq(rsp,  frame::arg_reg_save_area_bytes);
 538 #endif
 539 
 540   // Align stack if necessary
 541   testl(rsp, 15);
 542   jcc(Assembler::zero, L);
 543 
 544   subq(rsp, 8);
 545   {
 546     call(RuntimeAddress(entry_point));
 547   }
 548   addq(rsp, 8);
 549   jmp(E);
 550 
 551   bind(L);
 552   {
 553     call(RuntimeAddress(entry_point));
 554   }
 555 
 556   bind(E);
 557 
 558 #ifdef _WIN64
 559   // restore stack pointer
 560   addq(rsp, frame::arg_reg_save_area_bytes);
 561 #endif
 562 
 563 }
 564 
 565 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 566   assert(!src2.is_lval(), "should use cmpptr");
 567 
 568   if (reachable(src2)) {
 569     cmpq(src1, as_Address(src2));
 570   } else {
 571     lea(rscratch1, src2);
 572     Assembler::cmpq(src1, Address(rscratch1, 0));
 573   }
 574 }
 575 
 576 int MacroAssembler::corrected_idivq(Register reg) {
 577   // Full implementation of Java ldiv and lrem; checks for special
 578   // case as described in JVM spec., p.243 & p.271.  The function
 579   // returns the (pc) offset of the idivl instruction - may be needed
 580   // for implicit exceptions.
 581   //
 582   //         normal case                           special case
 583   //
 584   // input : rax: dividend                         min_long
 585   //         reg: divisor   (may not be eax/edx)   -1
 586   //
 587   // output: rax: quotient  (= rax idiv reg)       min_long
 588   //         rdx: remainder (= rax irem reg)       0
 589   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 590   static const int64_t min_long = 0x8000000000000000;
 591   Label normal_case, special_case;
 592 
 593   // check for special case
 594   cmp64(rax, ExternalAddress((address) &min_long));
 595   jcc(Assembler::notEqual, normal_case);
 596   xorl(rdx, rdx); // prepare rdx for possible special case (where
 597                   // remainder = 0)
 598   cmpq(reg, -1);
 599   jcc(Assembler::equal, special_case);
 600 
 601   // handle normal case
 602   bind(normal_case);
 603   cdqq();
 604   int idivq_offset = offset();
 605   idivq(reg);
 606 
 607   // normal and special case exit
 608   bind(special_case);
 609 
 610   return idivq_offset;
 611 }
 612 
 613 void MacroAssembler::decrementq(Register reg, int value) {
 614   if (value == min_jint) { subq(reg, value); return; }
 615   if (value <  0) { incrementq(reg, -value); return; }
 616   if (value == 0) {                        ; return; }
 617   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 618   /* else */      { subq(reg, value)       ; return; }
 619 }
 620 
 621 void MacroAssembler::decrementq(Address dst, int value) {
 622   if (value == min_jint) { subq(dst, value); return; }
 623   if (value <  0) { incrementq(dst, -value); return; }
 624   if (value == 0) {                        ; return; }
 625   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 626   /* else */      { subq(dst, value)       ; return; }
 627 }
 628 
 629 void MacroAssembler::incrementq(AddressLiteral dst) {
 630   if (reachable(dst)) {
 631     incrementq(as_Address(dst));
 632   } else {
 633     lea(rscratch1, dst);
 634     incrementq(Address(rscratch1, 0));
 635   }
 636 }
 637 
 638 void MacroAssembler::incrementq(Register reg, int value) {
 639   if (value == min_jint) { addq(reg, value); return; }
 640   if (value <  0) { decrementq(reg, -value); return; }
 641   if (value == 0) {                        ; return; }
 642   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 643   /* else */      { addq(reg, value)       ; return; }
 644 }
 645 
 646 void MacroAssembler::incrementq(Address dst, int value) {
 647   if (value == min_jint) { addq(dst, value); return; }
 648   if (value <  0) { decrementq(dst, -value); return; }
 649   if (value == 0) {                        ; return; }
 650   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 651   /* else */      { addq(dst, value)       ; return; }
 652 }
 653 
 654 // 32bit can do a case table jump in one instruction but we no longer allow the base
 655 // to be installed in the Address class
 656 void MacroAssembler::jump(ArrayAddress entry) {
 657   lea(rscratch1, entry.base());
 658   Address dispatch = entry.index();
 659   assert(dispatch._base == noreg, "must be");
 660   dispatch._base = rscratch1;
 661   jmp(dispatch);
 662 }
 663 
 664 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 665   ShouldNotReachHere(); // 64bit doesn't use two regs
 666   cmpq(x_lo, y_lo);
 667 }
 668 
 669 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 670     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 671 }
 672 
 673 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 674   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 675   movptr(dst, rscratch1);
 676 }
 677 
 678 void MacroAssembler::leave() {
 679   // %%% is this really better? Why not on 32bit too?
 680   emit_int8((unsigned char)0xC9); // LEAVE
 681 }
 682 
 683 void MacroAssembler::lneg(Register hi, Register lo) {
 684   ShouldNotReachHere(); // 64bit doesn't use two regs
 685   negq(lo);
 686 }
 687 
 688 void MacroAssembler::movoop(Register dst, jobject obj) {
 689   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 690 }
 691 
 692 void MacroAssembler::movoop(Address dst, jobject obj) {
 693   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 694   movq(dst, rscratch1);
 695 }
 696 
 697 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 698   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 699 }
 700 
 701 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 702   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 703   movq(dst, rscratch1);
 704 }
 705 
 706 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 707   if (src.is_lval()) {
 708     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 709   } else {
 710     if (reachable(src)) {
 711       movq(dst, as_Address(src));
 712     } else {
 713       lea(scratch, src);
 714       movq(dst, Address(scratch, 0));
 715     }
 716   }
 717 }
 718 
 719 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 720   movq(as_Address(dst), src);
 721 }
 722 
 723 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 724   movq(dst, as_Address(src));
 725 }
 726 
 727 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 728 void MacroAssembler::movptr(Address dst, intptr_t src) {
 729   mov64(rscratch1, src);
 730   movq(dst, rscratch1);
 731 }
 732 
 733 // These are mostly for initializing NULL
 734 void MacroAssembler::movptr(Address dst, int32_t src) {
 735   movslq(dst, src);
 736 }
 737 
 738 void MacroAssembler::movptr(Register dst, int32_t src) {
 739   mov64(dst, (intptr_t)src);
 740 }
 741 
 742 void MacroAssembler::pushoop(jobject obj) {
 743   movoop(rscratch1, obj);
 744   push(rscratch1);
 745 }
 746 
 747 void MacroAssembler::pushklass(Metadata* obj) {
 748   mov_metadata(rscratch1, obj);
 749   push(rscratch1);
 750 }
 751 
 752 void MacroAssembler::pushptr(AddressLiteral src) {
 753   lea(rscratch1, src);
 754   if (src.is_lval()) {
 755     push(rscratch1);
 756   } else {
 757     pushq(Address(rscratch1, 0));
 758   }
 759 }
 760 
 761 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 762   // we must set sp to zero to clear frame
 763   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 764   // must clear fp, so that compiled frames are not confused; it is
 765   // possible that we need it only for debugging
 766   if (clear_fp) {
 767     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 768   }
 769 
 770   // Always clear the pc because it could have been set by make_walkable()
 771   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 772   vzeroupper();
 773 }
 774 
 775 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 776                                          Register last_java_fp,
 777                                          address  last_java_pc) {
 778   vzeroupper();
 779   // determine last_java_sp register
 780   if (!last_java_sp->is_valid()) {
 781     last_java_sp = rsp;
 782   }
 783 
 784   // last_java_fp is optional
 785   if (last_java_fp->is_valid()) {
 786     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 787            last_java_fp);
 788   }
 789 
 790   // last_java_pc is optional
 791   if (last_java_pc != NULL) {
 792     Address java_pc(r15_thread,
 793                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 794     lea(rscratch1, InternalAddress(last_java_pc));
 795     movptr(java_pc, rscratch1);
 796   }
 797 
 798   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 799 }
 800 
 801 static void pass_arg0(MacroAssembler* masm, Register arg) {
 802   if (c_rarg0 != arg ) {
 803     masm->mov(c_rarg0, arg);
 804   }
 805 }
 806 
 807 static void pass_arg1(MacroAssembler* masm, Register arg) {
 808   if (c_rarg1 != arg ) {
 809     masm->mov(c_rarg1, arg);
 810   }
 811 }
 812 
 813 static void pass_arg2(MacroAssembler* masm, Register arg) {
 814   if (c_rarg2 != arg ) {
 815     masm->mov(c_rarg2, arg);
 816   }
 817 }
 818 
 819 static void pass_arg3(MacroAssembler* masm, Register arg) {
 820   if (c_rarg3 != arg ) {
 821     masm->mov(c_rarg3, arg);
 822   }
 823 }
 824 
 825 void MacroAssembler::stop(const char* msg) {
 826   address rip = pc();
 827   pusha(); // get regs on stack
 828   lea(c_rarg0, ExternalAddress((address) msg));
 829   lea(c_rarg1, InternalAddress(rip));
 830   movq(c_rarg2, rsp); // pass pointer to regs array
 831   andq(rsp, -16); // align stack as required by ABI
 832   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 833   hlt();
 834 }
 835 
 836 void MacroAssembler::warn(const char* msg) {
 837   push(rbp);
 838   movq(rbp, rsp);
 839   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 840   push_CPU_state();   // keeps alignment at 16 bytes
 841   lea(c_rarg0, ExternalAddress((address) msg));
 842   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 843   pop_CPU_state();
 844   mov(rsp, rbp);
 845   pop(rbp);
 846 }
 847 
 848 void MacroAssembler::print_state() {
 849   address rip = pc();
 850   pusha();            // get regs on stack
 851   push(rbp);
 852   movq(rbp, rsp);
 853   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 854   push_CPU_state();   // keeps alignment at 16 bytes
 855 
 856   lea(c_rarg0, InternalAddress(rip));
 857   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 858   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 859 
 860   pop_CPU_state();
 861   mov(rsp, rbp);
 862   pop(rbp);
 863   popa();
 864 }
 865 
 866 #ifndef PRODUCT
 867 extern "C" void findpc(intptr_t x);
 868 #endif
 869 
 870 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 871   // In order to get locks to work, we need to fake a in_VM state
 872   if (ShowMessageBoxOnError) {
 873     JavaThread* thread = JavaThread::current();
 874     JavaThreadState saved_state = thread->thread_state();
 875     thread->set_thread_state(_thread_in_vm);
 876 #ifndef PRODUCT
 877     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 878       ttyLocker ttyl;
 879       BytecodeCounter::print();
 880     }
 881 #endif
 882     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 883     // XXX correct this offset for amd64
 884     // This is the value of eip which points to where verify_oop will return.
 885     if (os::message_box(msg, "Execution stopped, print registers?")) {
 886       print_state64(pc, regs);
 887       BREAKPOINT;
 888       assert(false, "start up GDB");
 889     }
 890     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 891   } else {
 892     ttyLocker ttyl;
 893     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 894                     msg);
 895     assert(false, "DEBUG MESSAGE: %s", msg);
 896   }
 897 }
 898 
 899 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 900   ttyLocker ttyl;
 901   FlagSetting fs(Debugging, true);
 902   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 903 #ifndef PRODUCT
 904   tty->cr();
 905   findpc(pc);
 906   tty->cr();
 907 #endif
 908 #define PRINT_REG(rax, value) \
 909   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 910   PRINT_REG(rax, regs[15]);
 911   PRINT_REG(rbx, regs[12]);
 912   PRINT_REG(rcx, regs[14]);
 913   PRINT_REG(rdx, regs[13]);
 914   PRINT_REG(rdi, regs[8]);
 915   PRINT_REG(rsi, regs[9]);
 916   PRINT_REG(rbp, regs[10]);
 917   PRINT_REG(rsp, regs[11]);
 918   PRINT_REG(r8 , regs[7]);
 919   PRINT_REG(r9 , regs[6]);
 920   PRINT_REG(r10, regs[5]);
 921   PRINT_REG(r11, regs[4]);
 922   PRINT_REG(r12, regs[3]);
 923   PRINT_REG(r13, regs[2]);
 924   PRINT_REG(r14, regs[1]);
 925   PRINT_REG(r15, regs[0]);
 926 #undef PRINT_REG
 927   // Print some words near top of staack.
 928   int64_t* rsp = (int64_t*) regs[11];
 929   int64_t* dump_sp = rsp;
 930   for (int col1 = 0; col1 < 8; col1++) {
 931     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 932     os::print_location(tty, *dump_sp++);
 933   }
 934   for (int row = 0; row < 25; row++) {
 935     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 936     for (int col = 0; col < 4; col++) {
 937       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 938     }
 939     tty->cr();
 940   }
 941   // Print some instructions around pc:
 942   Disassembler::decode((address)pc-64, (address)pc);
 943   tty->print_cr("--------");
 944   Disassembler::decode((address)pc, (address)pc+32);
 945 }
 946 
 947 #endif // _LP64
 948 
 949 // Now versions that are common to 32/64 bit
 950 
 951 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 952   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 953 }
 954 
 955 void MacroAssembler::addptr(Register dst, Register src) {
 956   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 957 }
 958 
 959 void MacroAssembler::addptr(Address dst, Register src) {
 960   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 961 }
 962 
 963 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 964   if (reachable(src)) {
 965     Assembler::addsd(dst, as_Address(src));
 966   } else {
 967     lea(rscratch1, src);
 968     Assembler::addsd(dst, Address(rscratch1, 0));
 969   }
 970 }
 971 
 972 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 973   if (reachable(src)) {
 974     addss(dst, as_Address(src));
 975   } else {
 976     lea(rscratch1, src);
 977     addss(dst, Address(rscratch1, 0));
 978   }
 979 }
 980 
 981 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 982   if (reachable(src)) {
 983     Assembler::addpd(dst, as_Address(src));
 984   } else {
 985     lea(rscratch1, src);
 986     Assembler::addpd(dst, Address(rscratch1, 0));
 987   }
 988 }
 989 
 990 void MacroAssembler::align(int modulus) {
 991   align(modulus, offset());
 992 }
 993 
 994 void MacroAssembler::align(int modulus, int target) {
 995   if (target % modulus != 0) {
 996     nop(modulus - (target % modulus));
 997   }
 998 }
 999 
1000 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1001   // Used in sign-masking with aligned address.
1002   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1003   if (reachable(src)) {
1004     Assembler::andpd(dst, as_Address(src));
1005   } else {
1006     lea(rscratch1, src);
1007     Assembler::andpd(dst, Address(rscratch1, 0));
1008   }
1009 }
1010 
1011 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1012   // Used in sign-masking with aligned address.
1013   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1014   if (reachable(src)) {
1015     Assembler::andps(dst, as_Address(src));
1016   } else {
1017     lea(rscratch1, src);
1018     Assembler::andps(dst, Address(rscratch1, 0));
1019   }
1020 }
1021 
1022 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1023   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1024 }
1025 
1026 void MacroAssembler::atomic_incl(Address counter_addr) {
1027   if (os::is_MP())
1028     lock();
1029   incrementl(counter_addr);
1030 }
1031 
1032 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1033   if (reachable(counter_addr)) {
1034     atomic_incl(as_Address(counter_addr));
1035   } else {
1036     lea(scr, counter_addr);
1037     atomic_incl(Address(scr, 0));
1038   }
1039 }
1040 
1041 #ifdef _LP64
1042 void MacroAssembler::atomic_incq(Address counter_addr) {
1043   if (os::is_MP())
1044     lock();
1045   incrementq(counter_addr);
1046 }
1047 
1048 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1049   if (reachable(counter_addr)) {
1050     atomic_incq(as_Address(counter_addr));
1051   } else {
1052     lea(scr, counter_addr);
1053     atomic_incq(Address(scr, 0));
1054   }
1055 }
1056 #endif
1057 
1058 // Writes to stack successive pages until offset reached to check for
1059 // stack overflow + shadow pages.  This clobbers tmp.
1060 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1061   movptr(tmp, rsp);
1062   // Bang stack for total size given plus shadow page size.
1063   // Bang one page at a time because large size can bang beyond yellow and
1064   // red zones.
1065   Label loop;
1066   bind(loop);
1067   movl(Address(tmp, (-os::vm_page_size())), size );
1068   subptr(tmp, os::vm_page_size());
1069   subl(size, os::vm_page_size());
1070   jcc(Assembler::greater, loop);
1071 
1072   // Bang down shadow pages too.
1073   // At this point, (tmp-0) is the last address touched, so don't
1074   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1075   // was post-decremented.)  Skip this address by starting at i=1, and
1076   // touch a few more pages below.  N.B.  It is important to touch all
1077   // the way down including all pages in the shadow zone.
1078   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1079     // this could be any sized move but this is can be a debugging crumb
1080     // so the bigger the better.
1081     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1082   }
1083 }
1084 
1085 void MacroAssembler::reserved_stack_check() {
1086     // testing if reserved zone needs to be enabled
1087     Label no_reserved_zone_enabling;
1088     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1089     NOT_LP64(get_thread(rsi);)
1090 
1091     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1092     jcc(Assembler::below, no_reserved_zone_enabling);
1093 
1094     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1095     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1096     should_not_reach_here();
1097 
1098     bind(no_reserved_zone_enabling);
1099 }
1100 
1101 int MacroAssembler::biased_locking_enter(Register lock_reg,
1102                                          Register obj_reg,
1103                                          Register swap_reg,
1104                                          Register tmp_reg,
1105                                          bool swap_reg_contains_mark,
1106                                          Label& done,
1107                                          Label* slow_case,
1108                                          BiasedLockingCounters* counters) {
1109   assert(UseBiasedLocking, "why call this otherwise?");
1110   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1111   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1112   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1113   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1114   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1115   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1116 
1117   shenandoah_store_addr_check(obj_reg);
1118 
1119   if (PrintBiasedLockingStatistics && counters == NULL) {
1120     counters = BiasedLocking::counters();
1121   }
1122   // Biased locking
1123   // See whether the lock is currently biased toward our thread and
1124   // whether the epoch is still valid
1125   // Note that the runtime guarantees sufficient alignment of JavaThread
1126   // pointers to allow age to be placed into low bits
1127   // First check to see whether biasing is even enabled for this object
1128   Label cas_label;
1129   int null_check_offset = -1;
1130   if (!swap_reg_contains_mark) {
1131     null_check_offset = offset();
1132     movptr(swap_reg, mark_addr);
1133   }
1134   movptr(tmp_reg, swap_reg);
1135   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1136   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1137   jcc(Assembler::notEqual, cas_label);
1138   // The bias pattern is present in the object's header. Need to check
1139   // whether the bias owner and the epoch are both still current.
1140 #ifndef _LP64
1141   // Note that because there is no current thread register on x86_32 we
1142   // need to store off the mark word we read out of the object to
1143   // avoid reloading it and needing to recheck invariants below. This
1144   // store is unfortunate but it makes the overall code shorter and
1145   // simpler.
1146   movptr(saved_mark_addr, swap_reg);
1147 #endif
1148   if (swap_reg_contains_mark) {
1149     null_check_offset = offset();
1150   }
1151   load_prototype_header(tmp_reg, obj_reg);
1152 #ifdef _LP64
1153   orptr(tmp_reg, r15_thread);
1154   xorptr(tmp_reg, swap_reg);
1155   Register header_reg = tmp_reg;
1156 #else
1157   xorptr(tmp_reg, swap_reg);
1158   get_thread(swap_reg);
1159   xorptr(swap_reg, tmp_reg);
1160   Register header_reg = swap_reg;
1161 #endif
1162   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1163   if (counters != NULL) {
1164     cond_inc32(Assembler::zero,
1165                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1166   }
1167   jcc(Assembler::equal, done);
1168 
1169   Label try_revoke_bias;
1170   Label try_rebias;
1171 
1172   // At this point we know that the header has the bias pattern and
1173   // that we are not the bias owner in the current epoch. We need to
1174   // figure out more details about the state of the header in order to
1175   // know what operations can be legally performed on the object's
1176   // header.
1177 
1178   // If the low three bits in the xor result aren't clear, that means
1179   // the prototype header is no longer biased and we have to revoke
1180   // the bias on this object.
1181   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1182   jccb_if_possible(Assembler::notZero, try_revoke_bias);
1183 
1184   // Biasing is still enabled for this data type. See whether the
1185   // epoch of the current bias is still valid, meaning that the epoch
1186   // bits of the mark word are equal to the epoch bits of the
1187   // prototype header. (Note that the prototype header's epoch bits
1188   // only change at a safepoint.) If not, attempt to rebias the object
1189   // toward the current thread. Note that we must be absolutely sure
1190   // that the current epoch is invalid in order to do this because
1191   // otherwise the manipulations it performs on the mark word are
1192   // illegal.
1193   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1194   jccb_if_possible(Assembler::notZero, try_rebias);
1195 
1196   // The epoch of the current bias is still valid but we know nothing
1197   // about the owner; it might be set or it might be clear. Try to
1198   // acquire the bias of the object using an atomic operation. If this
1199   // fails we will go in to the runtime to revoke the object's bias.
1200   // Note that we first construct the presumed unbiased header so we
1201   // don't accidentally blow away another thread's valid bias.
1202   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1203   andptr(swap_reg,
1204          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1205 #ifdef _LP64
1206   movptr(tmp_reg, swap_reg);
1207   orptr(tmp_reg, r15_thread);
1208 #else
1209   get_thread(tmp_reg);
1210   orptr(tmp_reg, swap_reg);
1211 #endif
1212   if (os::is_MP()) {
1213     lock();
1214   }
1215   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1216   // If the biasing toward our thread failed, this means that
1217   // another thread succeeded in biasing it toward itself and we
1218   // need to revoke that bias. The revocation will occur in the
1219   // interpreter runtime in the slow case.
1220   if (counters != NULL) {
1221     cond_inc32(Assembler::zero,
1222                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1223   }
1224   if (slow_case != NULL) {
1225     jcc(Assembler::notZero, *slow_case);
1226   }
1227   jmp(done);
1228 
1229   bind(try_rebias);
1230   // At this point we know the epoch has expired, meaning that the
1231   // current "bias owner", if any, is actually invalid. Under these
1232   // circumstances _only_, we are allowed to use the current header's
1233   // value as the comparison value when doing the cas to acquire the
1234   // bias in the current epoch. In other words, we allow transfer of
1235   // the bias from one thread to another directly in this situation.
1236   //
1237   // FIXME: due to a lack of registers we currently blow away the age
1238   // bits in this situation. Should attempt to preserve them.
1239   load_prototype_header(tmp_reg, obj_reg);
1240 #ifdef _LP64
1241   orptr(tmp_reg, r15_thread);
1242 #else
1243   get_thread(swap_reg);
1244   orptr(tmp_reg, swap_reg);
1245   movptr(swap_reg, saved_mark_addr);
1246 #endif
1247   if (os::is_MP()) {
1248     lock();
1249   }
1250   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1251   // If the biasing toward our thread failed, then another thread
1252   // succeeded in biasing it toward itself and we need to revoke that
1253   // bias. The revocation will occur in the runtime in the slow case.
1254   if (counters != NULL) {
1255     cond_inc32(Assembler::zero,
1256                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1257   }
1258   if (slow_case != NULL) {
1259     jcc(Assembler::notZero, *slow_case);
1260   }
1261   jmp(done);
1262 
1263   bind(try_revoke_bias);
1264   // The prototype mark in the klass doesn't have the bias bit set any
1265   // more, indicating that objects of this data type are not supposed
1266   // to be biased any more. We are going to try to reset the mark of
1267   // this object to the prototype value and fall through to the
1268   // CAS-based locking scheme. Note that if our CAS fails, it means
1269   // that another thread raced us for the privilege of revoking the
1270   // bias of this particular object, so it's okay to continue in the
1271   // normal locking code.
1272   //
1273   // FIXME: due to a lack of registers we currently blow away the age
1274   // bits in this situation. Should attempt to preserve them.
1275   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1276   load_prototype_header(tmp_reg, obj_reg);
1277   if (os::is_MP()) {
1278     lock();
1279   }
1280   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1281   // Fall through to the normal CAS-based lock, because no matter what
1282   // the result of the above CAS, some thread must have succeeded in
1283   // removing the bias bit from the object's header.
1284   if (counters != NULL) {
1285     cond_inc32(Assembler::zero,
1286                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1287   }
1288 
1289   bind(cas_label);
1290 
1291   return null_check_offset;
1292 }
1293 
1294 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1295   assert(UseBiasedLocking, "why call this otherwise?");
1296 
1297   // Check for biased locking unlock case, which is a no-op
1298   // Note: we do not have to check the thread ID for two reasons.
1299   // First, the interpreter checks for IllegalMonitorStateException at
1300   // a higher level. Second, if the bias was revoked while we held the
1301   // lock, the object could not be rebiased toward another thread, so
1302   // the bias bit would be clear.
1303   shenandoah_store_addr_check(obj_reg); // Access mark word
1304   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1305   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1306   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1307   jcc(Assembler::equal, done);
1308 }
1309 
1310 #ifdef COMPILER2
1311 
1312 #if INCLUDE_RTM_OPT
1313 
1314 // Update rtm_counters based on abort status
1315 // input: abort_status
1316 //        rtm_counters (RTMLockingCounters*)
1317 // flags are killed
1318 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1319 
1320   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1321   if (PrintPreciseRTMLockingStatistics) {
1322     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1323       Label check_abort;
1324       testl(abort_status, (1<<i));
1325       jccb(Assembler::equal, check_abort);
1326       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1327       bind(check_abort);
1328     }
1329   }
1330 }
1331 
1332 // Branch if (random & (count-1) != 0), count is 2^n
1333 // tmp, scr and flags are killed
1334 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1335   assert(tmp == rax, "");
1336   assert(scr == rdx, "");
1337   rdtsc(); // modifies EDX:EAX
1338   andptr(tmp, count-1);
1339   jccb(Assembler::notZero, brLabel);
1340 }
1341 
1342 // Perform abort ratio calculation, set no_rtm bit if high ratio
1343 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1344 // tmpReg, rtm_counters_Reg and flags are killed
1345 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1346                                                  Register rtm_counters_Reg,
1347                                                  RTMLockingCounters* rtm_counters,
1348                                                  Metadata* method_data) {
1349   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1350 
1351   if (RTMLockingCalculationDelay > 0) {
1352     // Delay calculation
1353     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1354     testptr(tmpReg, tmpReg);
1355     jccb(Assembler::equal, L_done);
1356   }
1357   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1358   //   Aborted transactions = abort_count * 100
1359   //   All transactions = total_count *  RTMTotalCountIncrRate
1360   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1361 
1362   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1363   cmpptr(tmpReg, RTMAbortThreshold);
1364   jccb(Assembler::below, L_check_always_rtm2);
1365   imulptr(tmpReg, tmpReg, 100);
1366 
1367   Register scrReg = rtm_counters_Reg;
1368   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1369   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1370   imulptr(scrReg, scrReg, RTMAbortRatio);
1371   cmpptr(tmpReg, scrReg);
1372   jccb(Assembler::below, L_check_always_rtm1);
1373   if (method_data != NULL) {
1374     // set rtm_state to "no rtm" in MDO
1375     mov_metadata(tmpReg, method_data);
1376     if (os::is_MP()) {
1377       lock();
1378     }
1379     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1380   }
1381   jmpb(L_done);
1382   bind(L_check_always_rtm1);
1383   // Reload RTMLockingCounters* address
1384   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1385   bind(L_check_always_rtm2);
1386   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1387   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1388   jccb(Assembler::below, L_done);
1389   if (method_data != NULL) {
1390     // set rtm_state to "always rtm" in MDO
1391     mov_metadata(tmpReg, method_data);
1392     if (os::is_MP()) {
1393       lock();
1394     }
1395     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1396   }
1397   bind(L_done);
1398 }
1399 
1400 // Update counters and perform abort ratio calculation
1401 // input:  abort_status_Reg
1402 // rtm_counters_Reg, flags are killed
1403 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1404                                    Register rtm_counters_Reg,
1405                                    RTMLockingCounters* rtm_counters,
1406                                    Metadata* method_data,
1407                                    bool profile_rtm) {
1408 
1409   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1410   // update rtm counters based on rax value at abort
1411   // reads abort_status_Reg, updates flags
1412   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1413   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1414   if (profile_rtm) {
1415     // Save abort status because abort_status_Reg is used by following code.
1416     if (RTMRetryCount > 0) {
1417       push(abort_status_Reg);
1418     }
1419     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1420     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1421     // restore abort status
1422     if (RTMRetryCount > 0) {
1423       pop(abort_status_Reg);
1424     }
1425   }
1426 }
1427 
1428 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1429 // inputs: retry_count_Reg
1430 //       : abort_status_Reg
1431 // output: retry_count_Reg decremented by 1
1432 // flags are killed
1433 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1434   Label doneRetry;
1435   assert(abort_status_Reg == rax, "");
1436   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1437   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1438   // if reason is in 0x6 and retry count != 0 then retry
1439   andptr(abort_status_Reg, 0x6);
1440   jccb(Assembler::zero, doneRetry);
1441   testl(retry_count_Reg, retry_count_Reg);
1442   jccb(Assembler::zero, doneRetry);
1443   pause();
1444   decrementl(retry_count_Reg);
1445   jmp(retryLabel);
1446   bind(doneRetry);
1447 }
1448 
1449 // Spin and retry if lock is busy,
1450 // inputs: box_Reg (monitor address)
1451 //       : retry_count_Reg
1452 // output: retry_count_Reg decremented by 1
1453 //       : clear z flag if retry count exceeded
1454 // tmp_Reg, scr_Reg, flags are killed
1455 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1456                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1457   Label SpinLoop, SpinExit, doneRetry;
1458   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1459 
1460   testl(retry_count_Reg, retry_count_Reg);
1461   jccb(Assembler::zero, doneRetry);
1462   decrementl(retry_count_Reg);
1463   movptr(scr_Reg, RTMSpinLoopCount);
1464 
1465   bind(SpinLoop);
1466   pause();
1467   decrementl(scr_Reg);
1468   jccb(Assembler::lessEqual, SpinExit);
1469   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1470   testptr(tmp_Reg, tmp_Reg);
1471   jccb(Assembler::notZero, SpinLoop);
1472 
1473   bind(SpinExit);
1474   jmp(retryLabel);
1475   bind(doneRetry);
1476   incrementl(retry_count_Reg); // clear z flag
1477 }
1478 
1479 // Use RTM for normal stack locks
1480 // Input: objReg (object to lock)
1481 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1482                                        Register retry_on_abort_count_Reg,
1483                                        RTMLockingCounters* stack_rtm_counters,
1484                                        Metadata* method_data, bool profile_rtm,
1485                                        Label& DONE_LABEL, Label& IsInflated) {
1486   assert(UseRTMForStackLocks, "why call this otherwise?");
1487   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1488   assert(tmpReg == rax, "");
1489   assert(scrReg == rdx, "");
1490   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1491 
1492   if (RTMRetryCount > 0) {
1493     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1494     bind(L_rtm_retry);
1495   }
1496   shenandoah_store_addr_check(objReg); // Access mark word
1497   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1498   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1499   jcc(Assembler::notZero, IsInflated);
1500 
1501   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1502     Label L_noincrement;
1503     if (RTMTotalCountIncrRate > 1) {
1504       // tmpReg, scrReg and flags are killed
1505       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1506     }
1507     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1508     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1509     bind(L_noincrement);
1510   }
1511   xbegin(L_on_abort);
1512   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1513   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1514   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1515   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1516 
1517   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1518   if (UseRTMXendForLockBusy) {
1519     xend();
1520     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1521     jmp(L_decrement_retry);
1522   }
1523   else {
1524     xabort(0);
1525   }
1526   bind(L_on_abort);
1527   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1528     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1529   }
1530   bind(L_decrement_retry);
1531   if (RTMRetryCount > 0) {
1532     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1533     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1534   }
1535 }
1536 
1537 // Use RTM for inflating locks
1538 // inputs: objReg (object to lock)
1539 //         boxReg (on-stack box address (displaced header location) - KILLED)
1540 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1541 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1542                                           Register scrReg, Register retry_on_busy_count_Reg,
1543                                           Register retry_on_abort_count_Reg,
1544                                           RTMLockingCounters* rtm_counters,
1545                                           Metadata* method_data, bool profile_rtm,
1546                                           Label& DONE_LABEL) {
1547   assert(UseRTMLocking, "why call this otherwise?");
1548   assert(tmpReg == rax, "");
1549   assert(scrReg == rdx, "");
1550   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1551   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1552 
1553   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1554   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1555   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1556 
1557   if (RTMRetryCount > 0) {
1558     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1559     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1560     bind(L_rtm_retry);
1561   }
1562   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1563     Label L_noincrement;
1564     if (RTMTotalCountIncrRate > 1) {
1565       // tmpReg, scrReg and flags are killed
1566       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1567     }
1568     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1569     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1570     bind(L_noincrement);
1571   }
1572   xbegin(L_on_abort);
1573   shenandoah_store_addr_check(objReg); // Access mark word
1574   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1575   movptr(tmpReg, Address(tmpReg, owner_offset));
1576   testptr(tmpReg, tmpReg);
1577   jcc(Assembler::zero, DONE_LABEL);
1578   if (UseRTMXendForLockBusy) {
1579     xend();
1580     jmp(L_decrement_retry);
1581   }
1582   else {
1583     xabort(0);
1584   }
1585   bind(L_on_abort);
1586   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1587   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1588     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1589   }
1590   if (RTMRetryCount > 0) {
1591     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1592     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1593   }
1594 
1595   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1596   testptr(tmpReg, tmpReg) ;
1597   jccb(Assembler::notZero, L_decrement_retry) ;
1598 
1599   // Appears unlocked - try to swing _owner from null to non-null.
1600   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1601 #ifdef _LP64
1602   Register threadReg = r15_thread;
1603 #else
1604   get_thread(scrReg);
1605   Register threadReg = scrReg;
1606 #endif
1607   if (os::is_MP()) {
1608     lock();
1609   }
1610   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1611 
1612   if (RTMRetryCount > 0) {
1613     // success done else retry
1614     jccb(Assembler::equal, DONE_LABEL) ;
1615     bind(L_decrement_retry);
1616     // Spin and retry if lock is busy.
1617     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1618   }
1619   else {
1620     bind(L_decrement_retry);
1621   }
1622 }
1623 
1624 #endif //  INCLUDE_RTM_OPT
1625 
1626 // Fast_Lock and Fast_Unlock used by C2
1627 
1628 // Because the transitions from emitted code to the runtime
1629 // monitorenter/exit helper stubs are so slow it's critical that
1630 // we inline both the stack-locking fast-path and the inflated fast path.
1631 //
1632 // See also: cmpFastLock and cmpFastUnlock.
1633 //
1634 // What follows is a specialized inline transliteration of the code
1635 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1636 // another option would be to emit TrySlowEnter and TrySlowExit methods
1637 // at startup-time.  These methods would accept arguments as
1638 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1639 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1640 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1641 // In practice, however, the # of lock sites is bounded and is usually small.
1642 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1643 // if the processor uses simple bimodal branch predictors keyed by EIP
1644 // Since the helper routines would be called from multiple synchronization
1645 // sites.
1646 //
1647 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1648 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1649 // to those specialized methods.  That'd give us a mostly platform-independent
1650 // implementation that the JITs could optimize and inline at their pleasure.
1651 // Done correctly, the only time we'd need to cross to native could would be
1652 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1653 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1654 // (b) explicit barriers or fence operations.
1655 //
1656 // TODO:
1657 //
1658 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1659 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1660 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1661 //    the lock operators would typically be faster than reifying Self.
1662 //
1663 // *  Ideally I'd define the primitives as:
1664 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1665 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1666 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1667 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1668 //    Furthermore the register assignments are overconstrained, possibly resulting in
1669 //    sub-optimal code near the synchronization site.
1670 //
1671 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1672 //    Alternately, use a better sp-proximity test.
1673 //
1674 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1675 //    Either one is sufficient to uniquely identify a thread.
1676 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1677 //
1678 // *  Intrinsify notify() and notifyAll() for the common cases where the
1679 //    object is locked by the calling thread but the waitlist is empty.
1680 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1681 //
1682 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1683 //    But beware of excessive branch density on AMD Opterons.
1684 //
1685 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1686 //    or failure of the fast-path.  If the fast-path fails then we pass
1687 //    control to the slow-path, typically in C.  In Fast_Lock and
1688 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1689 //    will emit a conditional branch immediately after the node.
1690 //    So we have branches to branches and lots of ICC.ZF games.
1691 //    Instead, it might be better to have C2 pass a "FailureLabel"
1692 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1693 //    will drop through the node.  ICC.ZF is undefined at exit.
1694 //    In the case of failure, the node will branch directly to the
1695 //    FailureLabel
1696 
1697 
1698 // obj: object to lock
1699 // box: on-stack box address (displaced header location) - KILLED
1700 // rax,: tmp -- KILLED
1701 // scr: tmp -- KILLED
1702 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1703                                Register scrReg, Register cx1Reg, Register cx2Reg,
1704                                BiasedLockingCounters* counters,
1705                                RTMLockingCounters* rtm_counters,
1706                                RTMLockingCounters* stack_rtm_counters,
1707                                Metadata* method_data,
1708                                bool use_rtm, bool profile_rtm) {
1709   // Ensure the register assignments are disjoint
1710   assert(tmpReg == rax, "");
1711 
1712   if (use_rtm) {
1713     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1714   } else {
1715     assert(cx1Reg == noreg, "");
1716     assert(cx2Reg == noreg, "");
1717     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1718   }
1719 
1720   shenandoah_store_addr_check(objReg); // Access mark word
1721 
1722   if (counters != NULL) {
1723     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1724   }
1725   if (EmitSync & 1) {
1726       // set box->dhw = markOopDesc::unused_mark()
1727       // Force all sync thru slow-path: slow_enter() and slow_exit()
1728       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1729       cmpptr (rsp, (int32_t)NULL_WORD);
1730   } else {
1731     // Possible cases that we'll encounter in fast_lock
1732     // ------------------------------------------------
1733     // * Inflated
1734     //    -- unlocked
1735     //    -- Locked
1736     //       = by self
1737     //       = by other
1738     // * biased
1739     //    -- by Self
1740     //    -- by other
1741     // * neutral
1742     // * stack-locked
1743     //    -- by self
1744     //       = sp-proximity test hits
1745     //       = sp-proximity test generates false-negative
1746     //    -- by other
1747     //
1748 
1749     Label IsInflated, DONE_LABEL;
1750 
1751     // it's stack-locked, biased or neutral
1752     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1753     // order to reduce the number of conditional branches in the most common cases.
1754     // Beware -- there's a subtle invariant that fetch of the markword
1755     // at [FETCH], below, will never observe a biased encoding (*101b).
1756     // If this invariant is not held we risk exclusion (safety) failure.
1757     if (UseBiasedLocking && !UseOptoBiasInlining) {
1758       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1759     }
1760 
1761 #if INCLUDE_RTM_OPT
1762     if (UseRTMForStackLocks && use_rtm) {
1763       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1764                         stack_rtm_counters, method_data, profile_rtm,
1765                         DONE_LABEL, IsInflated);
1766     }
1767 #endif // INCLUDE_RTM_OPT
1768 
1769     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1770     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1771     jccb_if_possible(Assembler::notZero, IsInflated);
1772 
1773     // Attempt stack-locking ...
1774     orptr (tmpReg, markOopDesc::unlocked_value);
1775     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1776     if (os::is_MP()) {
1777       lock();
1778     }
1779     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1780     if (counters != NULL) {
1781       cond_inc32(Assembler::equal,
1782                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1783     }
1784     jcc(Assembler::equal, DONE_LABEL);           // Success
1785 
1786     // Recursive locking.
1787     // The object is stack-locked: markword contains stack pointer to BasicLock.
1788     // Locked by current thread if difference with current SP is less than one page.
1789     subptr(tmpReg, rsp);
1790     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1791     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1792     movptr(Address(boxReg, 0), tmpReg);
1793     if (counters != NULL) {
1794       cond_inc32(Assembler::equal,
1795                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1796     }
1797     jmp(DONE_LABEL);
1798 
1799     bind(IsInflated);
1800     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1801 
1802 #if INCLUDE_RTM_OPT
1803     // Use the same RTM locking code in 32- and 64-bit VM.
1804     if (use_rtm) {
1805       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1806                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1807     } else {
1808 #endif // INCLUDE_RTM_OPT
1809 
1810 #ifndef _LP64
1811     // The object is inflated.
1812 
1813     // boxReg refers to the on-stack BasicLock in the current frame.
1814     // We'd like to write:
1815     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1816     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1817     // additional latency as we have another ST in the store buffer that must drain.
1818 
1819     if (EmitSync & 8192) {
1820        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1821        get_thread (scrReg);
1822        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1823        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1824        if (os::is_MP()) {
1825          lock();
1826        }
1827        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1828     } else
1829     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1830        // register juggle because we need tmpReg for cmpxchgptr below
1831        movptr(scrReg, boxReg);
1832        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1833 
1834        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1835        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1836           // prefetchw [eax + Offset(_owner)-2]
1837           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1838        }
1839 
1840        if ((EmitSync & 64) == 0) {
1841          // Optimistic form: consider XORL tmpReg,tmpReg
1842          movptr(tmpReg, NULL_WORD);
1843        } else {
1844          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1845          // Test-And-CAS instead of CAS
1846          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1847          testptr(tmpReg, tmpReg);                   // Locked ?
1848          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1849        }
1850 
1851        // Appears unlocked - try to swing _owner from null to non-null.
1852        // Ideally, I'd manifest "Self" with get_thread and then attempt
1853        // to CAS the register containing Self into m->Owner.
1854        // But we don't have enough registers, so instead we can either try to CAS
1855        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1856        // we later store "Self" into m->Owner.  Transiently storing a stack address
1857        // (rsp or the address of the box) into  m->owner is harmless.
1858        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1859        if (os::is_MP()) {
1860          lock();
1861        }
1862        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1863        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1864        // If we weren't able to swing _owner from NULL to the BasicLock
1865        // then take the slow path.
1866        jccb_if_possible(Assembler::notZero, DONE_LABEL);
1867        // update _owner from BasicLock to thread
1868        get_thread (scrReg);                    // beware: clobbers ICCs
1869        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1870        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1871 
1872        // If the CAS fails we can either retry or pass control to the slow-path.
1873        // We use the latter tactic.
1874        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1875        // If the CAS was successful ...
1876        //   Self has acquired the lock
1877        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1878        // Intentional fall-through into DONE_LABEL ...
1879     } else {
1880        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1881        movptr(boxReg, tmpReg);
1882 
1883        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1884        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1885           // prefetchw [eax + Offset(_owner)-2]
1886           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1887        }
1888 
1889        if ((EmitSync & 64) == 0) {
1890          // Optimistic form
1891          xorptr  (tmpReg, tmpReg);
1892        } else {
1893          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1894          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1895          testptr(tmpReg, tmpReg);                   // Locked ?
1896          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1897        }
1898 
1899        // Appears unlocked - try to swing _owner from null to non-null.
1900        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1901        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1902        get_thread (scrReg);
1903        if (os::is_MP()) {
1904          lock();
1905        }
1906        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1907 
1908        // If the CAS fails we can either retry or pass control to the slow-path.
1909        // We use the latter tactic.
1910        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1911        // If the CAS was successful ...
1912        //   Self has acquired the lock
1913        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1914        // Intentional fall-through into DONE_LABEL ...
1915     }
1916 #else // _LP64
1917     // It's inflated
1918     movq(scrReg, tmpReg);
1919     xorq(tmpReg, tmpReg);
1920 
1921     if (os::is_MP()) {
1922       lock();
1923     }
1924     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1925     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1926     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1927     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1928     // Intentional fall-through into DONE_LABEL ...
1929     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1930 #endif // _LP64
1931 #if INCLUDE_RTM_OPT
1932     } // use_rtm()
1933 #endif
1934     // DONE_LABEL is a hot target - we'd really like to place it at the
1935     // start of cache line by padding with NOPs.
1936     // See the AMD and Intel software optimization manuals for the
1937     // most efficient "long" NOP encodings.
1938     // Unfortunately none of our alignment mechanisms suffice.
1939     bind(DONE_LABEL);
1940 
1941     // At DONE_LABEL the icc ZFlag is set as follows ...
1942     // Fast_Unlock uses the same protocol.
1943     // ZFlag == 1 -> Success
1944     // ZFlag == 0 -> Failure - force control through the slow-path
1945   }
1946 }
1947 
1948 // obj: object to unlock
1949 // box: box address (displaced header location), killed.  Must be EAX.
1950 // tmp: killed, cannot be obj nor box.
1951 //
1952 // Some commentary on balanced locking:
1953 //
1954 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1955 // Methods that don't have provably balanced locking are forced to run in the
1956 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1957 // The interpreter provides two properties:
1958 // I1:  At return-time the interpreter automatically and quietly unlocks any
1959 //      objects acquired the current activation (frame).  Recall that the
1960 //      interpreter maintains an on-stack list of locks currently held by
1961 //      a frame.
1962 // I2:  If a method attempts to unlock an object that is not held by the
1963 //      the frame the interpreter throws IMSX.
1964 //
1965 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1966 // B() doesn't have provably balanced locking so it runs in the interpreter.
1967 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1968 // is still locked by A().
1969 //
1970 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1971 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1972 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1973 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1974 // Arguably given that the spec legislates the JNI case as undefined our implementation
1975 // could reasonably *avoid* checking owner in Fast_Unlock().
1976 // In the interest of performance we elide m->Owner==Self check in unlock.
1977 // A perfectly viable alternative is to elide the owner check except when
1978 // Xcheck:jni is enabled.
1979 
1980 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1981   assert(boxReg == rax, "");
1982   assert_different_registers(objReg, boxReg, tmpReg);
1983 
1984   shenandoah_store_addr_check(objReg); // Access mark word
1985 
1986   if (EmitSync & 4) {
1987     // Disable - inhibit all inlining.  Force control through the slow-path
1988     cmpptr (rsp, 0);
1989   } else {
1990     Label DONE_LABEL, Stacked, CheckSucc;
1991 
1992     // Critically, the biased locking test must have precedence over
1993     // and appear before the (box->dhw == 0) recursive stack-lock test.
1994     if (UseBiasedLocking && !UseOptoBiasInlining) {
1995        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1996     }
1997 
1998 #if INCLUDE_RTM_OPT
1999     if (UseRTMForStackLocks && use_rtm) {
2000       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
2001       Label L_regular_unlock;
2002       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
2003       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
2004       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
2005       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2006       xend();                                       // otherwise end...
2007       jmp(DONE_LABEL);                              // ... and we're done
2008       bind(L_regular_unlock);
2009     }
2010 #endif
2011 
2012     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2013     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2014     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2015     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2016     jccb  (Assembler::zero, Stacked);
2017 
2018     // It's inflated.
2019 #if INCLUDE_RTM_OPT
2020     if (use_rtm) {
2021       Label L_regular_inflated_unlock;
2022       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2023       movptr(boxReg, Address(tmpReg, owner_offset));
2024       testptr(boxReg, boxReg);
2025       jccb(Assembler::notZero, L_regular_inflated_unlock);
2026       xend();
2027       jmpb_if_possible(DONE_LABEL);
2028       bind(L_regular_inflated_unlock);
2029     }
2030 #endif
2031 
2032     // Despite our balanced locking property we still check that m->_owner == Self
2033     // as java routines or native JNI code called by this thread might
2034     // have released the lock.
2035     // Refer to the comments in synchronizer.cpp for how we might encode extra
2036     // state in _succ so we can avoid fetching EntryList|cxq.
2037     //
2038     // I'd like to add more cases in fast_lock() and fast_unlock() --
2039     // such as recursive enter and exit -- but we have to be wary of
2040     // I$ bloat, T$ effects and BP$ effects.
2041     //
2042     // If there's no contention try a 1-0 exit.  That is, exit without
2043     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2044     // we detect and recover from the race that the 1-0 exit admits.
2045     //
2046     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2047     // before it STs null into _owner, releasing the lock.  Updates
2048     // to data protected by the critical section must be visible before
2049     // we drop the lock (and thus before any other thread could acquire
2050     // the lock and observe the fields protected by the lock).
2051     // IA32's memory-model is SPO, so STs are ordered with respect to
2052     // each other and there's no need for an explicit barrier (fence).
2053     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2054 #ifndef _LP64
2055     get_thread (boxReg);
2056     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2057       // prefetchw [ebx + Offset(_owner)-2]
2058       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2059     }
2060 
2061     // Note that we could employ various encoding schemes to reduce
2062     // the number of loads below (currently 4) to just 2 or 3.
2063     // Refer to the comments in synchronizer.cpp.
2064     // In practice the chain of fetches doesn't seem to impact performance, however.
2065     xorptr(boxReg, boxReg);
2066     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2067        // Attempt to reduce branch density - AMD's branch predictor.
2068        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2069        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2070        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2071        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2072        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2073        jmpb_if_possible(DONE_LABEL);
2074     } else {
2075        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2076        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2077        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2078        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2079        jccb  (Assembler::notZero, CheckSucc);
2080        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2081        jmpb_if_possible(DONE_LABEL);
2082     }
2083 
2084     // The Following code fragment (EmitSync & 65536) improves the performance of
2085     // contended applications and contended synchronization microbenchmarks.
2086     // Unfortunately the emission of the code - even though not executed - causes regressions
2087     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2088     // with an equal number of never-executed NOPs results in the same regression.
2089     // We leave it off by default.
2090 
2091     if ((EmitSync & 65536) != 0) {
2092        Label LSuccess, LGoSlowPath ;
2093 
2094        bind  (CheckSucc);
2095 
2096        // Optional pre-test ... it's safe to elide this
2097        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2098        jccb(Assembler::zero, LGoSlowPath);
2099 
2100        // We have a classic Dekker-style idiom:
2101        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2102        // There are a number of ways to implement the barrier:
2103        // (1) lock:andl &m->_owner, 0
2104        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2105        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2106        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2107        // (2) If supported, an explicit MFENCE is appealing.
2108        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2109        //     particularly if the write-buffer is full as might be the case if
2110        //     if stores closely precede the fence or fence-equivalent instruction.
2111        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2112        //     as the situation has changed with Nehalem and Shanghai.
2113        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2114        //     The $lines underlying the top-of-stack should be in M-state.
2115        //     The locked add instruction is serializing, of course.
2116        // (4) Use xchg, which is serializing
2117        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2118        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2119        //     The integer condition codes will tell us if succ was 0.
2120        //     Since _succ and _owner should reside in the same $line and
2121        //     we just stored into _owner, it's likely that the $line
2122        //     remains in M-state for the lock:orl.
2123        //
2124        // We currently use (3), although it's likely that switching to (2)
2125        // is correct for the future.
2126 
2127        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2128        if (os::is_MP()) {
2129          lock(); addptr(Address(rsp, 0), 0);
2130        }
2131        // Ratify _succ remains non-null
2132        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2133        jccb  (Assembler::notZero, LSuccess);
2134 
2135        xorptr(boxReg, boxReg);                  // box is really EAX
2136        if (os::is_MP()) { lock(); }
2137        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2138        // There's no successor so we tried to regrab the lock with the
2139        // placeholder value. If that didn't work, then another thread
2140        // grabbed the lock so we're done (and exit was a success).
2141        jccb  (Assembler::notEqual, LSuccess);
2142        // Since we're low on registers we installed rsp as a placeholding in _owner.
2143        // Now install Self over rsp.  This is safe as we're transitioning from
2144        // non-null to non=null
2145        get_thread (boxReg);
2146        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2147        // Intentional fall-through into LGoSlowPath ...
2148 
2149        bind  (LGoSlowPath);
2150        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2151        jmpb_if_possible(DONE_LABEL);
2152 
2153        bind  (LSuccess);
2154        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2155        jmpb_if_possible(DONE_LABEL);
2156     }
2157 
2158     bind (Stacked);
2159     // It's not inflated and it's not recursively stack-locked and it's not biased.
2160     // It must be stack-locked.
2161     // Try to reset the header to displaced header.
2162     // The "box" value on the stack is stable, so we can reload
2163     // and be assured we observe the same value as above.
2164     movptr(tmpReg, Address(boxReg, 0));
2165     if (os::is_MP()) {
2166       lock();
2167     }
2168     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2169     // Intention fall-thru into DONE_LABEL
2170 
2171     // DONE_LABEL is a hot target - we'd really like to place it at the
2172     // start of cache line by padding with NOPs.
2173     // See the AMD and Intel software optimization manuals for the
2174     // most efficient "long" NOP encodings.
2175     // Unfortunately none of our alignment mechanisms suffice.
2176     if ((EmitSync & 65536) == 0) {
2177        bind (CheckSucc);
2178     }
2179 #else // _LP64
2180     // It's inflated
2181     if (EmitSync & 1024) {
2182       // Emit code to check that _owner == Self
2183       // We could fold the _owner test into subsequent code more efficiently
2184       // than using a stand-alone check, but since _owner checking is off by
2185       // default we don't bother. We also might consider predicating the
2186       // _owner==Self check on Xcheck:jni or running on a debug build.
2187       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2188       xorptr(boxReg, r15_thread);
2189     } else {
2190       xorptr(boxReg, boxReg);
2191     }
2192     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2193     jccb_if_possible(Assembler::notZero, DONE_LABEL);
2194     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2195     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2196     jccb  (Assembler::notZero, CheckSucc);
2197     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2198     jmpb_if_possible(DONE_LABEL);
2199 
2200     if ((EmitSync & 65536) == 0) {
2201       // Try to avoid passing control into the slow_path ...
2202       Label LSuccess, LGoSlowPath ;
2203       bind  (CheckSucc);
2204 
2205       // The following optional optimization can be elided if necessary
2206       // Effectively: if (succ == null) goto SlowPath
2207       // The code reduces the window for a race, however,
2208       // and thus benefits performance.
2209       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2210       jccb  (Assembler::zero, LGoSlowPath);
2211 
2212       xorptr(boxReg, boxReg);
2213       if ((EmitSync & 16) && os::is_MP()) {
2214         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2215       } else {
2216         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2217         if (os::is_MP()) {
2218           // Memory barrier/fence
2219           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2220           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2221           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2222           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2223           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2224           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2225           lock(); addl(Address(rsp, 0), 0);
2226         }
2227       }
2228       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2229       jccb  (Assembler::notZero, LSuccess);
2230 
2231       // Rare inopportune interleaving - race.
2232       // The successor vanished in the small window above.
2233       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2234       // We need to ensure progress and succession.
2235       // Try to reacquire the lock.
2236       // If that fails then the new owner is responsible for succession and this
2237       // thread needs to take no further action and can exit via the fast path (success).
2238       // If the re-acquire succeeds then pass control into the slow path.
2239       // As implemented, this latter mode is horrible because we generated more
2240       // coherence traffic on the lock *and* artifically extended the critical section
2241       // length while by virtue of passing control into the slow path.
2242 
2243       // box is really RAX -- the following CMPXCHG depends on that binding
2244       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2245       if (os::is_MP()) { lock(); }
2246       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2247       // There's no successor so we tried to regrab the lock.
2248       // If that didn't work, then another thread grabbed the
2249       // lock so we're done (and exit was a success).
2250       jccb  (Assembler::notEqual, LSuccess);
2251       // Intentional fall-through into slow-path
2252 
2253       bind  (LGoSlowPath);
2254       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2255       jmpb_if_possible(DONE_LABEL);
2256 
2257       bind  (LSuccess);
2258       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2259       jmpb_if_possible  (DONE_LABEL);
2260     }
2261 
2262     bind  (Stacked);
2263     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2264     if (os::is_MP()) { lock(); }
2265     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2266 
2267     if (EmitSync & 65536) {
2268        bind (CheckSucc);
2269     }
2270 #endif
2271     bind(DONE_LABEL);
2272   }
2273 }
2274 #endif // COMPILER2
2275 
2276 void MacroAssembler::c2bool(Register x) {
2277   // implements x == 0 ? 0 : 1
2278   // note: must only look at least-significant byte of x
2279   //       since C-style booleans are stored in one byte
2280   //       only! (was bug)
2281   andl(x, 0xFF);
2282   setb(Assembler::notZero, x);
2283 }
2284 
2285 // Wouldn't need if AddressLiteral version had new name
2286 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2287   Assembler::call(L, rtype);
2288 }
2289 
2290 void MacroAssembler::call(Register entry) {
2291   Assembler::call(entry);
2292 }
2293 
2294 void MacroAssembler::call(AddressLiteral entry) {
2295   if (reachable(entry)) {
2296     Assembler::call_literal(entry.target(), entry.rspec());
2297   } else {
2298     lea(rscratch1, entry);
2299     Assembler::call(rscratch1);
2300   }
2301 }
2302 
2303 void MacroAssembler::ic_call(address entry, jint method_index) {
2304   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2305   movptr(rax, (intptr_t)Universe::non_oop_word());
2306   call(AddressLiteral(entry, rh));
2307 }
2308 
2309 // Implementation of call_VM versions
2310 
2311 void MacroAssembler::call_VM(Register oop_result,
2312                              address entry_point,
2313                              bool check_exceptions) {
2314   Label C, E;
2315   call(C, relocInfo::none);
2316   jmp(E);
2317 
2318   bind(C);
2319   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2320   ret(0);
2321 
2322   bind(E);
2323 }
2324 
2325 void MacroAssembler::call_VM(Register oop_result,
2326                              address entry_point,
2327                              Register arg_1,
2328                              bool check_exceptions) {
2329   Label C, E;
2330   call(C, relocInfo::none);
2331   jmp(E);
2332 
2333   bind(C);
2334   pass_arg1(this, arg_1);
2335   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2336   ret(0);
2337 
2338   bind(E);
2339 }
2340 
2341 void MacroAssembler::call_VM(Register oop_result,
2342                              address entry_point,
2343                              Register arg_1,
2344                              Register arg_2,
2345                              bool check_exceptions) {
2346   Label C, E;
2347   call(C, relocInfo::none);
2348   jmp(E);
2349 
2350   bind(C);
2351 
2352   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2353 
2354   pass_arg2(this, arg_2);
2355   pass_arg1(this, arg_1);
2356   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2357   ret(0);
2358 
2359   bind(E);
2360 }
2361 
2362 void MacroAssembler::call_VM(Register oop_result,
2363                              address entry_point,
2364                              Register arg_1,
2365                              Register arg_2,
2366                              Register arg_3,
2367                              bool check_exceptions) {
2368   Label C, E;
2369   call(C, relocInfo::none);
2370   jmp(E);
2371 
2372   bind(C);
2373 
2374   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2375   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2376   pass_arg3(this, arg_3);
2377 
2378   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2379   pass_arg2(this, arg_2);
2380 
2381   pass_arg1(this, arg_1);
2382   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2383   ret(0);
2384 
2385   bind(E);
2386 }
2387 
2388 void MacroAssembler::call_VM(Register oop_result,
2389                              Register last_java_sp,
2390                              address entry_point,
2391                              int number_of_arguments,
2392                              bool check_exceptions) {
2393   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2394   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2395 }
2396 
2397 void MacroAssembler::call_VM(Register oop_result,
2398                              Register last_java_sp,
2399                              address entry_point,
2400                              Register arg_1,
2401                              bool check_exceptions) {
2402   pass_arg1(this, arg_1);
2403   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2404 }
2405 
2406 void MacroAssembler::call_VM(Register oop_result,
2407                              Register last_java_sp,
2408                              address entry_point,
2409                              Register arg_1,
2410                              Register arg_2,
2411                              bool check_exceptions) {
2412 
2413   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2414   pass_arg2(this, arg_2);
2415   pass_arg1(this, arg_1);
2416   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2417 }
2418 
2419 void MacroAssembler::call_VM(Register oop_result,
2420                              Register last_java_sp,
2421                              address entry_point,
2422                              Register arg_1,
2423                              Register arg_2,
2424                              Register arg_3,
2425                              bool check_exceptions) {
2426   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2427   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2428   pass_arg3(this, arg_3);
2429   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2430   pass_arg2(this, arg_2);
2431   pass_arg1(this, arg_1);
2432   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2433 }
2434 
2435 void MacroAssembler::super_call_VM(Register oop_result,
2436                                    Register last_java_sp,
2437                                    address entry_point,
2438                                    int number_of_arguments,
2439                                    bool check_exceptions) {
2440   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2441   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2442 }
2443 
2444 void MacroAssembler::super_call_VM(Register oop_result,
2445                                    Register last_java_sp,
2446                                    address entry_point,
2447                                    Register arg_1,
2448                                    bool check_exceptions) {
2449   pass_arg1(this, arg_1);
2450   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2451 }
2452 
2453 void MacroAssembler::super_call_VM(Register oop_result,
2454                                    Register last_java_sp,
2455                                    address entry_point,
2456                                    Register arg_1,
2457                                    Register arg_2,
2458                                    bool check_exceptions) {
2459 
2460   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2461   pass_arg2(this, arg_2);
2462   pass_arg1(this, arg_1);
2463   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2464 }
2465 
2466 void MacroAssembler::super_call_VM(Register oop_result,
2467                                    Register last_java_sp,
2468                                    address entry_point,
2469                                    Register arg_1,
2470                                    Register arg_2,
2471                                    Register arg_3,
2472                                    bool check_exceptions) {
2473   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2474   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2475   pass_arg3(this, arg_3);
2476   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2477   pass_arg2(this, arg_2);
2478   pass_arg1(this, arg_1);
2479   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2480 }
2481 
2482 void MacroAssembler::call_VM_base(Register oop_result,
2483                                   Register java_thread,
2484                                   Register last_java_sp,
2485                                   address  entry_point,
2486                                   int      number_of_arguments,
2487                                   bool     check_exceptions) {
2488   // determine java_thread register
2489   if (!java_thread->is_valid()) {
2490 #ifdef _LP64
2491     java_thread = r15_thread;
2492 #else
2493     java_thread = rdi;
2494     get_thread(java_thread);
2495 #endif // LP64
2496   }
2497   // determine last_java_sp register
2498   if (!last_java_sp->is_valid()) {
2499     last_java_sp = rsp;
2500   }
2501   // debugging support
2502   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2503   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2504 #ifdef ASSERT
2505   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2506   // r12 is the heapbase.
2507   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2508 #endif // ASSERT
2509 
2510   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2511   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2512 
2513   // push java thread (becomes first argument of C function)
2514 
2515   NOT_LP64(push(java_thread); number_of_arguments++);
2516   LP64_ONLY(mov(c_rarg0, r15_thread));
2517 
2518   // set last Java frame before call
2519   assert(last_java_sp != rbp, "can't use ebp/rbp");
2520 
2521   // Only interpreter should have to set fp
2522   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2523 
2524   // do the call, remove parameters
2525   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2526 
2527   // restore the thread (cannot use the pushed argument since arguments
2528   // may be overwritten by C code generated by an optimizing compiler);
2529   // however can use the register value directly if it is callee saved.
2530   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2531     // rdi & rsi (also r15) are callee saved -> nothing to do
2532 #ifdef ASSERT
2533     guarantee(java_thread != rax, "change this code");
2534     push(rax);
2535     { Label L;
2536       get_thread(rax);
2537       cmpptr(java_thread, rax);
2538       jcc(Assembler::equal, L);
2539       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2540       bind(L);
2541     }
2542     pop(rax);
2543 #endif
2544   } else {
2545     get_thread(java_thread);
2546   }
2547   // reset last Java frame
2548   // Only interpreter should have to clear fp
2549   reset_last_Java_frame(java_thread, true);
2550 
2551    // C++ interp handles this in the interpreter
2552   check_and_handle_popframe(java_thread);
2553   check_and_handle_earlyret(java_thread);
2554 
2555   if (check_exceptions) {
2556     // check for pending exceptions (java_thread is set upon return)
2557     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2558 #ifndef _LP64
2559     jump_cc(Assembler::notEqual,
2560             RuntimeAddress(StubRoutines::forward_exception_entry()));
2561 #else
2562     // This used to conditionally jump to forward_exception however it is
2563     // possible if we relocate that the branch will not reach. So we must jump
2564     // around so we can always reach
2565 
2566     Label ok;
2567     jcc(Assembler::equal, ok);
2568     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2569     bind(ok);
2570 #endif // LP64
2571   }
2572 
2573   // get oop result if there is one and reset the value in the thread
2574   if (oop_result->is_valid()) {
2575     get_vm_result(oop_result, java_thread);
2576   }
2577 }
2578 
2579 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2580 
2581   // Calculate the value for last_Java_sp
2582   // somewhat subtle. call_VM does an intermediate call
2583   // which places a return address on the stack just under the
2584   // stack pointer as the user finsihed with it. This allows
2585   // use to retrieve last_Java_pc from last_Java_sp[-1].
2586   // On 32bit we then have to push additional args on the stack to accomplish
2587   // the actual requested call. On 64bit call_VM only can use register args
2588   // so the only extra space is the return address that call_VM created.
2589   // This hopefully explains the calculations here.
2590 
2591 #ifdef _LP64
2592   // We've pushed one address, correct last_Java_sp
2593   lea(rax, Address(rsp, wordSize));
2594 #else
2595   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2596 #endif // LP64
2597 
2598   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2599 
2600 }
2601 
2602 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2603 void MacroAssembler::call_VM_leaf0(address entry_point) {
2604   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2605 }
2606 
2607 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2608   call_VM_leaf_base(entry_point, number_of_arguments);
2609 }
2610 
2611 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2612   pass_arg0(this, arg_0);
2613   call_VM_leaf(entry_point, 1);
2614 }
2615 
2616 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2617 
2618   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2619   pass_arg1(this, arg_1);
2620   pass_arg0(this, arg_0);
2621   call_VM_leaf(entry_point, 2);
2622 }
2623 
2624 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2625   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2626   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2627   pass_arg2(this, arg_2);
2628   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2629   pass_arg1(this, arg_1);
2630   pass_arg0(this, arg_0);
2631   call_VM_leaf(entry_point, 3);
2632 }
2633 
2634 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2635   pass_arg0(this, arg_0);
2636   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2637 }
2638 
2639 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2640 
2641   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2642   pass_arg1(this, arg_1);
2643   pass_arg0(this, arg_0);
2644   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2645 }
2646 
2647 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2648   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2649   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2650   pass_arg2(this, arg_2);
2651   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2652   pass_arg1(this, arg_1);
2653   pass_arg0(this, arg_0);
2654   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2655 }
2656 
2657 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2658   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2659   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2660   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2661   pass_arg3(this, arg_3);
2662   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2663   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2664   pass_arg2(this, arg_2);
2665   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2666   pass_arg1(this, arg_1);
2667   pass_arg0(this, arg_0);
2668   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2669 }
2670 
2671 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2672   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2673   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2674   verify_oop(oop_result, "broken oop in call_VM_base");
2675 }
2676 
2677 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2678   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2679   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2680 }
2681 
2682 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2683 }
2684 
2685 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2686 }
2687 
2688 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2689   if (reachable(src1)) {
2690     cmpl(as_Address(src1), imm);
2691   } else {
2692     lea(rscratch1, src1);
2693     cmpl(Address(rscratch1, 0), imm);
2694   }
2695 }
2696 
2697 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2698   assert(!src2.is_lval(), "use cmpptr");
2699   if (reachable(src2)) {
2700     cmpl(src1, as_Address(src2));
2701   } else {
2702     lea(rscratch1, src2);
2703     cmpl(src1, Address(rscratch1, 0));
2704   }
2705 }
2706 
2707 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2708   Assembler::cmpl(src1, imm);
2709 }
2710 
2711 void MacroAssembler::cmp32(Register src1, Address src2) {
2712   Assembler::cmpl(src1, src2);
2713 }
2714 
2715 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2716   ucomisd(opr1, opr2);
2717 
2718   Label L;
2719   if (unordered_is_less) {
2720     movl(dst, -1);
2721     jcc(Assembler::parity, L);
2722     jcc(Assembler::below , L);
2723     movl(dst, 0);
2724     jcc(Assembler::equal , L);
2725     increment(dst);
2726   } else { // unordered is greater
2727     movl(dst, 1);
2728     jcc(Assembler::parity, L);
2729     jcc(Assembler::above , L);
2730     movl(dst, 0);
2731     jcc(Assembler::equal , L);
2732     decrementl(dst);
2733   }
2734   bind(L);
2735 }
2736 
2737 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2738   ucomiss(opr1, opr2);
2739 
2740   Label L;
2741   if (unordered_is_less) {
2742     movl(dst, -1);
2743     jcc(Assembler::parity, L);
2744     jcc(Assembler::below , L);
2745     movl(dst, 0);
2746     jcc(Assembler::equal , L);
2747     increment(dst);
2748   } else { // unordered is greater
2749     movl(dst, 1);
2750     jcc(Assembler::parity, L);
2751     jcc(Assembler::above , L);
2752     movl(dst, 0);
2753     jcc(Assembler::equal , L);
2754     decrementl(dst);
2755   }
2756   bind(L);
2757 }
2758 
2759 
2760 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2761   if (reachable(src1)) {
2762     cmpb(as_Address(src1), imm);
2763   } else {
2764     lea(rscratch1, src1);
2765     cmpb(Address(rscratch1, 0), imm);
2766   }
2767 }
2768 
2769 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2770 #ifdef _LP64
2771   if (src2.is_lval()) {
2772     movptr(rscratch1, src2);
2773     Assembler::cmpq(src1, rscratch1);
2774   } else if (reachable(src2)) {
2775     cmpq(src1, as_Address(src2));
2776   } else {
2777     lea(rscratch1, src2);
2778     Assembler::cmpq(src1, Address(rscratch1, 0));
2779   }
2780 #else
2781   if (src2.is_lval()) {
2782     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2783   } else {
2784     cmpl(src1, as_Address(src2));
2785   }
2786 #endif // _LP64
2787 }
2788 
2789 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2790   assert(src2.is_lval(), "not a mem-mem compare");
2791 #ifdef _LP64
2792   // moves src2's literal address
2793   movptr(rscratch1, src2);
2794   Assembler::cmpq(src1, rscratch1);
2795 #else
2796   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2797 #endif // _LP64
2798 }
2799 
2800 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2801   if (reachable(adr)) {
2802     if (os::is_MP())
2803       lock();
2804     cmpxchgptr(reg, as_Address(adr));
2805   } else {
2806     lea(rscratch1, adr);
2807     if (os::is_MP())
2808       lock();
2809     cmpxchgptr(reg, Address(rscratch1, 0));
2810   }
2811 }
2812 
2813 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2814   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2815 }
2816 
2817 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2818   if (reachable(src)) {
2819     Assembler::comisd(dst, as_Address(src));
2820   } else {
2821     lea(rscratch1, src);
2822     Assembler::comisd(dst, Address(rscratch1, 0));
2823   }
2824 }
2825 
2826 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2827   if (reachable(src)) {
2828     Assembler::comiss(dst, as_Address(src));
2829   } else {
2830     lea(rscratch1, src);
2831     Assembler::comiss(dst, Address(rscratch1, 0));
2832   }
2833 }
2834 
2835 
2836 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2837   Condition negated_cond = negate_condition(cond);
2838   Label L;
2839   jcc(negated_cond, L);
2840   pushf(); // Preserve flags
2841   atomic_incl(counter_addr);
2842   popf();
2843   bind(L);
2844 }
2845 
2846 int MacroAssembler::corrected_idivl(Register reg) {
2847   // Full implementation of Java idiv and irem; checks for
2848   // special case as described in JVM spec., p.243 & p.271.
2849   // The function returns the (pc) offset of the idivl
2850   // instruction - may be needed for implicit exceptions.
2851   //
2852   //         normal case                           special case
2853   //
2854   // input : rax,: dividend                         min_int
2855   //         reg: divisor   (may not be rax,/rdx)   -1
2856   //
2857   // output: rax,: quotient  (= rax, idiv reg)       min_int
2858   //         rdx: remainder (= rax, irem reg)       0
2859   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2860   const int min_int = 0x80000000;
2861   Label normal_case, special_case;
2862 
2863   // check for special case
2864   cmpl(rax, min_int);
2865   jcc(Assembler::notEqual, normal_case);
2866   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2867   cmpl(reg, -1);
2868   jcc(Assembler::equal, special_case);
2869 
2870   // handle normal case
2871   bind(normal_case);
2872   cdql();
2873   int idivl_offset = offset();
2874   idivl(reg);
2875 
2876   // normal and special case exit
2877   bind(special_case);
2878 
2879   return idivl_offset;
2880 }
2881 
2882 
2883 
2884 void MacroAssembler::decrementl(Register reg, int value) {
2885   if (value == min_jint) {subl(reg, value) ; return; }
2886   if (value <  0) { incrementl(reg, -value); return; }
2887   if (value == 0) {                        ; return; }
2888   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2889   /* else */      { subl(reg, value)       ; return; }
2890 }
2891 
2892 void MacroAssembler::decrementl(Address dst, int value) {
2893   if (value == min_jint) {subl(dst, value) ; return; }
2894   if (value <  0) { incrementl(dst, -value); return; }
2895   if (value == 0) {                        ; return; }
2896   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2897   /* else */      { subl(dst, value)       ; return; }
2898 }
2899 
2900 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2901   assert (shift_value > 0, "illegal shift value");
2902   Label _is_positive;
2903   testl (reg, reg);
2904   jcc (Assembler::positive, _is_positive);
2905   int offset = (1 << shift_value) - 1 ;
2906 
2907   if (offset == 1) {
2908     incrementl(reg);
2909   } else {
2910     addl(reg, offset);
2911   }
2912 
2913   bind (_is_positive);
2914   sarl(reg, shift_value);
2915 }
2916 
2917 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2918   if (reachable(src)) {
2919     Assembler::divsd(dst, as_Address(src));
2920   } else {
2921     lea(rscratch1, src);
2922     Assembler::divsd(dst, Address(rscratch1, 0));
2923   }
2924 }
2925 
2926 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2927   if (reachable(src)) {
2928     Assembler::divss(dst, as_Address(src));
2929   } else {
2930     lea(rscratch1, src);
2931     Assembler::divss(dst, Address(rscratch1, 0));
2932   }
2933 }
2934 
2935 // !defined(COMPILER2) is because of stupid core builds
2936 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2937 void MacroAssembler::empty_FPU_stack() {
2938   if (VM_Version::supports_mmx()) {
2939     emms();
2940   } else {
2941     for (int i = 8; i-- > 0; ) ffree(i);
2942   }
2943 }
2944 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2945 
2946 
2947 // Defines obj, preserves var_size_in_bytes
2948 void MacroAssembler::eden_allocate(Register obj,
2949                                    Register var_size_in_bytes,
2950                                    int con_size_in_bytes,
2951                                    Register t1,
2952                                    Label& slow_case) {
2953   assert(obj == rax, "obj must be in rax, for cmpxchg");
2954   assert_different_registers(obj, var_size_in_bytes, t1);
2955   if (!Universe::heap()->supports_inline_contig_alloc()) {
2956     jmp(slow_case);
2957   } else {
2958     Register end = t1;
2959     Label retry;
2960     bind(retry);
2961     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2962     movptr(obj, heap_top);
2963     if (var_size_in_bytes == noreg) {
2964       lea(end, Address(obj, con_size_in_bytes));
2965     } else {
2966       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2967     }
2968     // if end < obj then we wrapped around => object too long => slow case
2969     cmpptr(end, obj);
2970     jcc(Assembler::below, slow_case);
2971     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2972     jcc(Assembler::above, slow_case);
2973     // Compare obj with the top addr, and if still equal, store the new top addr in
2974     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2975     // it otherwise. Use lock prefix for atomicity on MPs.
2976     locked_cmpxchgptr(end, heap_top);
2977     jcc(Assembler::notEqual, retry);
2978   }
2979 }
2980 
2981 void MacroAssembler::enter() {
2982   push(rbp);
2983   mov(rbp, rsp);
2984 }
2985 
2986 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2987 void MacroAssembler::fat_nop() {
2988   if (UseAddressNop) {
2989     addr_nop_5();
2990   } else {
2991     emit_int8(0x26); // es:
2992     emit_int8(0x2e); // cs:
2993     emit_int8(0x64); // fs:
2994     emit_int8(0x65); // gs:
2995     emit_int8((unsigned char)0x90);
2996   }
2997 }
2998 
2999 void MacroAssembler::fcmp(Register tmp) {
3000   fcmp(tmp, 1, true, true);
3001 }
3002 
3003 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3004   assert(!pop_right || pop_left, "usage error");
3005   if (VM_Version::supports_cmov()) {
3006     assert(tmp == noreg, "unneeded temp");
3007     if (pop_left) {
3008       fucomip(index);
3009     } else {
3010       fucomi(index);
3011     }
3012     if (pop_right) {
3013       fpop();
3014     }
3015   } else {
3016     assert(tmp != noreg, "need temp");
3017     if (pop_left) {
3018       if (pop_right) {
3019         fcompp();
3020       } else {
3021         fcomp(index);
3022       }
3023     } else {
3024       fcom(index);
3025     }
3026     // convert FPU condition into eflags condition via rax,
3027     save_rax(tmp);
3028     fwait(); fnstsw_ax();
3029     sahf();
3030     restore_rax(tmp);
3031   }
3032   // condition codes set as follows:
3033   //
3034   // CF (corresponds to C0) if x < y
3035   // PF (corresponds to C2) if unordered
3036   // ZF (corresponds to C3) if x = y
3037 }
3038 
3039 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3040   fcmp2int(dst, unordered_is_less, 1, true, true);
3041 }
3042 
3043 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3044   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3045   Label L;
3046   if (unordered_is_less) {
3047     movl(dst, -1);
3048     jcc(Assembler::parity, L);
3049     jcc(Assembler::below , L);
3050     movl(dst, 0);
3051     jcc(Assembler::equal , L);
3052     increment(dst);
3053   } else { // unordered is greater
3054     movl(dst, 1);
3055     jcc(Assembler::parity, L);
3056     jcc(Assembler::above , L);
3057     movl(dst, 0);
3058     jcc(Assembler::equal , L);
3059     decrementl(dst);
3060   }
3061   bind(L);
3062 }
3063 
3064 void MacroAssembler::fld_d(AddressLiteral src) {
3065   fld_d(as_Address(src));
3066 }
3067 
3068 void MacroAssembler::fld_s(AddressLiteral src) {
3069   fld_s(as_Address(src));
3070 }
3071 
3072 void MacroAssembler::fld_x(AddressLiteral src) {
3073   Assembler::fld_x(as_Address(src));
3074 }
3075 
3076 void MacroAssembler::fldcw(AddressLiteral src) {
3077   Assembler::fldcw(as_Address(src));
3078 }
3079 
3080 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3081   if (reachable(src)) {
3082     Assembler::mulpd(dst, as_Address(src));
3083   } else {
3084     lea(rscratch1, src);
3085     Assembler::mulpd(dst, Address(rscratch1, 0));
3086   }
3087 }
3088 
3089 void MacroAssembler::increase_precision() {
3090   subptr(rsp, BytesPerWord);
3091   fnstcw(Address(rsp, 0));
3092   movl(rax, Address(rsp, 0));
3093   orl(rax, 0x300);
3094   push(rax);
3095   fldcw(Address(rsp, 0));
3096   pop(rax);
3097 }
3098 
3099 void MacroAssembler::restore_precision() {
3100   fldcw(Address(rsp, 0));
3101   addptr(rsp, BytesPerWord);
3102 }
3103 
3104 void MacroAssembler::fpop() {
3105   ffree();
3106   fincstp();
3107 }
3108 
3109 void MacroAssembler::load_float(Address src) {
3110   if (UseSSE >= 1) {
3111     movflt(xmm0, src);
3112   } else {
3113     LP64_ONLY(ShouldNotReachHere());
3114     NOT_LP64(fld_s(src));
3115   }
3116 }
3117 
3118 void MacroAssembler::store_float(Address dst) {
3119   if (UseSSE >= 1) {
3120     movflt(dst, xmm0);
3121   } else {
3122     LP64_ONLY(ShouldNotReachHere());
3123     NOT_LP64(fstp_s(dst));
3124   }
3125 }
3126 
3127 void MacroAssembler::load_double(Address src) {
3128   if (UseSSE >= 2) {
3129     movdbl(xmm0, src);
3130   } else {
3131     LP64_ONLY(ShouldNotReachHere());
3132     NOT_LP64(fld_d(src));
3133   }
3134 }
3135 
3136 void MacroAssembler::store_double(Address dst) {
3137   if (UseSSE >= 2) {
3138     movdbl(dst, xmm0);
3139   } else {
3140     LP64_ONLY(ShouldNotReachHere());
3141     NOT_LP64(fstp_d(dst));
3142   }
3143 }
3144 
3145 void MacroAssembler::fremr(Register tmp) {
3146   save_rax(tmp);
3147   { Label L;
3148     bind(L);
3149     fprem();
3150     fwait(); fnstsw_ax();
3151 #ifdef _LP64
3152     testl(rax, 0x400);
3153     jcc(Assembler::notEqual, L);
3154 #else
3155     sahf();
3156     jcc(Assembler::parity, L);
3157 #endif // _LP64
3158   }
3159   restore_rax(tmp);
3160   // Result is in ST0.
3161   // Note: fxch & fpop to get rid of ST1
3162   // (otherwise FPU stack could overflow eventually)
3163   fxch(1);
3164   fpop();
3165 }
3166 
3167 // dst = c = a * b + c
3168 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3169   Assembler::vfmadd231sd(c, a, b);
3170   if (dst != c) {
3171     movdbl(dst, c);
3172   }
3173 }
3174 
3175 // dst = c = a * b + c
3176 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3177   Assembler::vfmadd231ss(c, a, b);
3178   if (dst != c) {
3179     movflt(dst, c);
3180   }
3181 }
3182 
3183 // dst = c = a * b + c
3184 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3185   Assembler::vfmadd231pd(c, a, b, vector_len);
3186   if (dst != c) {
3187     vmovdqu(dst, c);
3188   }
3189 }
3190 
3191 // dst = c = a * b + c
3192 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3193   Assembler::vfmadd231ps(c, a, b, vector_len);
3194   if (dst != c) {
3195     vmovdqu(dst, c);
3196   }
3197 }
3198 
3199 // dst = c = a * b + c
3200 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3201   Assembler::vfmadd231pd(c, a, b, vector_len);
3202   if (dst != c) {
3203     vmovdqu(dst, c);
3204   }
3205 }
3206 
3207 // dst = c = a * b + c
3208 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3209   Assembler::vfmadd231ps(c, a, b, vector_len);
3210   if (dst != c) {
3211     vmovdqu(dst, c);
3212   }
3213 }
3214 
3215 void MacroAssembler::incrementl(AddressLiteral dst) {
3216   if (reachable(dst)) {
3217     incrementl(as_Address(dst));
3218   } else {
3219     lea(rscratch1, dst);
3220     incrementl(Address(rscratch1, 0));
3221   }
3222 }
3223 
3224 void MacroAssembler::incrementl(ArrayAddress dst) {
3225   incrementl(as_Address(dst));
3226 }
3227 
3228 void MacroAssembler::incrementl(Register reg, int value) {
3229   if (value == min_jint) {addl(reg, value) ; return; }
3230   if (value <  0) { decrementl(reg, -value); return; }
3231   if (value == 0) {                        ; return; }
3232   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3233   /* else */      { addl(reg, value)       ; return; }
3234 }
3235 
3236 void MacroAssembler::incrementl(Address dst, int value) {
3237   if (value == min_jint) {addl(dst, value) ; return; }
3238   if (value <  0) { decrementl(dst, -value); return; }
3239   if (value == 0) {                        ; return; }
3240   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3241   /* else */      { addl(dst, value)       ; return; }
3242 }
3243 
3244 void MacroAssembler::jump(AddressLiteral dst) {
3245   if (reachable(dst)) {
3246     jmp_literal(dst.target(), dst.rspec());
3247   } else {
3248     lea(rscratch1, dst);
3249     jmp(rscratch1);
3250   }
3251 }
3252 
3253 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3254   if (reachable(dst)) {
3255     InstructionMark im(this);
3256     relocate(dst.reloc());
3257     const int short_size = 2;
3258     const int long_size = 6;
3259     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3260     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3261       // 0111 tttn #8-bit disp
3262       emit_int8(0x70 | cc);
3263       emit_int8((offs - short_size) & 0xFF);
3264     } else {
3265       // 0000 1111 1000 tttn #32-bit disp
3266       emit_int8(0x0F);
3267       emit_int8((unsigned char)(0x80 | cc));
3268       emit_int32(offs - long_size);
3269     }
3270   } else {
3271 #ifdef ASSERT
3272     warning("reversing conditional branch");
3273 #endif /* ASSERT */
3274     Label skip;
3275     jccb(reverse[cc], skip);
3276     lea(rscratch1, dst);
3277     Assembler::jmp(rscratch1);
3278     bind(skip);
3279   }
3280 }
3281 
3282 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3283   if (reachable(src)) {
3284     Assembler::ldmxcsr(as_Address(src));
3285   } else {
3286     lea(rscratch1, src);
3287     Assembler::ldmxcsr(Address(rscratch1, 0));
3288   }
3289 }
3290 
3291 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3292   int off;
3293   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3294     off = offset();
3295     movsbl(dst, src); // movsxb
3296   } else {
3297     off = load_unsigned_byte(dst, src);
3298     shll(dst, 24);
3299     sarl(dst, 24);
3300   }
3301   return off;
3302 }
3303 
3304 // Note: load_signed_short used to be called load_signed_word.
3305 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3306 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3307 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3308 int MacroAssembler::load_signed_short(Register dst, Address src) {
3309   int off;
3310   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3311     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3312     // version but this is what 64bit has always done. This seems to imply
3313     // that users are only using 32bits worth.
3314     off = offset();
3315     movswl(dst, src); // movsxw
3316   } else {
3317     off = load_unsigned_short(dst, src);
3318     shll(dst, 16);
3319     sarl(dst, 16);
3320   }
3321   return off;
3322 }
3323 
3324 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3325   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3326   // and "3.9 Partial Register Penalties", p. 22).
3327   int off;
3328   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3329     off = offset();
3330     movzbl(dst, src); // movzxb
3331   } else {
3332     xorl(dst, dst);
3333     off = offset();
3334     movb(dst, src);
3335   }
3336   return off;
3337 }
3338 
3339 // Note: load_unsigned_short used to be called load_unsigned_word.
3340 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3341   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3342   // and "3.9 Partial Register Penalties", p. 22).
3343   int off;
3344   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3345     off = offset();
3346     movzwl(dst, src); // movzxw
3347   } else {
3348     xorl(dst, dst);
3349     off = offset();
3350     movw(dst, src);
3351   }
3352   return off;
3353 }
3354 
3355 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3356   switch (size_in_bytes) {
3357 #ifndef _LP64
3358   case  8:
3359     assert(dst2 != noreg, "second dest register required");
3360     movl(dst,  src);
3361     movl(dst2, src.plus_disp(BytesPerInt));
3362     break;
3363 #else
3364   case  8:  movq(dst, src); break;
3365 #endif
3366   case  4:  movl(dst, src); break;
3367   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3368   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3369   default:  ShouldNotReachHere();
3370   }
3371 }
3372 
3373 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3374   switch (size_in_bytes) {
3375 #ifndef _LP64
3376   case  8:
3377     assert(src2 != noreg, "second source register required");
3378     movl(dst,                        src);
3379     movl(dst.plus_disp(BytesPerInt), src2);
3380     break;
3381 #else
3382   case  8:  movq(dst, src); break;
3383 #endif
3384   case  4:  movl(dst, src); break;
3385   case  2:  movw(dst, src); break;
3386   case  1:  movb(dst, src); break;
3387   default:  ShouldNotReachHere();
3388   }
3389 }
3390 
3391 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3392   if (reachable(dst)) {
3393     movl(as_Address(dst), src);
3394   } else {
3395     lea(rscratch1, dst);
3396     movl(Address(rscratch1, 0), src);
3397   }
3398 }
3399 
3400 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3401   if (reachable(src)) {
3402     movl(dst, as_Address(src));
3403   } else {
3404     lea(rscratch1, src);
3405     movl(dst, Address(rscratch1, 0));
3406   }
3407 }
3408 
3409 // C++ bool manipulation
3410 
3411 void MacroAssembler::movbool(Register dst, Address src) {
3412   if(sizeof(bool) == 1)
3413     movb(dst, src);
3414   else if(sizeof(bool) == 2)
3415     movw(dst, src);
3416   else if(sizeof(bool) == 4)
3417     movl(dst, src);
3418   else
3419     // unsupported
3420     ShouldNotReachHere();
3421 }
3422 
3423 void MacroAssembler::movbool(Address dst, bool boolconst) {
3424   if(sizeof(bool) == 1)
3425     movb(dst, (int) boolconst);
3426   else if(sizeof(bool) == 2)
3427     movw(dst, (int) boolconst);
3428   else if(sizeof(bool) == 4)
3429     movl(dst, (int) boolconst);
3430   else
3431     // unsupported
3432     ShouldNotReachHere();
3433 }
3434 
3435 void MacroAssembler::movbool(Address dst, Register src) {
3436   if(sizeof(bool) == 1)
3437     movb(dst, src);
3438   else if(sizeof(bool) == 2)
3439     movw(dst, src);
3440   else if(sizeof(bool) == 4)
3441     movl(dst, src);
3442   else
3443     // unsupported
3444     ShouldNotReachHere();
3445 }
3446 
3447 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3448   movb(as_Address(dst), src);
3449 }
3450 
3451 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3452   if (reachable(src)) {
3453     movdl(dst, as_Address(src));
3454   } else {
3455     lea(rscratch1, src);
3456     movdl(dst, Address(rscratch1, 0));
3457   }
3458 }
3459 
3460 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3461   if (reachable(src)) {
3462     movq(dst, as_Address(src));
3463   } else {
3464     lea(rscratch1, src);
3465     movq(dst, Address(rscratch1, 0));
3466   }
3467 }
3468 
3469 void MacroAssembler::setvectmask(Register dst, Register src) {
3470   Assembler::movl(dst, 1);
3471   Assembler::shlxl(dst, dst, src);
3472   Assembler::decl(dst);
3473   Assembler::kmovdl(k1, dst);
3474   Assembler::movl(dst, src);
3475 }
3476 
3477 void MacroAssembler::restorevectmask() {
3478   Assembler::knotwl(k1, k0);
3479 }
3480 
3481 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3482   if (reachable(src)) {
3483     if (UseXmmLoadAndClearUpper) {
3484       movsd (dst, as_Address(src));
3485     } else {
3486       movlpd(dst, as_Address(src));
3487     }
3488   } else {
3489     lea(rscratch1, src);
3490     if (UseXmmLoadAndClearUpper) {
3491       movsd (dst, Address(rscratch1, 0));
3492     } else {
3493       movlpd(dst, Address(rscratch1, 0));
3494     }
3495   }
3496 }
3497 
3498 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3499   if (reachable(src)) {
3500     movss(dst, as_Address(src));
3501   } else {
3502     lea(rscratch1, src);
3503     movss(dst, Address(rscratch1, 0));
3504   }
3505 }
3506 
3507 void MacroAssembler::movptr(Register dst, Register src) {
3508   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3509 }
3510 
3511 void MacroAssembler::movptr(Register dst, Address src) {
3512   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3513 }
3514 
3515 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3516 void MacroAssembler::movptr(Register dst, intptr_t src) {
3517   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3518 }
3519 
3520 void MacroAssembler::movptr(Address dst, Register src) {
3521   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3522 }
3523 
3524 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3525   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3526     Assembler::vextractf32x4(dst, src, 0);
3527   } else {
3528     Assembler::movdqu(dst, src);
3529   }
3530 }
3531 
3532 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3533   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3534     Assembler::vinsertf32x4(dst, dst, src, 0);
3535   } else {
3536     Assembler::movdqu(dst, src);
3537   }
3538 }
3539 
3540 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3541   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3542     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3543   } else {
3544     Assembler::movdqu(dst, src);
3545   }
3546 }
3547 
3548 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3549   if (reachable(src)) {
3550     movdqu(dst, as_Address(src));
3551   } else {
3552     lea(scratchReg, src);
3553     movdqu(dst, Address(scratchReg, 0));
3554   }
3555 }
3556 
3557 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3558   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3559     vextractf64x4_low(dst, src);
3560   } else {
3561     Assembler::vmovdqu(dst, src);
3562   }
3563 }
3564 
3565 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3566   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3567     vinsertf64x4_low(dst, src);
3568   } else {
3569     Assembler::vmovdqu(dst, src);
3570   }
3571 }
3572 
3573 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3574   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3575     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3576   }
3577   else {
3578     Assembler::vmovdqu(dst, src);
3579   }
3580 }
3581 
3582 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3583   if (reachable(src)) {
3584     vmovdqu(dst, as_Address(src));
3585   }
3586   else {
3587     lea(rscratch1, src);
3588     vmovdqu(dst, Address(rscratch1, 0));
3589   }
3590 }
3591 
3592 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3593   if (reachable(src)) {
3594     Assembler::movdqa(dst, as_Address(src));
3595   } else {
3596     lea(rscratch1, src);
3597     Assembler::movdqa(dst, Address(rscratch1, 0));
3598   }
3599 }
3600 
3601 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3602   if (reachable(src)) {
3603     Assembler::movsd(dst, as_Address(src));
3604   } else {
3605     lea(rscratch1, src);
3606     Assembler::movsd(dst, Address(rscratch1, 0));
3607   }
3608 }
3609 
3610 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3611   if (reachable(src)) {
3612     Assembler::movss(dst, as_Address(src));
3613   } else {
3614     lea(rscratch1, src);
3615     Assembler::movss(dst, Address(rscratch1, 0));
3616   }
3617 }
3618 
3619 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3620   if (reachable(src)) {
3621     Assembler::mulsd(dst, as_Address(src));
3622   } else {
3623     lea(rscratch1, src);
3624     Assembler::mulsd(dst, Address(rscratch1, 0));
3625   }
3626 }
3627 
3628 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3629   if (reachable(src)) {
3630     Assembler::mulss(dst, as_Address(src));
3631   } else {
3632     lea(rscratch1, src);
3633     Assembler::mulss(dst, Address(rscratch1, 0));
3634   }
3635 }
3636 
3637 void MacroAssembler::null_check(Register reg, int offset) {
3638   if (needs_explicit_null_check(offset)) {
3639     // provoke OS NULL exception if reg = NULL by
3640     // accessing M[reg] w/o changing any (non-CC) registers
3641     // NOTE: cmpl is plenty here to provoke a segv
3642     cmpptr(rax, Address(reg, 0));
3643     // Note: should probably use testl(rax, Address(reg, 0));
3644     //       may be shorter code (however, this version of
3645     //       testl needs to be implemented first)
3646   } else {
3647     // nothing to do, (later) access of M[reg + offset]
3648     // will provoke OS NULL exception if reg = NULL
3649   }
3650 }
3651 
3652 void MacroAssembler::os_breakpoint() {
3653   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3654   // (e.g., MSVC can't call ps() otherwise)
3655   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3656 }
3657 
3658 void MacroAssembler::unimplemented(const char* what) {
3659   char* b = new char[1024];
3660   jio_snprintf(b, 1024, "unimplemented: %s", what);
3661   stop(b);
3662 }
3663 
3664 #ifdef _LP64
3665 #define XSTATE_BV 0x200
3666 #endif
3667 
3668 void MacroAssembler::pop_CPU_state() {
3669   pop_FPU_state();
3670   pop_IU_state();
3671 }
3672 
3673 void MacroAssembler::pop_FPU_state() {
3674 #ifndef _LP64
3675   frstor(Address(rsp, 0));
3676 #else
3677   fxrstor(Address(rsp, 0));
3678 #endif
3679   addptr(rsp, FPUStateSizeInWords * wordSize);
3680 }
3681 
3682 void MacroAssembler::pop_IU_state() {
3683   popa();
3684   LP64_ONLY(addq(rsp, 8));
3685   popf();
3686 }
3687 
3688 // Save Integer and Float state
3689 // Warning: Stack must be 16 byte aligned (64bit)
3690 void MacroAssembler::push_CPU_state() {
3691   push_IU_state();
3692   push_FPU_state();
3693 }
3694 
3695 void MacroAssembler::push_FPU_state() {
3696   subptr(rsp, FPUStateSizeInWords * wordSize);
3697 #ifndef _LP64
3698   fnsave(Address(rsp, 0));
3699   fwait();
3700 #else
3701   fxsave(Address(rsp, 0));
3702 #endif // LP64
3703 }
3704 
3705 void MacroAssembler::push_IU_state() {
3706   // Push flags first because pusha kills them
3707   pushf();
3708   // Make sure rsp stays 16-byte aligned
3709   LP64_ONLY(subq(rsp, 8));
3710   pusha();
3711 }
3712 
3713 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3714   if (!java_thread->is_valid()) {
3715     java_thread = rdi;
3716     get_thread(java_thread);
3717   }
3718   // we must set sp to zero to clear frame
3719   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3720   if (clear_fp) {
3721     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3722   }
3723 
3724   // Always clear the pc because it could have been set by make_walkable()
3725   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3726 
3727   vzeroupper();
3728 }
3729 
3730 void MacroAssembler::restore_rax(Register tmp) {
3731   if (tmp == noreg) pop(rax);
3732   else if (tmp != rax) mov(rax, tmp);
3733 }
3734 
3735 void MacroAssembler::round_to(Register reg, int modulus) {
3736   addptr(reg, modulus - 1);
3737   andptr(reg, -modulus);
3738 }
3739 
3740 void MacroAssembler::save_rax(Register tmp) {
3741   if (tmp == noreg) push(rax);
3742   else if (tmp != rax) mov(tmp, rax);
3743 }
3744 
3745 // Write serialization page so VM thread can do a pseudo remote membar.
3746 // We use the current thread pointer to calculate a thread specific
3747 // offset to write to within the page. This minimizes bus traffic
3748 // due to cache line collision.
3749 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3750   movl(tmp, thread);
3751   shrl(tmp, os::get_serialize_page_shift_count());
3752   andl(tmp, (os::vm_page_size() - sizeof(int)));
3753 
3754   Address index(noreg, tmp, Address::times_1);
3755   ExternalAddress page(os::get_memory_serialize_page());
3756 
3757   // Size of store must match masking code above
3758   movl(as_Address(ArrayAddress(page, index)), tmp);
3759 }
3760 
3761 // Special Shenandoah CAS implementation that handles false negatives
3762 // due to concurrent evacuation.
3763 #ifndef _LP64
3764 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3765                               bool exchange,
3766                               Register tmp1, Register tmp2) {
3767   // Shenandoah has no 32-bit version for this.
3768   Unimplemented();
3769 }
3770 #else
3771 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3772                               bool exchange,
3773                               Register tmp1, Register tmp2) {
3774   assert(UseShenandoahGC, "Should only be used with Shenandoah");
3775   assert(ShenandoahCASBarrier, "Should only be used when CAS barrier is enabled");
3776   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
3777 
3778   Label retry, done;
3779 
3780   // Remember oldval for retry logic below
3781   if (UseCompressedOops) {
3782     movl(tmp1, oldval);
3783   } else {
3784     movptr(tmp1, oldval);
3785   }
3786 
3787   // Step 1. Try to CAS with given arguments. If successful, then we are done,
3788   // and can safely return.
3789   if (os::is_MP()) lock();
3790   if (UseCompressedOops) {
3791     cmpxchgl(newval, addr);
3792   } else {
3793     cmpxchgptr(newval, addr);
3794   }
3795   jcc(Assembler::equal, done, true);
3796 
3797   // Step 2. CAS had failed. This may be a false negative.
3798   //
3799   // The trouble comes when we compare the to-space pointer with the from-space
3800   // pointer to the same object. To resolve this, it will suffice to read both
3801   // oldval and the value from memory through the read barriers -- this will give
3802   // both to-space pointers. If they mismatch, then it was a legitimate failure.
3803   //
3804   if (UseCompressedOops) {
3805     decode_heap_oop(tmp1);
3806   }
3807   oopDesc::bs()->interpreter_read_barrier(this, tmp1);
3808 
3809   if (UseCompressedOops) {
3810     movl(tmp2, oldval);
3811     decode_heap_oop(tmp2);
3812   } else {
3813     movptr(tmp2, oldval);
3814   }
3815   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3816 
3817   cmpptr(tmp1, tmp2);
3818   jcc(Assembler::notEqual, done, true);
3819 
3820   // Step 3. Try to CAS again with resolved to-space pointers.
3821   //
3822   // Corner case: it may happen that somebody stored the from-space pointer
3823   // to memory while we were preparing for retry. Therefore, we can fail again
3824   // on retry, and so need to do this in loop, always re-reading the failure
3825   // witness through the read barrier.
3826   bind(retry);
3827   if (os::is_MP()) lock();
3828   if (UseCompressedOops) {
3829     cmpxchgl(newval, addr);
3830   } else {
3831     cmpxchgptr(newval, addr);
3832   }
3833   jcc(Assembler::equal, done, true);
3834 
3835   if (UseCompressedOops) {
3836     movl(tmp2, oldval);
3837     decode_heap_oop(tmp2);
3838   } else {
3839     movptr(tmp2, oldval);
3840   }
3841   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3842 
3843   cmpptr(tmp1, tmp2);
3844   jcc(Assembler::equal, retry, true);
3845 
3846   // Step 4. If we need a boolean result out of CAS, check the flag again,
3847   // and promote the result. Note that we handle the flag from both the CAS
3848   // itself and from the retry loop.
3849   bind(done);
3850   if (!exchange) {
3851     setb(Assembler::equal, res);
3852     movzbl(res, res);
3853   }
3854 }
3855 #endif
3856 
3857 // Calls to C land
3858 //
3859 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3860 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3861 // has to be reset to 0. This is required to allow proper stack traversal.
3862 void MacroAssembler::set_last_Java_frame(Register java_thread,
3863                                          Register last_java_sp,
3864                                          Register last_java_fp,
3865                                          address  last_java_pc) {
3866   vzeroupper();
3867   // determine java_thread register
3868   if (!java_thread->is_valid()) {
3869     java_thread = rdi;
3870     get_thread(java_thread);
3871   }
3872   // determine last_java_sp register
3873   if (!last_java_sp->is_valid()) {
3874     last_java_sp = rsp;
3875   }
3876 
3877   // last_java_fp is optional
3878 
3879   if (last_java_fp->is_valid()) {
3880     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3881   }
3882 
3883   // last_java_pc is optional
3884 
3885   if (last_java_pc != NULL) {
3886     lea(Address(java_thread,
3887                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3888         InternalAddress(last_java_pc));
3889 
3890   }
3891   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3892 }
3893 
3894 void MacroAssembler::shlptr(Register dst, int imm8) {
3895   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3896 }
3897 
3898 void MacroAssembler::shrptr(Register dst, int imm8) {
3899   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3900 }
3901 
3902 void MacroAssembler::sign_extend_byte(Register reg) {
3903   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3904     movsbl(reg, reg); // movsxb
3905   } else {
3906     shll(reg, 24);
3907     sarl(reg, 24);
3908   }
3909 }
3910 
3911 void MacroAssembler::sign_extend_short(Register reg) {
3912   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3913     movswl(reg, reg); // movsxw
3914   } else {
3915     shll(reg, 16);
3916     sarl(reg, 16);
3917   }
3918 }
3919 
3920 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3921   assert(reachable(src), "Address should be reachable");
3922   testl(dst, as_Address(src));
3923 }
3924 
3925 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3926   int dst_enc = dst->encoding();
3927   int src_enc = src->encoding();
3928   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3929     Assembler::pcmpeqb(dst, src);
3930   } else if ((dst_enc < 16) && (src_enc < 16)) {
3931     Assembler::pcmpeqb(dst, src);
3932   } else if (src_enc < 16) {
3933     subptr(rsp, 64);
3934     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3935     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3936     Assembler::pcmpeqb(xmm0, src);
3937     movdqu(dst, xmm0);
3938     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3939     addptr(rsp, 64);
3940   } else if (dst_enc < 16) {
3941     subptr(rsp, 64);
3942     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3943     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3944     Assembler::pcmpeqb(dst, xmm0);
3945     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3946     addptr(rsp, 64);
3947   } else {
3948     subptr(rsp, 64);
3949     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3950     subptr(rsp, 64);
3951     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3952     movdqu(xmm0, src);
3953     movdqu(xmm1, dst);
3954     Assembler::pcmpeqb(xmm1, xmm0);
3955     movdqu(dst, xmm1);
3956     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3957     addptr(rsp, 64);
3958     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3959     addptr(rsp, 64);
3960   }
3961 }
3962 
3963 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3964   int dst_enc = dst->encoding();
3965   int src_enc = src->encoding();
3966   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3967     Assembler::pcmpeqw(dst, src);
3968   } else if ((dst_enc < 16) && (src_enc < 16)) {
3969     Assembler::pcmpeqw(dst, src);
3970   } else if (src_enc < 16) {
3971     subptr(rsp, 64);
3972     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3973     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3974     Assembler::pcmpeqw(xmm0, src);
3975     movdqu(dst, xmm0);
3976     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3977     addptr(rsp, 64);
3978   } else if (dst_enc < 16) {
3979     subptr(rsp, 64);
3980     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3981     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3982     Assembler::pcmpeqw(dst, xmm0);
3983     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985   } else {
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3988     subptr(rsp, 64);
3989     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3990     movdqu(xmm0, src);
3991     movdqu(xmm1, dst);
3992     Assembler::pcmpeqw(xmm1, xmm0);
3993     movdqu(dst, xmm1);
3994     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3995     addptr(rsp, 64);
3996     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3997     addptr(rsp, 64);
3998   }
3999 }
4000 
4001 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
4002   int dst_enc = dst->encoding();
4003   if (dst_enc < 16) {
4004     Assembler::pcmpestri(dst, src, imm8);
4005   } else {
4006     subptr(rsp, 64);
4007     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4008     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4009     Assembler::pcmpestri(xmm0, src, imm8);
4010     movdqu(dst, xmm0);
4011     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4012     addptr(rsp, 64);
4013   }
4014 }
4015 
4016 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
4017   int dst_enc = dst->encoding();
4018   int src_enc = src->encoding();
4019   if ((dst_enc < 16) && (src_enc < 16)) {
4020     Assembler::pcmpestri(dst, src, imm8);
4021   } else if (src_enc < 16) {
4022     subptr(rsp, 64);
4023     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4024     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4025     Assembler::pcmpestri(xmm0, src, imm8);
4026     movdqu(dst, xmm0);
4027     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4028     addptr(rsp, 64);
4029   } else if (dst_enc < 16) {
4030     subptr(rsp, 64);
4031     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4032     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4033     Assembler::pcmpestri(dst, xmm0, imm8);
4034     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4035     addptr(rsp, 64);
4036   } else {
4037     subptr(rsp, 64);
4038     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4039     subptr(rsp, 64);
4040     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4041     movdqu(xmm0, src);
4042     movdqu(xmm1, dst);
4043     Assembler::pcmpestri(xmm1, xmm0, imm8);
4044     movdqu(dst, xmm1);
4045     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4046     addptr(rsp, 64);
4047     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4048     addptr(rsp, 64);
4049   }
4050 }
4051 
4052 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4053   int dst_enc = dst->encoding();
4054   int src_enc = src->encoding();
4055   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4056     Assembler::pmovzxbw(dst, src);
4057   } else if ((dst_enc < 16) && (src_enc < 16)) {
4058     Assembler::pmovzxbw(dst, src);
4059   } else if (src_enc < 16) {
4060     subptr(rsp, 64);
4061     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4062     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4063     Assembler::pmovzxbw(xmm0, src);
4064     movdqu(dst, xmm0);
4065     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4066     addptr(rsp, 64);
4067   } else if (dst_enc < 16) {
4068     subptr(rsp, 64);
4069     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4070     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4071     Assembler::pmovzxbw(dst, xmm0);
4072     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4073     addptr(rsp, 64);
4074   } else {
4075     subptr(rsp, 64);
4076     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4077     subptr(rsp, 64);
4078     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4079     movdqu(xmm0, src);
4080     movdqu(xmm1, dst);
4081     Assembler::pmovzxbw(xmm1, xmm0);
4082     movdqu(dst, xmm1);
4083     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4084     addptr(rsp, 64);
4085     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4086     addptr(rsp, 64);
4087   }
4088 }
4089 
4090 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4091   int dst_enc = dst->encoding();
4092   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4093     Assembler::pmovzxbw(dst, src);
4094   } else if (dst_enc < 16) {
4095     Assembler::pmovzxbw(dst, src);
4096   } else {
4097     subptr(rsp, 64);
4098     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4099     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4100     Assembler::pmovzxbw(xmm0, src);
4101     movdqu(dst, xmm0);
4102     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4103     addptr(rsp, 64);
4104   }
4105 }
4106 
4107 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4108   int src_enc = src->encoding();
4109   if (src_enc < 16) {
4110     Assembler::pmovmskb(dst, src);
4111   } else {
4112     subptr(rsp, 64);
4113     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4114     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4115     Assembler::pmovmskb(dst, xmm0);
4116     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4117     addptr(rsp, 64);
4118   }
4119 }
4120 
4121 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4122   int dst_enc = dst->encoding();
4123   int src_enc = src->encoding();
4124   if ((dst_enc < 16) && (src_enc < 16)) {
4125     Assembler::ptest(dst, src);
4126   } else if (src_enc < 16) {
4127     subptr(rsp, 64);
4128     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4129     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4130     Assembler::ptest(xmm0, src);
4131     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4132     addptr(rsp, 64);
4133   } else if (dst_enc < 16) {
4134     subptr(rsp, 64);
4135     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4136     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4137     Assembler::ptest(dst, xmm0);
4138     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4139     addptr(rsp, 64);
4140   } else {
4141     subptr(rsp, 64);
4142     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4143     subptr(rsp, 64);
4144     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4145     movdqu(xmm0, src);
4146     movdqu(xmm1, dst);
4147     Assembler::ptest(xmm1, xmm0);
4148     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4149     addptr(rsp, 64);
4150     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4151     addptr(rsp, 64);
4152   }
4153 }
4154 
4155 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4156   if (reachable(src)) {
4157     Assembler::sqrtsd(dst, as_Address(src));
4158   } else {
4159     lea(rscratch1, src);
4160     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4161   }
4162 }
4163 
4164 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4165   if (reachable(src)) {
4166     Assembler::sqrtss(dst, as_Address(src));
4167   } else {
4168     lea(rscratch1, src);
4169     Assembler::sqrtss(dst, Address(rscratch1, 0));
4170   }
4171 }
4172 
4173 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4174   if (reachable(src)) {
4175     Assembler::subsd(dst, as_Address(src));
4176   } else {
4177     lea(rscratch1, src);
4178     Assembler::subsd(dst, Address(rscratch1, 0));
4179   }
4180 }
4181 
4182 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4183   if (reachable(src)) {
4184     Assembler::subss(dst, as_Address(src));
4185   } else {
4186     lea(rscratch1, src);
4187     Assembler::subss(dst, Address(rscratch1, 0));
4188   }
4189 }
4190 
4191 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4192   if (reachable(src)) {
4193     Assembler::ucomisd(dst, as_Address(src));
4194   } else {
4195     lea(rscratch1, src);
4196     Assembler::ucomisd(dst, Address(rscratch1, 0));
4197   }
4198 }
4199 
4200 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4201   if (reachable(src)) {
4202     Assembler::ucomiss(dst, as_Address(src));
4203   } else {
4204     lea(rscratch1, src);
4205     Assembler::ucomiss(dst, Address(rscratch1, 0));
4206   }
4207 }
4208 
4209 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4210   // Used in sign-bit flipping with aligned address.
4211   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4212   if (reachable(src)) {
4213     Assembler::xorpd(dst, as_Address(src));
4214   } else {
4215     lea(rscratch1, src);
4216     Assembler::xorpd(dst, Address(rscratch1, 0));
4217   }
4218 }
4219 
4220 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4221   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4222     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4223   }
4224   else {
4225     Assembler::xorpd(dst, src);
4226   }
4227 }
4228 
4229 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4230   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4231     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4232   } else {
4233     Assembler::xorps(dst, src);
4234   }
4235 }
4236 
4237 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4238   // Used in sign-bit flipping with aligned address.
4239   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4240   if (reachable(src)) {
4241     Assembler::xorps(dst, as_Address(src));
4242   } else {
4243     lea(rscratch1, src);
4244     Assembler::xorps(dst, Address(rscratch1, 0));
4245   }
4246 }
4247 
4248 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4249   // Used in sign-bit flipping with aligned address.
4250   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4251   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4252   if (reachable(src)) {
4253     Assembler::pshufb(dst, as_Address(src));
4254   } else {
4255     lea(rscratch1, src);
4256     Assembler::pshufb(dst, Address(rscratch1, 0));
4257   }
4258 }
4259 
4260 // AVX 3-operands instructions
4261 
4262 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4263   if (reachable(src)) {
4264     vaddsd(dst, nds, as_Address(src));
4265   } else {
4266     lea(rscratch1, src);
4267     vaddsd(dst, nds, Address(rscratch1, 0));
4268   }
4269 }
4270 
4271 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4272   if (reachable(src)) {
4273     vaddss(dst, nds, as_Address(src));
4274   } else {
4275     lea(rscratch1, src);
4276     vaddss(dst, nds, Address(rscratch1, 0));
4277   }
4278 }
4279 
4280 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4281   int dst_enc = dst->encoding();
4282   int nds_enc = nds->encoding();
4283   int src_enc = src->encoding();
4284   if ((dst_enc < 16) && (nds_enc < 16)) {
4285     vandps(dst, nds, negate_field, vector_len);
4286   } else if ((src_enc < 16) && (dst_enc < 16)) {
4287     evmovdqul(src, nds, Assembler::AVX_512bit);
4288     vandps(dst, src, negate_field, vector_len);
4289   } else if (src_enc < 16) {
4290     evmovdqul(src, nds, Assembler::AVX_512bit);
4291     vandps(src, src, negate_field, vector_len);
4292     evmovdqul(dst, src, Assembler::AVX_512bit);
4293   } else if (dst_enc < 16) {
4294     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4295     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4296     vandps(dst, xmm0, negate_field, vector_len);
4297     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4298   } else {
4299     if (src_enc != dst_enc) {
4300       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4301       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4302       vandps(xmm0, xmm0, negate_field, vector_len);
4303       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4304       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4305     } else {
4306       subptr(rsp, 64);
4307       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4308       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4309       vandps(xmm0, xmm0, negate_field, vector_len);
4310       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4311       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4312       addptr(rsp, 64);
4313     }
4314   }
4315 }
4316 
4317 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4318   int dst_enc = dst->encoding();
4319   int nds_enc = nds->encoding();
4320   int src_enc = src->encoding();
4321   if ((dst_enc < 16) && (nds_enc < 16)) {
4322     vandpd(dst, nds, negate_field, vector_len);
4323   } else if ((src_enc < 16) && (dst_enc < 16)) {
4324     evmovdqul(src, nds, Assembler::AVX_512bit);
4325     vandpd(dst, src, negate_field, vector_len);
4326   } else if (src_enc < 16) {
4327     evmovdqul(src, nds, Assembler::AVX_512bit);
4328     vandpd(src, src, negate_field, vector_len);
4329     evmovdqul(dst, src, Assembler::AVX_512bit);
4330   } else if (dst_enc < 16) {
4331     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4332     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4333     vandpd(dst, xmm0, negate_field, vector_len);
4334     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4335   } else {
4336     if (src_enc != dst_enc) {
4337       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4338       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4339       vandpd(xmm0, xmm0, negate_field, vector_len);
4340       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4341       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4342     } else {
4343       subptr(rsp, 64);
4344       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4345       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4346       vandpd(xmm0, xmm0, negate_field, vector_len);
4347       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4348       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4349       addptr(rsp, 64);
4350     }
4351   }
4352 }
4353 
4354 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4355   int dst_enc = dst->encoding();
4356   int nds_enc = nds->encoding();
4357   int src_enc = src->encoding();
4358   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4359     Assembler::vpaddb(dst, nds, src, vector_len);
4360   } else if ((dst_enc < 16) && (src_enc < 16)) {
4361     Assembler::vpaddb(dst, dst, src, vector_len);
4362   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4363     // use nds as scratch for src
4364     evmovdqul(nds, src, Assembler::AVX_512bit);
4365     Assembler::vpaddb(dst, dst, nds, vector_len);
4366   } else if ((src_enc < 16) && (nds_enc < 16)) {
4367     // use nds as scratch for dst
4368     evmovdqul(nds, dst, Assembler::AVX_512bit);
4369     Assembler::vpaddb(nds, nds, src, vector_len);
4370     evmovdqul(dst, nds, Assembler::AVX_512bit);
4371   } else if (dst_enc < 16) {
4372     // use nds as scatch for xmm0 to hold src
4373     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4374     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4375     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4376     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4377   } else {
4378     // worse case scenario, all regs are in the upper bank
4379     subptr(rsp, 64);
4380     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4381     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4382     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4383     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4384     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4385     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4386     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4387     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4388     addptr(rsp, 64);
4389   }
4390 }
4391 
4392 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4393   int dst_enc = dst->encoding();
4394   int nds_enc = nds->encoding();
4395   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4396     Assembler::vpaddb(dst, nds, src, vector_len);
4397   } else if (dst_enc < 16) {
4398     Assembler::vpaddb(dst, dst, src, vector_len);
4399   } else if (nds_enc < 16) {
4400     // implies dst_enc in upper bank with src as scratch
4401     evmovdqul(nds, dst, Assembler::AVX_512bit);
4402     Assembler::vpaddb(nds, nds, src, vector_len);
4403     evmovdqul(dst, nds, Assembler::AVX_512bit);
4404   } else {
4405     // worse case scenario, all regs in upper bank
4406     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4407     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4408     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4409     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4410   }
4411 }
4412 
4413 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4414   int dst_enc = dst->encoding();
4415   int nds_enc = nds->encoding();
4416   int src_enc = src->encoding();
4417   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4418     Assembler::vpaddw(dst, nds, src, vector_len);
4419   } else if ((dst_enc < 16) && (src_enc < 16)) {
4420     Assembler::vpaddw(dst, dst, src, vector_len);
4421   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4422     // use nds as scratch for src
4423     evmovdqul(nds, src, Assembler::AVX_512bit);
4424     Assembler::vpaddw(dst, dst, nds, vector_len);
4425   } else if ((src_enc < 16) && (nds_enc < 16)) {
4426     // use nds as scratch for dst
4427     evmovdqul(nds, dst, Assembler::AVX_512bit);
4428     Assembler::vpaddw(nds, nds, src, vector_len);
4429     evmovdqul(dst, nds, Assembler::AVX_512bit);
4430   } else if (dst_enc < 16) {
4431     // use nds as scatch for xmm0 to hold src
4432     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4433     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4434     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4435     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4436   } else {
4437     // worse case scenario, all regs are in the upper bank
4438     subptr(rsp, 64);
4439     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4440     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4441     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4442     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4443     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4444     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4445     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4446     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4447     addptr(rsp, 64);
4448   }
4449 }
4450 
4451 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4452   int dst_enc = dst->encoding();
4453   int nds_enc = nds->encoding();
4454   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4455     Assembler::vpaddw(dst, nds, src, vector_len);
4456   } else if (dst_enc < 16) {
4457     Assembler::vpaddw(dst, dst, src, vector_len);
4458   } else if (nds_enc < 16) {
4459     // implies dst_enc in upper bank with src as scratch
4460     evmovdqul(nds, dst, Assembler::AVX_512bit);
4461     Assembler::vpaddw(nds, nds, src, vector_len);
4462     evmovdqul(dst, nds, Assembler::AVX_512bit);
4463   } else {
4464     // worse case scenario, all regs in upper bank
4465     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4466     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4467     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4468     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4469   }
4470 }
4471 
4472 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4473   if (reachable(src)) {
4474     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4475   } else {
4476     lea(rscratch1, src);
4477     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4478   }
4479 }
4480 
4481 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4482   int dst_enc = dst->encoding();
4483   int src_enc = src->encoding();
4484   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4485     Assembler::vpbroadcastw(dst, src);
4486   } else if ((dst_enc < 16) && (src_enc < 16)) {
4487     Assembler::vpbroadcastw(dst, src);
4488   } else if (src_enc < 16) {
4489     subptr(rsp, 64);
4490     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4491     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4492     Assembler::vpbroadcastw(xmm0, src);
4493     movdqu(dst, xmm0);
4494     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4495     addptr(rsp, 64);
4496   } else if (dst_enc < 16) {
4497     subptr(rsp, 64);
4498     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4499     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4500     Assembler::vpbroadcastw(dst, xmm0);
4501     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4502     addptr(rsp, 64);
4503   } else {
4504     subptr(rsp, 64);
4505     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4506     subptr(rsp, 64);
4507     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4508     movdqu(xmm0, src);
4509     movdqu(xmm1, dst);
4510     Assembler::vpbroadcastw(xmm1, xmm0);
4511     movdqu(dst, xmm1);
4512     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4513     addptr(rsp, 64);
4514     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4515     addptr(rsp, 64);
4516   }
4517 }
4518 
4519 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4520   int dst_enc = dst->encoding();
4521   int nds_enc = nds->encoding();
4522   int src_enc = src->encoding();
4523   assert(dst_enc == nds_enc, "");
4524   if ((dst_enc < 16) && (src_enc < 16)) {
4525     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4526   } else if (src_enc < 16) {
4527     subptr(rsp, 64);
4528     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4529     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4530     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4531     movdqu(dst, xmm0);
4532     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4533     addptr(rsp, 64);
4534   } else if (dst_enc < 16) {
4535     subptr(rsp, 64);
4536     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4537     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4538     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4539     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4540     addptr(rsp, 64);
4541   } else {
4542     subptr(rsp, 64);
4543     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4544     subptr(rsp, 64);
4545     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4546     movdqu(xmm0, src);
4547     movdqu(xmm1, dst);
4548     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4549     movdqu(dst, xmm1);
4550     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4551     addptr(rsp, 64);
4552     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4553     addptr(rsp, 64);
4554   }
4555 }
4556 
4557 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4558   int dst_enc = dst->encoding();
4559   int nds_enc = nds->encoding();
4560   int src_enc = src->encoding();
4561   assert(dst_enc == nds_enc, "");
4562   if ((dst_enc < 16) && (src_enc < 16)) {
4563     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4564   } else if (src_enc < 16) {
4565     subptr(rsp, 64);
4566     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4567     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4568     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4569     movdqu(dst, xmm0);
4570     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4571     addptr(rsp, 64);
4572   } else if (dst_enc < 16) {
4573     subptr(rsp, 64);
4574     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4575     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4576     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4577     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4578     addptr(rsp, 64);
4579   } else {
4580     subptr(rsp, 64);
4581     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4582     subptr(rsp, 64);
4583     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4584     movdqu(xmm0, src);
4585     movdqu(xmm1, dst);
4586     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4587     movdqu(dst, xmm1);
4588     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4589     addptr(rsp, 64);
4590     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4591     addptr(rsp, 64);
4592   }
4593 }
4594 
4595 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4596   int dst_enc = dst->encoding();
4597   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4598     Assembler::vpmovzxbw(dst, src, vector_len);
4599   } else if (dst_enc < 16) {
4600     Assembler::vpmovzxbw(dst, src, vector_len);
4601   } else {
4602     subptr(rsp, 64);
4603     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4604     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4605     Assembler::vpmovzxbw(xmm0, src, vector_len);
4606     movdqu(dst, xmm0);
4607     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4608     addptr(rsp, 64);
4609   }
4610 }
4611 
4612 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4613   int src_enc = src->encoding();
4614   if (src_enc < 16) {
4615     Assembler::vpmovmskb(dst, src);
4616   } else {
4617     subptr(rsp, 64);
4618     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4619     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4620     Assembler::vpmovmskb(dst, xmm0);
4621     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4622     addptr(rsp, 64);
4623   }
4624 }
4625 
4626 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4627   int dst_enc = dst->encoding();
4628   int nds_enc = nds->encoding();
4629   int src_enc = src->encoding();
4630   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4631     Assembler::vpmullw(dst, nds, src, vector_len);
4632   } else if ((dst_enc < 16) && (src_enc < 16)) {
4633     Assembler::vpmullw(dst, dst, src, vector_len);
4634   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4635     // use nds as scratch for src
4636     evmovdqul(nds, src, Assembler::AVX_512bit);
4637     Assembler::vpmullw(dst, dst, nds, vector_len);
4638   } else if ((src_enc < 16) && (nds_enc < 16)) {
4639     // use nds as scratch for dst
4640     evmovdqul(nds, dst, Assembler::AVX_512bit);
4641     Assembler::vpmullw(nds, nds, src, vector_len);
4642     evmovdqul(dst, nds, Assembler::AVX_512bit);
4643   } else if (dst_enc < 16) {
4644     // use nds as scatch for xmm0 to hold src
4645     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4646     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4647     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4648     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4649   } else {
4650     // worse case scenario, all regs are in the upper bank
4651     subptr(rsp, 64);
4652     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4653     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4654     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4655     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4656     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4657     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4658     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4659     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4660     addptr(rsp, 64);
4661   }
4662 }
4663 
4664 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4665   int dst_enc = dst->encoding();
4666   int nds_enc = nds->encoding();
4667   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4668     Assembler::vpmullw(dst, nds, src, vector_len);
4669   } else if (dst_enc < 16) {
4670     Assembler::vpmullw(dst, dst, src, vector_len);
4671   } else if (nds_enc < 16) {
4672     // implies dst_enc in upper bank with src as scratch
4673     evmovdqul(nds, dst, Assembler::AVX_512bit);
4674     Assembler::vpmullw(nds, nds, src, vector_len);
4675     evmovdqul(dst, nds, Assembler::AVX_512bit);
4676   } else {
4677     // worse case scenario, all regs in upper bank
4678     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4679     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4680     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4681     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4682   }
4683 }
4684 
4685 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4686   int dst_enc = dst->encoding();
4687   int nds_enc = nds->encoding();
4688   int src_enc = src->encoding();
4689   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4690     Assembler::vpsubb(dst, nds, src, vector_len);
4691   } else if ((dst_enc < 16) && (src_enc < 16)) {
4692     Assembler::vpsubb(dst, dst, src, vector_len);
4693   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4694     // use nds as scratch for src
4695     evmovdqul(nds, src, Assembler::AVX_512bit);
4696     Assembler::vpsubb(dst, dst, nds, vector_len);
4697   } else if ((src_enc < 16) && (nds_enc < 16)) {
4698     // use nds as scratch for dst
4699     evmovdqul(nds, dst, Assembler::AVX_512bit);
4700     Assembler::vpsubb(nds, nds, src, vector_len);
4701     evmovdqul(dst, nds, Assembler::AVX_512bit);
4702   } else if (dst_enc < 16) {
4703     // use nds as scatch for xmm0 to hold src
4704     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4705     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4706     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4707     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4708   } else {
4709     // worse case scenario, all regs are in the upper bank
4710     subptr(rsp, 64);
4711     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4712     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4713     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4714     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4715     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4716     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4717     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4718     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4719     addptr(rsp, 64);
4720   }
4721 }
4722 
4723 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4724   int dst_enc = dst->encoding();
4725   int nds_enc = nds->encoding();
4726   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4727     Assembler::vpsubb(dst, nds, src, vector_len);
4728   } else if (dst_enc < 16) {
4729     Assembler::vpsubb(dst, dst, src, vector_len);
4730   } else if (nds_enc < 16) {
4731     // implies dst_enc in upper bank with src as scratch
4732     evmovdqul(nds, dst, Assembler::AVX_512bit);
4733     Assembler::vpsubb(nds, nds, src, vector_len);
4734     evmovdqul(dst, nds, Assembler::AVX_512bit);
4735   } else {
4736     // worse case scenario, all regs in upper bank
4737     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4738     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4739     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4740     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4741   }
4742 }
4743 
4744 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4745   int dst_enc = dst->encoding();
4746   int nds_enc = nds->encoding();
4747   int src_enc = src->encoding();
4748   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4749     Assembler::vpsubw(dst, nds, src, vector_len);
4750   } else if ((dst_enc < 16) && (src_enc < 16)) {
4751     Assembler::vpsubw(dst, dst, src, vector_len);
4752   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4753     // use nds as scratch for src
4754     evmovdqul(nds, src, Assembler::AVX_512bit);
4755     Assembler::vpsubw(dst, dst, nds, vector_len);
4756   } else if ((src_enc < 16) && (nds_enc < 16)) {
4757     // use nds as scratch for dst
4758     evmovdqul(nds, dst, Assembler::AVX_512bit);
4759     Assembler::vpsubw(nds, nds, src, vector_len);
4760     evmovdqul(dst, nds, Assembler::AVX_512bit);
4761   } else if (dst_enc < 16) {
4762     // use nds as scatch for xmm0 to hold src
4763     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4764     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4765     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4766     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4767   } else {
4768     // worse case scenario, all regs are in the upper bank
4769     subptr(rsp, 64);
4770     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4771     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4772     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4773     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4774     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4775     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4776     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4777     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4778     addptr(rsp, 64);
4779   }
4780 }
4781 
4782 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4783   int dst_enc = dst->encoding();
4784   int nds_enc = nds->encoding();
4785   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4786     Assembler::vpsubw(dst, nds, src, vector_len);
4787   } else if (dst_enc < 16) {
4788     Assembler::vpsubw(dst, dst, src, vector_len);
4789   } else if (nds_enc < 16) {
4790     // implies dst_enc in upper bank with src as scratch
4791     evmovdqul(nds, dst, Assembler::AVX_512bit);
4792     Assembler::vpsubw(nds, nds, src, vector_len);
4793     evmovdqul(dst, nds, Assembler::AVX_512bit);
4794   } else {
4795     // worse case scenario, all regs in upper bank
4796     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4797     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4798     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4799     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4800   }
4801 }
4802 
4803 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4804   int dst_enc = dst->encoding();
4805   int nds_enc = nds->encoding();
4806   int shift_enc = shift->encoding();
4807   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4808     Assembler::vpsraw(dst, nds, shift, vector_len);
4809   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4810     Assembler::vpsraw(dst, dst, shift, vector_len);
4811   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4812     // use nds_enc as scratch with shift
4813     evmovdqul(nds, shift, Assembler::AVX_512bit);
4814     Assembler::vpsraw(dst, dst, nds, vector_len);
4815   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4816     // use nds as scratch with dst
4817     evmovdqul(nds, dst, Assembler::AVX_512bit);
4818     Assembler::vpsraw(nds, nds, shift, vector_len);
4819     evmovdqul(dst, nds, Assembler::AVX_512bit);
4820   } else if (dst_enc < 16) {
4821     // use nds to save a copy of xmm0 and hold shift
4822     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4823     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4824     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4825     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4826   } else if (nds_enc < 16) {
4827     // use nds as dest as temps
4828     evmovdqul(nds, dst, Assembler::AVX_512bit);
4829     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4830     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4831     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4832     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4833     evmovdqul(dst, nds, Assembler::AVX_512bit);
4834   } else {
4835     // worse case scenario, all regs are in the upper bank
4836     subptr(rsp, 64);
4837     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4838     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4839     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4840     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4841     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4842     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4843     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4844     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4845     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4846     addptr(rsp, 64);
4847   }
4848 }
4849 
4850 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4851   int dst_enc = dst->encoding();
4852   int nds_enc = nds->encoding();
4853   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4854     Assembler::vpsraw(dst, nds, shift, vector_len);
4855   } else if (dst_enc < 16) {
4856     Assembler::vpsraw(dst, dst, shift, vector_len);
4857   } else if (nds_enc < 16) {
4858     // use nds as scratch
4859     evmovdqul(nds, dst, Assembler::AVX_512bit);
4860     Assembler::vpsraw(nds, nds, shift, vector_len);
4861     evmovdqul(dst, nds, Assembler::AVX_512bit);
4862   } else {
4863     // use nds as scratch for xmm0
4864     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4865     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4866     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4867     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4868   }
4869 }
4870 
4871 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4872   int dst_enc = dst->encoding();
4873   int nds_enc = nds->encoding();
4874   int shift_enc = shift->encoding();
4875   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4876     Assembler::vpsrlw(dst, nds, shift, vector_len);
4877   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4878     Assembler::vpsrlw(dst, dst, shift, vector_len);
4879   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4880     // use nds_enc as scratch with shift
4881     evmovdqul(nds, shift, Assembler::AVX_512bit);
4882     Assembler::vpsrlw(dst, dst, nds, vector_len);
4883   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4884     // use nds as scratch with dst
4885     evmovdqul(nds, dst, Assembler::AVX_512bit);
4886     Assembler::vpsrlw(nds, nds, shift, vector_len);
4887     evmovdqul(dst, nds, Assembler::AVX_512bit);
4888   } else if (dst_enc < 16) {
4889     // use nds to save a copy of xmm0 and hold shift
4890     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4891     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4892     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4893     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4894   } else if (nds_enc < 16) {
4895     // use nds as dest as temps
4896     evmovdqul(nds, dst, Assembler::AVX_512bit);
4897     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4898     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4899     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4900     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4901     evmovdqul(dst, nds, Assembler::AVX_512bit);
4902   } else {
4903     // worse case scenario, all regs are in the upper bank
4904     subptr(rsp, 64);
4905     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4906     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4907     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4908     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4909     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4910     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4911     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4912     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4913     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4914     addptr(rsp, 64);
4915   }
4916 }
4917 
4918 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4919   int dst_enc = dst->encoding();
4920   int nds_enc = nds->encoding();
4921   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4922     Assembler::vpsrlw(dst, nds, shift, vector_len);
4923   } else if (dst_enc < 16) {
4924     Assembler::vpsrlw(dst, dst, shift, vector_len);
4925   } else if (nds_enc < 16) {
4926     // use nds as scratch
4927     evmovdqul(nds, dst, Assembler::AVX_512bit);
4928     Assembler::vpsrlw(nds, nds, shift, vector_len);
4929     evmovdqul(dst, nds, Assembler::AVX_512bit);
4930   } else {
4931     // use nds as scratch for xmm0
4932     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4933     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4934     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4935     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4936   }
4937 }
4938 
4939 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4940   int dst_enc = dst->encoding();
4941   int nds_enc = nds->encoding();
4942   int shift_enc = shift->encoding();
4943   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4944     Assembler::vpsllw(dst, nds, shift, vector_len);
4945   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4946     Assembler::vpsllw(dst, dst, shift, vector_len);
4947   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4948     // use nds_enc as scratch with shift
4949     evmovdqul(nds, shift, Assembler::AVX_512bit);
4950     Assembler::vpsllw(dst, dst, nds, vector_len);
4951   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4952     // use nds as scratch with dst
4953     evmovdqul(nds, dst, Assembler::AVX_512bit);
4954     Assembler::vpsllw(nds, nds, shift, vector_len);
4955     evmovdqul(dst, nds, Assembler::AVX_512bit);
4956   } else if (dst_enc < 16) {
4957     // use nds to save a copy of xmm0 and hold shift
4958     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4959     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4960     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4961     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4962   } else if (nds_enc < 16) {
4963     // use nds as dest as temps
4964     evmovdqul(nds, dst, Assembler::AVX_512bit);
4965     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4966     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4967     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4968     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4969     evmovdqul(dst, nds, Assembler::AVX_512bit);
4970   } else {
4971     // worse case scenario, all regs are in the upper bank
4972     subptr(rsp, 64);
4973     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4974     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4975     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4976     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4977     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4978     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4979     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4980     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4981     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4982     addptr(rsp, 64);
4983   }
4984 }
4985 
4986 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4987   int dst_enc = dst->encoding();
4988   int nds_enc = nds->encoding();
4989   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4990     Assembler::vpsllw(dst, nds, shift, vector_len);
4991   } else if (dst_enc < 16) {
4992     Assembler::vpsllw(dst, dst, shift, vector_len);
4993   } else if (nds_enc < 16) {
4994     // use nds as scratch
4995     evmovdqul(nds, dst, Assembler::AVX_512bit);
4996     Assembler::vpsllw(nds, nds, shift, vector_len);
4997     evmovdqul(dst, nds, Assembler::AVX_512bit);
4998   } else {
4999     // use nds as scratch for xmm0
5000     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
5001     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5002     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
5003     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5004   }
5005 }
5006 
5007 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
5008   int dst_enc = dst->encoding();
5009   int src_enc = src->encoding();
5010   if ((dst_enc < 16) && (src_enc < 16)) {
5011     Assembler::vptest(dst, src);
5012   } else if (src_enc < 16) {
5013     subptr(rsp, 64);
5014     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5015     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5016     Assembler::vptest(xmm0, src);
5017     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5018     addptr(rsp, 64);
5019   } else if (dst_enc < 16) {
5020     subptr(rsp, 64);
5021     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5022     evmovdqul(xmm0, src, Assembler::AVX_512bit);
5023     Assembler::vptest(dst, xmm0);
5024     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5025     addptr(rsp, 64);
5026   } else {
5027     subptr(rsp, 64);
5028     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5029     subptr(rsp, 64);
5030     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5031     movdqu(xmm0, src);
5032     movdqu(xmm1, dst);
5033     Assembler::vptest(xmm1, xmm0);
5034     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5035     addptr(rsp, 64);
5036     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5037     addptr(rsp, 64);
5038   }
5039 }
5040 
5041 // This instruction exists within macros, ergo we cannot control its input
5042 // when emitted through those patterns.
5043 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
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::punpcklbw(dst, src);
5050       } else {
5051         subptr(rsp, 64);
5052         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5053         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5054         Assembler::punpcklbw(xmm0, xmm0);
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::punpcklbw(dst, src);
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::punpcklbw(xmm0, src);
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::punpcklbw(dst, xmm0);
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::punpcklbw(xmm0, xmm1);
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::punpcklbw(dst, src);
5094   }
5095 }
5096 
5097 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5098   if (VM_Version::supports_avx512vl()) {
5099     Assembler::pshufd(dst, src, mode);
5100   } else {
5101     int dst_enc = dst->encoding();
5102     if (dst_enc < 16) {
5103       Assembler::pshufd(dst, src, mode);
5104     } else {
5105       subptr(rsp, 64);
5106       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5107       Assembler::pshufd(xmm0, src, mode);
5108       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5109       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5110       addptr(rsp, 64);
5111     }
5112   }
5113 }
5114 
5115 // This instruction exists within macros, ergo we cannot control its input
5116 // when emitted through those patterns.
5117 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5118   if (VM_Version::supports_avx512nobw()) {
5119     int dst_enc = dst->encoding();
5120     int src_enc = src->encoding();
5121     if (dst_enc == src_enc) {
5122       if (dst_enc < 16) {
5123         Assembler::pshuflw(dst, src, mode);
5124       } else {
5125         subptr(rsp, 64);
5126         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5127         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5128         Assembler::pshuflw(xmm0, xmm0, mode);
5129         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5130         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5131         addptr(rsp, 64);
5132       }
5133     } else {
5134       if ((src_enc < 16) && (dst_enc < 16)) {
5135         Assembler::pshuflw(dst, src, mode);
5136       } else if (src_enc < 16) {
5137         subptr(rsp, 64);
5138         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5139         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5140         Assembler::pshuflw(xmm0, src, mode);
5141         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5142         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5143         addptr(rsp, 64);
5144       } else if (dst_enc < 16) {
5145         subptr(rsp, 64);
5146         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5147         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5148         Assembler::pshuflw(dst, xmm0, mode);
5149         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5150         addptr(rsp, 64);
5151       } else {
5152         subptr(rsp, 64);
5153         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5154         subptr(rsp, 64);
5155         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5156         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5157         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5158         Assembler::pshuflw(xmm0, xmm1, mode);
5159         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5160         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5161         addptr(rsp, 64);
5162         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5163         addptr(rsp, 64);
5164       }
5165     }
5166   } else {
5167     Assembler::pshuflw(dst, src, mode);
5168   }
5169 }
5170 
5171 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5172   if (reachable(src)) {
5173     vandpd(dst, nds, as_Address(src), vector_len);
5174   } else {
5175     lea(rscratch1, src);
5176     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5177   }
5178 }
5179 
5180 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5181   if (reachable(src)) {
5182     vandps(dst, nds, as_Address(src), vector_len);
5183   } else {
5184     lea(rscratch1, src);
5185     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5186   }
5187 }
5188 
5189 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5190   if (reachable(src)) {
5191     vdivsd(dst, nds, as_Address(src));
5192   } else {
5193     lea(rscratch1, src);
5194     vdivsd(dst, nds, Address(rscratch1, 0));
5195   }
5196 }
5197 
5198 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5199   if (reachable(src)) {
5200     vdivss(dst, nds, as_Address(src));
5201   } else {
5202     lea(rscratch1, src);
5203     vdivss(dst, nds, Address(rscratch1, 0));
5204   }
5205 }
5206 
5207 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5208   if (reachable(src)) {
5209     vmulsd(dst, nds, as_Address(src));
5210   } else {
5211     lea(rscratch1, src);
5212     vmulsd(dst, nds, Address(rscratch1, 0));
5213   }
5214 }
5215 
5216 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5217   if (reachable(src)) {
5218     vmulss(dst, nds, as_Address(src));
5219   } else {
5220     lea(rscratch1, src);
5221     vmulss(dst, nds, Address(rscratch1, 0));
5222   }
5223 }
5224 
5225 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5226   if (reachable(src)) {
5227     vsubsd(dst, nds, as_Address(src));
5228   } else {
5229     lea(rscratch1, src);
5230     vsubsd(dst, nds, Address(rscratch1, 0));
5231   }
5232 }
5233 
5234 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5235   if (reachable(src)) {
5236     vsubss(dst, nds, as_Address(src));
5237   } else {
5238     lea(rscratch1, src);
5239     vsubss(dst, nds, Address(rscratch1, 0));
5240   }
5241 }
5242 
5243 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5244   int nds_enc = nds->encoding();
5245   int dst_enc = dst->encoding();
5246   bool dst_upper_bank = (dst_enc > 15);
5247   bool nds_upper_bank = (nds_enc > 15);
5248   if (VM_Version::supports_avx512novl() &&
5249       (nds_upper_bank || dst_upper_bank)) {
5250     if (dst_upper_bank) {
5251       subptr(rsp, 64);
5252       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5253       movflt(xmm0, nds);
5254       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5255       movflt(dst, xmm0);
5256       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5257       addptr(rsp, 64);
5258     } else {
5259       movflt(dst, nds);
5260       vxorps(dst, dst, src, Assembler::AVX_128bit);
5261     }
5262   } else {
5263     vxorps(dst, nds, src, Assembler::AVX_128bit);
5264   }
5265 }
5266 
5267 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5268   int nds_enc = nds->encoding();
5269   int dst_enc = dst->encoding();
5270   bool dst_upper_bank = (dst_enc > 15);
5271   bool nds_upper_bank = (nds_enc > 15);
5272   if (VM_Version::supports_avx512novl() &&
5273       (nds_upper_bank || dst_upper_bank)) {
5274     if (dst_upper_bank) {
5275       subptr(rsp, 64);
5276       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5277       movdbl(xmm0, nds);
5278       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5279       movdbl(dst, xmm0);
5280       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5281       addptr(rsp, 64);
5282     } else {
5283       movdbl(dst, nds);
5284       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5285     }
5286   } else {
5287     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5288   }
5289 }
5290 
5291 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5292   if (reachable(src)) {
5293     vxorpd(dst, nds, as_Address(src), vector_len);
5294   } else {
5295     lea(rscratch1, src);
5296     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5297   }
5298 }
5299 
5300 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5301   if (reachable(src)) {
5302     vxorps(dst, nds, as_Address(src), vector_len);
5303   } else {
5304     lea(rscratch1, src);
5305     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5306   }
5307 }
5308 
5309 
5310 void MacroAssembler::resolve_jobject(Register value,
5311                                      Register thread,
5312                                      Register tmp) {
5313   assert_different_registers(value, thread, tmp);
5314   Label done, not_weak;
5315   testptr(value, value);
5316   jcc(Assembler::zero, done);                // Use NULL as-is.
5317   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5318   jcc(Assembler::zero, not_weak);
5319   // Resolve jweak.
5320   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5321   verify_oop(value);
5322 #if INCLUDE_ALL_GCS
5323   if (UseG1GC || UseShenandoahGC) {
5324     g1_write_barrier_pre(noreg /* obj */,
5325                          value /* pre_val */,
5326                          thread /* thread */,
5327                          tmp /* tmp */,
5328                          true /* tosca_live */,
5329                          true /* expand_call */);
5330   }
5331 #endif // INCLUDE_ALL_GCS
5332   jmp(done);
5333   bind(not_weak);
5334   // Resolve (untagged) jobject.
5335   movptr(value, Address(value, 0));
5336   verify_oop(value);
5337   bind(done);
5338 }
5339 
5340 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5341   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5342   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5343   // The inverted mask is sign-extended
5344   andptr(possibly_jweak, inverted_jweak_mask);
5345 }
5346 
5347 //////////////////////////////////////////////////////////////////////////////////
5348 #if INCLUDE_ALL_GCS
5349 
5350 void MacroAssembler::g1_write_barrier_pre(Register obj,
5351                                           Register pre_val,
5352                                           Register thread,
5353                                           Register tmp,
5354                                           bool tosca_live,
5355                                           bool expand_call) {
5356 
5357   // If expand_call is true then we expand the call_VM_leaf macro
5358   // directly to skip generating the check by
5359   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5360 
5361 #ifdef _LP64
5362   assert(thread == r15_thread, "must be");
5363 #endif // _LP64
5364 
5365   Label done;
5366   Label runtime;
5367 
5368   assert(pre_val != noreg, "check this code");
5369 
5370   if (obj != noreg) {
5371     assert_different_registers(obj, pre_val, tmp);
5372     assert(pre_val != rax, "check this code");
5373   }
5374 
5375   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5376                                        SATBMarkQueue::byte_offset_of_active()));
5377   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5378                                        SATBMarkQueue::byte_offset_of_index()));
5379   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5380                                        SATBMarkQueue::byte_offset_of_buf()));
5381 
5382 
5383   // Is marking active?
5384   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5385     cmpl(in_progress, 0);
5386   } else {
5387     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5388     cmpb(in_progress, 0);
5389   }
5390   jcc(Assembler::equal, done);
5391 
5392   // Do we need to load the previous value?
5393   if (obj != noreg) {
5394     load_heap_oop(pre_val, Address(obj, 0));
5395   }
5396 
5397   // Is the previous value null?
5398   cmpptr(pre_val, (int32_t) NULL_WORD);
5399   jcc(Assembler::equal, done);
5400 
5401   // Can we store original value in the thread's buffer?
5402   // Is index == 0?
5403   // (The index field is typed as size_t.)
5404 
5405   movptr(tmp, index);                   // tmp := *index_adr
5406   cmpptr(tmp, 0);                       // tmp == 0?
5407   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5408 
5409   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5410   movptr(index, tmp);                   // *index_adr := tmp
5411   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5412 
5413   // Record the previous value
5414   movptr(Address(tmp, 0), pre_val);
5415   jmp(done);
5416 
5417   bind(runtime);
5418   // save the live input values
5419   if(tosca_live) push(rax);
5420 
5421   if (obj != noreg && obj != rax)
5422     push(obj);
5423 
5424   if (pre_val != rax)
5425     push(pre_val);
5426 
5427   // Calling the runtime using the regular call_VM_leaf mechanism generates
5428   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5429   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5430   //
5431   // If we care generating the pre-barrier without a frame (e.g. in the
5432   // intrinsified Reference.get() routine) then ebp might be pointing to
5433   // the caller frame and so this check will most likely fail at runtime.
5434   //
5435   // Expanding the call directly bypasses the generation of the check.
5436   // So when we do not have have a full interpreter frame on the stack
5437   // expand_call should be passed true.
5438 
5439   NOT_LP64( push(thread); )
5440 
5441   if (expand_call) {
5442     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5443     pass_arg1(this, thread);
5444     pass_arg0(this, pre_val);
5445     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5446   } else {
5447     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5448   }
5449 
5450   NOT_LP64( pop(thread); )
5451 
5452   // save the live input values
5453   if (pre_val != rax)
5454     pop(pre_val);
5455 
5456   if (obj != noreg && obj != rax)
5457     pop(obj);
5458 
5459   if(tosca_live) pop(rax);
5460 
5461   bind(done);
5462 }
5463 
5464 void MacroAssembler::shenandoah_write_barrier_post(Register store_addr,
5465                                                    Register new_val,
5466                                                    Register thread,
5467                                                    Register tmp,
5468                                                    Register tmp2) {
5469   assert(UseShenandoahGC, "why else should we be here?");
5470 
5471   if (! UseShenandoahMatrix) {
5472     // No need for that barrier if not using matrix.
5473     return;
5474   }
5475 
5476   Label done;
5477   testptr(new_val, new_val);
5478   jcc(Assembler::zero, done);
5479   ShenandoahConnectionMatrix* matrix = ShenandoahHeap::heap()->connection_matrix();
5480   address matrix_addr = matrix->matrix_addr();
5481   movptr(rscratch1, (intptr_t) ShenandoahHeap::heap()->base());
5482   // Compute to-region index
5483   movptr(tmp, new_val);
5484   subptr(tmp, rscratch1);
5485   shrptr(tmp, ShenandoahHeapRegion::region_size_bytes_shift_jint());
5486   // Compute from-region index
5487   movptr(tmp2, store_addr);
5488   subptr(tmp2, rscratch1);
5489   shrptr(tmp2, ShenandoahHeapRegion::region_size_bytes_shift_jint());
5490   // Compute matrix index
5491   imulptr(tmp, tmp, matrix->stride_jint());
5492   addptr(tmp, tmp2);
5493   // Address is _matrix[from * stride + to]
5494   movptr(rscratch1, (intptr_t) matrix_addr);
5495   // Test if the element is already set.
5496   testb(Address(rscratch1, tmp, Address::times_1), 0);
5497   jcc(Assembler::notZero, done);
5498   // Store true, if not yet set.
5499   movb(Address(rscratch1, tmp, Address::times_1), 1);
5500   bind(done);
5501 }
5502 
5503 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5504                                            Register new_val,
5505                                            Register thread,
5506                                            Register tmp,
5507                                            Register tmp2) {
5508 #ifdef _LP64
5509   assert(thread == r15_thread, "must be");
5510 #endif // _LP64
5511 
5512   assert(UseG1GC, "expect G1 GC");
5513 
5514   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5515                                        DirtyCardQueue::byte_offset_of_index()));
5516   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5517                                        DirtyCardQueue::byte_offset_of_buf()));
5518 
5519   CardTableModRefBS* ct =
5520     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5521   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5522 
5523   Label done;
5524   Label runtime;
5525 
5526   // Does store cross heap regions?
5527 
5528   movptr(tmp, store_addr);
5529   xorptr(tmp, new_val);
5530   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5531   jcc(Assembler::equal, done);
5532 
5533   // crosses regions, storing NULL?
5534 
5535   cmpptr(new_val, (int32_t) NULL_WORD);
5536   jcc(Assembler::equal, done);
5537 
5538   // storing region crossing non-NULL, is card already dirty?
5539 
5540   const Register card_addr = tmp;
5541   const Register cardtable = tmp2;
5542 
5543   movptr(card_addr, store_addr);
5544   shrptr(card_addr, CardTableModRefBS::card_shift);
5545   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5546   // a valid address and therefore is not properly handled by the relocation code.
5547   movptr(cardtable, (intptr_t)ct->byte_map_base);
5548   addptr(card_addr, cardtable);
5549 
5550   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5551   jcc(Assembler::equal, done);
5552 
5553   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5554   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5555   jcc(Assembler::equal, done);
5556 
5557 
5558   // storing a region crossing, non-NULL oop, card is clean.
5559   // dirty card and log.
5560 
5561   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5562 
5563   cmpl(queue_index, 0);
5564   jcc(Assembler::equal, runtime);
5565   subl(queue_index, wordSize);
5566   movptr(tmp2, buffer);
5567 #ifdef _LP64
5568   movslq(rscratch1, queue_index);
5569   addq(tmp2, rscratch1);
5570   movq(Address(tmp2, 0), card_addr);
5571 #else
5572   addl(tmp2, queue_index);
5573   movl(Address(tmp2, 0), card_addr);
5574 #endif
5575   jmp(done);
5576 
5577   bind(runtime);
5578   // save the live input values
5579   push(store_addr);
5580   push(new_val);
5581 #ifdef _LP64
5582   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5583 #else
5584   push(thread);
5585   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5586   pop(thread);
5587 #endif
5588   pop(new_val);
5589   pop(store_addr);
5590 
5591   bind(done);
5592 }
5593 
5594 void MacroAssembler::keep_alive_barrier(Register val,
5595                                         Register thread,
5596                                         Register tmp) {
5597 
5598   if (UseG1GC || (UseShenandoahGC && ShenandoahKeepAliveBarrier)) {
5599     // Generate the G1 pre-barrier code to log the value of
5600     // the referent field in an SATB buffer.
5601     g1_write_barrier_pre(noreg, 
5602                          rax /* pre_val */,
5603                          thread /* thread */,
5604                          tmp,
5605                          true /* tosca_live */,
5606                          true /* expand_call */);
5607   }
5608 }
5609 
5610 #ifndef _LP64
5611 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5612   Unimplemented();
5613 }
5614 #else
5615 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5616   assert(UseShenandoahGC, "must only be called with Shenandoah GC active");
5617   assert(ShenandoahWriteBarrier, "must only be called when write barriers are enabled");
5618 
5619   Label done;
5620 
5621   // Check for evacuation-in-progress
5622   Address evacuation_in_progress = Address(r15_thread, in_bytes(JavaThread::evacuation_in_progress_offset()));
5623   cmpb(evacuation_in_progress, 0);
5624 
5625   // The read-barrier.
5626   movptr(dst, Address(dst, BrooksPointer::byte_offset()));
5627 
5628   jccb(Assembler::equal, done);
5629 
5630   if (dst != rax) {
5631     xchgptr(dst, rax); // Move obj into rax and save rax into obj.
5632   }
5633 
5634   assert(StubRoutines::x86::shenandoah_wb() != NULL, "need write barrier stub");
5635   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::shenandoah_wb())));
5636 
5637   if (dst != rax) {
5638     xchgptr(rax, dst); // Swap back obj with rax.
5639   }
5640 
5641   bind(done);
5642 }
5643 #endif // _LP64
5644 
5645 #endif // INCLUDE_ALL_GCS
5646 //////////////////////////////////////////////////////////////////////////////////
5647 
5648 
5649 void MacroAssembler::store_check(Register obj, Address dst) {
5650   store_check(obj);
5651 }
5652 
5653 void MacroAssembler::store_check(Register obj) {
5654   // Does a store check for the oop in register obj. The content of
5655   // register obj is destroyed afterwards.
5656   BarrierSet* bs = Universe::heap()->barrier_set();
5657   assert(bs->kind() == BarrierSet::CardTableForRS ||
5658          bs->kind() == BarrierSet::CardTableExtension,
5659          "Wrong barrier set kind");
5660 
5661   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5662   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5663 
5664   shrptr(obj, CardTableModRefBS::card_shift);
5665 
5666   Address card_addr;
5667 
5668   // The calculation for byte_map_base is as follows:
5669   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5670   // So this essentially converts an address to a displacement and it will
5671   // never need to be relocated. On 64bit however the value may be too
5672   // large for a 32bit displacement.
5673   intptr_t disp = (intptr_t) ct->byte_map_base;
5674   if (is_simm32(disp)) {
5675     card_addr = Address(noreg, obj, Address::times_1, disp);
5676   } else {
5677     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5678     // displacement and done in a single instruction given favorable mapping and a
5679     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5680     // entry and that entry is not properly handled by the relocation code.
5681     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5682     Address index(noreg, obj, Address::times_1);
5683     card_addr = as_Address(ArrayAddress(cardtable, index));
5684   }
5685 
5686   int dirty = CardTableModRefBS::dirty_card_val();
5687   if (UseCondCardMark) {
5688     Label L_already_dirty;
5689     if (UseConcMarkSweepGC) {
5690       membar(Assembler::StoreLoad);
5691     }
5692     cmpb(card_addr, dirty);
5693     jcc(Assembler::equal, L_already_dirty);
5694     movb(card_addr, dirty);
5695     bind(L_already_dirty);
5696   } else {
5697     movb(card_addr, dirty);
5698   }
5699 }
5700 
5701 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5702   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5703 }
5704 
5705 // Force generation of a 4 byte immediate value even if it fits into 8bit
5706 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5707   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5708 }
5709 
5710 void MacroAssembler::subptr(Register dst, Register src) {
5711   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5712 }
5713 
5714 // C++ bool manipulation
5715 void MacroAssembler::testbool(Register dst) {
5716   if(sizeof(bool) == 1)
5717     testb(dst, 0xff);
5718   else if(sizeof(bool) == 2) {
5719     // testw implementation needed for two byte bools
5720     ShouldNotReachHere();
5721   } else if(sizeof(bool) == 4)
5722     testl(dst, dst);
5723   else
5724     // unsupported
5725     ShouldNotReachHere();
5726 }
5727 
5728 void MacroAssembler::testptr(Register dst, Register src) {
5729   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5730 }
5731 
5732 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5733 void MacroAssembler::tlab_allocate(Register obj,
5734                                    Register var_size_in_bytes,
5735                                    int con_size_in_bytes,
5736                                    Register t1,
5737                                    Register t2,
5738                                    Label& slow_case) {
5739   assert_different_registers(obj, t1, t2);
5740   assert_different_registers(obj, var_size_in_bytes, t1);
5741   Register end = t2;
5742   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5743 
5744   verify_tlab();
5745 
5746   NOT_LP64(get_thread(thread));
5747 
5748   uint oop_extra_words = Universe::heap()->oop_extra_words();
5749 
5750   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5751   if (var_size_in_bytes == noreg) {
5752     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5753   } else {
5754     if (oop_extra_words > 0) {
5755       addptr(var_size_in_bytes, oop_extra_words * HeapWordSize);
5756     }
5757     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5758   }
5759   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5760   jcc(Assembler::above, slow_case);
5761 
5762   // update the tlab top pointer
5763   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5764 
5765   Universe::heap()->compile_prepare_oop(this, obj);
5766 
5767   // recover var_size_in_bytes if necessary
5768   if (var_size_in_bytes == end) {
5769     subptr(var_size_in_bytes, obj);
5770   }
5771   verify_tlab();
5772 }
5773 
5774 // Preserves rbx, and rdx.
5775 Register MacroAssembler::tlab_refill(Label& retry,
5776                                      Label& try_eden,
5777                                      Label& slow_case) {
5778   Register top = rax;
5779   Register t1  = rcx; // object size
5780   Register t2  = rsi;
5781   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5782   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5783   Label do_refill, discard_tlab;
5784 
5785   if (!Universe::heap()->supports_inline_contig_alloc()) {
5786     // No allocation in the shared eden.
5787     jmp(slow_case);
5788   }
5789 
5790   NOT_LP64(get_thread(thread_reg));
5791 
5792   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5793   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5794 
5795   // calculate amount of free space
5796   subptr(t1, top);
5797   shrptr(t1, LogHeapWordSize);
5798 
5799   // Retain tlab and allocate object in shared space if
5800   // the amount free in the tlab is too large to discard.
5801   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5802   jcc(Assembler::lessEqual, discard_tlab);
5803 
5804   // Retain
5805   // %%% yuck as movptr...
5806   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5807   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5808   if (TLABStats) {
5809     // increment number of slow_allocations
5810     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5811   }
5812   jmp(try_eden);
5813 
5814   bind(discard_tlab);
5815   if (TLABStats) {
5816     // increment number of refills
5817     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5818     // accumulate wastage -- t1 is amount free in tlab
5819     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5820   }
5821 
5822   // if tlab is currently allocated (top or end != null) then
5823   // fill [top, end + alignment_reserve) with array object
5824   testptr(top, top);
5825   jcc(Assembler::zero, do_refill);
5826 
5827   // set up the mark word
5828   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5829   // set the length to the remaining space
5830   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5831   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5832   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5833   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5834   // set klass to intArrayKlass
5835   // dubious reloc why not an oop reloc?
5836   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5837   // store klass last.  concurrent gcs assumes klass length is valid if
5838   // klass field is not null.
5839   store_klass(top, t1);
5840 
5841   movptr(t1, top);
5842   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5843   incr_allocated_bytes(thread_reg, t1, 0);
5844 
5845   // refill the tlab with an eden allocation
5846   bind(do_refill);
5847   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5848   shlptr(t1, LogHeapWordSize);
5849   // allocate new tlab, address returned in top
5850   eden_allocate(top, t1, 0, t2, slow_case);
5851 
5852   // Check that t1 was preserved in eden_allocate.
5853 #ifdef ASSERT
5854   if (UseTLAB) {
5855     Label ok;
5856     Register tsize = rsi;
5857     assert_different_registers(tsize, thread_reg, t1);
5858     push(tsize);
5859     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5860     shlptr(tsize, LogHeapWordSize);
5861     cmpptr(t1, tsize);
5862     jcc(Assembler::equal, ok);
5863     STOP("assert(t1 != tlab size)");
5864     should_not_reach_here();
5865 
5866     bind(ok);
5867     pop(tsize);
5868   }
5869 #endif
5870   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5871   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5872   addptr(top, t1);
5873   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5874   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5875 
5876   if (ZeroTLAB) {
5877     // This is a fast TLAB refill, therefore the GC is not notified of it.
5878     // So compiled code must fill the new TLAB with zeroes.
5879     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5880     zero_memory(top, t1, 0, t2);
5881   }
5882 
5883   verify_tlab();
5884   jmp(retry);
5885 
5886   return thread_reg; // for use by caller
5887 }
5888 
5889 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5890 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5891   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5892   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5893   Label done;
5894 
5895   testptr(length_in_bytes, length_in_bytes);
5896   jcc(Assembler::zero, done);
5897 
5898   // initialize topmost word, divide index by 2, check if odd and test if zero
5899   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5900 #ifdef ASSERT
5901   {
5902     Label L;
5903     testptr(length_in_bytes, BytesPerWord - 1);
5904     jcc(Assembler::zero, L);
5905     stop("length must be a multiple of BytesPerWord");
5906     bind(L);
5907   }
5908 #endif
5909   Register index = length_in_bytes;
5910   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5911   if (UseIncDec) {
5912     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5913   } else {
5914     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5915     shrptr(index, 1);
5916   }
5917 #ifndef _LP64
5918   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5919   {
5920     Label even;
5921     // note: if index was a multiple of 8, then it cannot
5922     //       be 0 now otherwise it must have been 0 before
5923     //       => if it is even, we don't need to check for 0 again
5924     jcc(Assembler::carryClear, even);
5925     // clear topmost word (no jump would be needed if conditional assignment worked here)
5926     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5927     // index could be 0 now, must check again
5928     jcc(Assembler::zero, done);
5929     bind(even);
5930   }
5931 #endif // !_LP64
5932   // initialize remaining object fields: index is a multiple of 2 now
5933   {
5934     Label loop;
5935     bind(loop);
5936     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5937     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5938     decrement(index);
5939     jcc(Assembler::notZero, loop);
5940   }
5941 
5942   bind(done);
5943 }
5944 
5945 void MacroAssembler::incr_allocated_bytes(Register thread,
5946                                           Register var_size_in_bytes,
5947                                           int con_size_in_bytes,
5948                                           Register t1) {
5949   if (!thread->is_valid()) {
5950 #ifdef _LP64
5951     thread = r15_thread;
5952 #else
5953     assert(t1->is_valid(), "need temp reg");
5954     thread = t1;
5955     get_thread(thread);
5956 #endif
5957   }
5958 
5959 #ifdef _LP64
5960   if (var_size_in_bytes->is_valid()) {
5961     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5962   } else {
5963     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5964   }
5965 #else
5966   if (var_size_in_bytes->is_valid()) {
5967     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5968   } else {
5969     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5970   }
5971   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5972 #endif
5973 }
5974 
5975 // Look up the method for a megamorphic invokeinterface call.
5976 // The target method is determined by <intf_klass, itable_index>.
5977 // The receiver klass is in recv_klass.
5978 // On success, the result will be in method_result, and execution falls through.
5979 // On failure, execution transfers to the given label.
5980 void MacroAssembler::lookup_interface_method(Register recv_klass,
5981                                              Register intf_klass,
5982                                              RegisterOrConstant itable_index,
5983                                              Register method_result,
5984                                              Register scan_temp,
5985                                              Label& L_no_such_interface) {
5986   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5987   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5988          "caller must use same register for non-constant itable index as for method");
5989 
5990   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5991   int vtable_base = in_bytes(Klass::vtable_start_offset());
5992   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5993   int scan_step   = itableOffsetEntry::size() * wordSize;
5994   int vte_size    = vtableEntry::size_in_bytes();
5995   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5996   assert(vte_size == wordSize, "else adjust times_vte_scale");
5997 
5998   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5999 
6000   // %%% Could store the aligned, prescaled offset in the klassoop.
6001   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
6002 
6003   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
6004   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
6005   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
6006 
6007   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
6008   //   if (scan->interface() == intf) {
6009   //     result = (klass + scan->offset() + itable_index);
6010   //   }
6011   // }
6012   Label search, found_method;
6013 
6014   for (int peel = 1; peel >= 0; peel--) {
6015     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
6016     cmpptr(intf_klass, method_result);
6017 
6018     if (peel) {
6019       jccb(Assembler::equal, found_method);
6020     } else {
6021       jccb(Assembler::notEqual, search);
6022       // (invert the test to fall through to found_method...)
6023     }
6024 
6025     if (!peel)  break;
6026 
6027     bind(search);
6028 
6029     // Check that the previous entry is non-null.  A null entry means that
6030     // the receiver class doesn't implement the interface, and wasn't the
6031     // same as when the caller was compiled.
6032     testptr(method_result, method_result);
6033     jcc(Assembler::zero, L_no_such_interface);
6034     addptr(scan_temp, scan_step);
6035   }
6036 
6037   bind(found_method);
6038 
6039   // Got a hit.
6040   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
6041   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
6042 }
6043 
6044 
6045 // virtual method calling
6046 void MacroAssembler::lookup_virtual_method(Register recv_klass,
6047                                            RegisterOrConstant vtable_index,
6048                                            Register method_result) {
6049   const int base = in_bytes(Klass::vtable_start_offset());
6050   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
6051   Address vtable_entry_addr(recv_klass,
6052                             vtable_index, Address::times_ptr,
6053                             base + vtableEntry::method_offset_in_bytes());
6054   movptr(method_result, vtable_entry_addr);
6055 }
6056 
6057 
6058 void MacroAssembler::check_klass_subtype(Register sub_klass,
6059                            Register super_klass,
6060                            Register temp_reg,
6061                            Label& L_success) {
6062   Label L_failure;
6063   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
6064   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
6065   bind(L_failure);
6066 }
6067 
6068 
6069 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
6070                                                    Register super_klass,
6071                                                    Register temp_reg,
6072                                                    Label* L_success,
6073                                                    Label* L_failure,
6074                                                    Label* L_slow_path,
6075                                         RegisterOrConstant super_check_offset) {
6076   assert_different_registers(sub_klass, super_klass, temp_reg);
6077   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
6078   if (super_check_offset.is_register()) {
6079     assert_different_registers(sub_klass, super_klass,
6080                                super_check_offset.as_register());
6081   } else if (must_load_sco) {
6082     assert(temp_reg != noreg, "supply either a temp or a register offset");
6083   }
6084 
6085   Label L_fallthrough;
6086   int label_nulls = 0;
6087   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6088   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6089   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6090   assert(label_nulls <= 1, "at most one NULL in the batch");
6091 
6092   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6093   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6094   Address super_check_offset_addr(super_klass, sco_offset);
6095 
6096   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6097   // range of a jccb.  If this routine grows larger, reconsider at
6098   // least some of these.
6099 #define local_jcc(assembler_cond, label)                                \
6100   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6101   else                             jcc( assembler_cond, label) /*omit semi*/
6102 
6103   // Hacked jmp, which may only be used just before L_fallthrough.
6104 #define final_jmp(label)                                                \
6105   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6106   else                            jmp(label)                /*omit semi*/
6107 
6108   // If the pointers are equal, we are done (e.g., String[] elements).
6109   // This self-check enables sharing of secondary supertype arrays among
6110   // non-primary types such as array-of-interface.  Otherwise, each such
6111   // type would need its own customized SSA.
6112   // We move this check to the front of the fast path because many
6113   // type checks are in fact trivially successful in this manner,
6114   // so we get a nicely predicted branch right at the start of the check.
6115   cmpptr(sub_klass, super_klass);
6116   local_jcc(Assembler::equal, *L_success);
6117 
6118   // Check the supertype display:
6119   if (must_load_sco) {
6120     // Positive movl does right thing on LP64.
6121     movl(temp_reg, super_check_offset_addr);
6122     super_check_offset = RegisterOrConstant(temp_reg);
6123   }
6124   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6125   cmpptr(super_klass, super_check_addr); // load displayed supertype
6126 
6127   // This check has worked decisively for primary supers.
6128   // Secondary supers are sought in the super_cache ('super_cache_addr').
6129   // (Secondary supers are interfaces and very deeply nested subtypes.)
6130   // This works in the same check above because of a tricky aliasing
6131   // between the super_cache and the primary super display elements.
6132   // (The 'super_check_addr' can address either, as the case requires.)
6133   // Note that the cache is updated below if it does not help us find
6134   // what we need immediately.
6135   // So if it was a primary super, we can just fail immediately.
6136   // Otherwise, it's the slow path for us (no success at this point).
6137 
6138   if (super_check_offset.is_register()) {
6139     local_jcc(Assembler::equal, *L_success);
6140     cmpl(super_check_offset.as_register(), sc_offset);
6141     if (L_failure == &L_fallthrough) {
6142       local_jcc(Assembler::equal, *L_slow_path);
6143     } else {
6144       local_jcc(Assembler::notEqual, *L_failure);
6145       final_jmp(*L_slow_path);
6146     }
6147   } else if (super_check_offset.as_constant() == sc_offset) {
6148     // Need a slow path; fast failure is impossible.
6149     if (L_slow_path == &L_fallthrough) {
6150       local_jcc(Assembler::equal, *L_success);
6151     } else {
6152       local_jcc(Assembler::notEqual, *L_slow_path);
6153       final_jmp(*L_success);
6154     }
6155   } else {
6156     // No slow path; it's a fast decision.
6157     if (L_failure == &L_fallthrough) {
6158       local_jcc(Assembler::equal, *L_success);
6159     } else {
6160       local_jcc(Assembler::notEqual, *L_failure);
6161       final_jmp(*L_success);
6162     }
6163   }
6164 
6165   bind(L_fallthrough);
6166 
6167 #undef local_jcc
6168 #undef final_jmp
6169 }
6170 
6171 
6172 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6173                                                    Register super_klass,
6174                                                    Register temp_reg,
6175                                                    Register temp2_reg,
6176                                                    Label* L_success,
6177                                                    Label* L_failure,
6178                                                    bool set_cond_codes) {
6179   assert_different_registers(sub_klass, super_klass, temp_reg);
6180   if (temp2_reg != noreg)
6181     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6182 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6183 
6184   Label L_fallthrough;
6185   int label_nulls = 0;
6186   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6187   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6188   assert(label_nulls <= 1, "at most one NULL in the batch");
6189 
6190   // a couple of useful fields in sub_klass:
6191   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6192   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6193   Address secondary_supers_addr(sub_klass, ss_offset);
6194   Address super_cache_addr(     sub_klass, sc_offset);
6195 
6196   // Do a linear scan of the secondary super-klass chain.
6197   // This code is rarely used, so simplicity is a virtue here.
6198   // The repne_scan instruction uses fixed registers, which we must spill.
6199   // Don't worry too much about pre-existing connections with the input regs.
6200 
6201   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6202   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6203 
6204   // Get super_klass value into rax (even if it was in rdi or rcx).
6205   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6206   if (super_klass != rax || UseCompressedOops) {
6207     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6208     mov(rax, super_klass);
6209   }
6210   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6211   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6212 
6213 #ifndef PRODUCT
6214   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6215   ExternalAddress pst_counter_addr((address) pst_counter);
6216   NOT_LP64(  incrementl(pst_counter_addr) );
6217   LP64_ONLY( lea(rcx, pst_counter_addr) );
6218   LP64_ONLY( incrementl(Address(rcx, 0)) );
6219 #endif //PRODUCT
6220 
6221   // We will consult the secondary-super array.
6222   movptr(rdi, secondary_supers_addr);
6223   // Load the array length.  (Positive movl does right thing on LP64.)
6224   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6225   // Skip to start of data.
6226   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6227 
6228   // Scan RCX words at [RDI] for an occurrence of RAX.
6229   // Set NZ/Z based on last compare.
6230   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6231   // not change flags (only scas instruction which is repeated sets flags).
6232   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6233 
6234     testptr(rax,rax); // Set Z = 0
6235     repne_scan();
6236 
6237   // Unspill the temp. registers:
6238   if (pushed_rdi)  pop(rdi);
6239   if (pushed_rcx)  pop(rcx);
6240   if (pushed_rax)  pop(rax);
6241 
6242   if (set_cond_codes) {
6243     // Special hack for the AD files:  rdi is guaranteed non-zero.
6244     assert(!pushed_rdi, "rdi must be left non-NULL");
6245     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6246   }
6247 
6248   if (L_failure == &L_fallthrough)
6249         jccb(Assembler::notEqual, *L_failure);
6250   else  jcc(Assembler::notEqual, *L_failure);
6251 
6252   // Success.  Cache the super we found and proceed in triumph.
6253   movptr(super_cache_addr, super_klass);
6254 
6255   if (L_success != &L_fallthrough) {
6256     jmp(*L_success);
6257   }
6258 
6259 #undef IS_A_TEMP
6260 
6261   bind(L_fallthrough);
6262 }
6263 
6264 
6265 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6266   if (VM_Version::supports_cmov()) {
6267     cmovl(cc, dst, src);
6268   } else {
6269     Label L;
6270     jccb(negate_condition(cc), L);
6271     movl(dst, src);
6272     bind(L);
6273   }
6274 }
6275 
6276 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6277   if (VM_Version::supports_cmov()) {
6278     cmovl(cc, dst, src);
6279   } else {
6280     Label L;
6281     jccb(negate_condition(cc), L);
6282     movl(dst, src);
6283     bind(L);
6284   }
6285 }
6286 
6287 void MacroAssembler::verify_oop(Register reg, const char* s) {
6288   if (!VerifyOops) return;
6289 
6290   // Pass register number to verify_oop_subroutine
6291   const char* b = NULL;
6292   {
6293     ResourceMark rm;
6294     stringStream ss;
6295     ss.print("verify_oop: %s: %s", reg->name(), s);
6296     b = code_string(ss.as_string());
6297   }
6298   BLOCK_COMMENT("verify_oop {");
6299 #ifdef _LP64
6300   push(rscratch1);                    // save r10, trashed by movptr()
6301 #endif
6302   push(rax);                          // save rax,
6303   push(reg);                          // pass register argument
6304   ExternalAddress buffer((address) b);
6305   // avoid using pushptr, as it modifies scratch registers
6306   // and our contract is not to modify anything
6307   movptr(rax, buffer.addr());
6308   push(rax);
6309   // call indirectly to solve generation ordering problem
6310   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6311   call(rax);
6312   // Caller pops the arguments (oop, message) and restores rax, r10
6313   BLOCK_COMMENT("} verify_oop");
6314 }
6315 
6316 
6317 void MacroAssembler::shenandoah_in_heap_check(Register dst, Register tmp, Label& done) {
6318   // Converts dst to biased region index
6319 
6320   // Test that oop is not in to-space.
6321   shrptr(dst, ShenandoahHeapRegion::region_size_bytes_shift_jint());
6322 
6323   // Check if in bounds for cset check. This implicitly checks if target is in heap.
6324   // Since heap might not start at zero, we want to bias the low/high boundaries.
6325   uintx bias = (uintx) ShenandoahHeap::heap()->base() >> ShenandoahHeapRegion::region_size_bytes_shift();
6326   int32_t low = (int32_t) (0 + bias);
6327   int32_t high = (int32_t) (ShenandoahHeap::heap()->num_regions() + bias);
6328 
6329   cmpptr(dst, low);
6330   jccb(Assembler::below, done);
6331   cmpptr(dst, high);
6332   jccb(Assembler::aboveEqual, done);
6333 }
6334 
6335 void MacroAssembler::shenandoah_cset_check(Register dst, Register tmp, Label& done) {
6336   // Destroys dst
6337 
6338   shenandoah_in_heap_check(dst, tmp, done);
6339 
6340   movptr(tmp, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
6341   movbool(tmp, Address(tmp, dst, Address::times_1));
6342   testbool(tmp);
6343   jccb(Assembler::zero, done);
6344 
6345   // Check for cancelled GC.
6346   movptr(tmp, (intptr_t) ShenandoahHeap::cancelled_concgc_addr());
6347   movbool(tmp, Address(tmp, 0));
6348   testbool(tmp);
6349   jccb(Assembler::notZero, done);
6350 }
6351 
6352 #ifndef _LP64
6353 void MacroAssembler::shenandoah_store_addr_check(Address addr) {
6354   // Not implemented on 32-bit, pass.
6355 }
6356 void MacroAssembler::shenandoah_store_addr_check(Register dst) {
6357   // Not implemented on 32-bit, pass.
6358 }
6359 void MacroAssembler::shenandoah_store_val_check(Register dst, Register value) {
6360   // Not implemented on 32-bit, pass.
6361 }
6362 void MacroAssembler::shenandoah_store_val_check(Address dst, Register value) {
6363   // Not implemented on 32-bit, pass.
6364 }
6365 void MacroAssembler::shenandoah_lock_check(Register dst) {
6366   // Not implemented on 32-bit, pass.
6367 }
6368 #else
6369 void MacroAssembler::shenandoah_store_addr_check(Address addr) {
6370   shenandoah_store_addr_check(addr.base());
6371 }
6372 
6373 void MacroAssembler::shenandoah_store_addr_check(Register dst) {
6374   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6375   if (dst == rsp) return; // Stack-based target
6376 
6377   // This method temporarily destroys dst, but always pushes
6378   // the original values on stack, and restores them on exit.
6379 
6380   Register tmp = NULL;
6381   if (dst != rscratch1) {
6382     tmp = rscratch1;
6383   } else if (dst != rscratch2) {
6384     tmp = rscratch2;
6385   } else {
6386     guarantee(false, "able to select the temp register");
6387   }
6388 
6389   Label done;
6390 
6391   pushf();
6392   push(dst);
6393   push(tmp);
6394 
6395   // Check null.
6396   testptr(dst, dst);
6397   jcc(Assembler::zero, done);
6398 
6399   shenandoah_cset_check(dst, tmp, done);
6400 
6401   // Fail.
6402   pop(tmp);
6403   pop(dst);
6404   popf();
6405 
6406   // Stop, provoke SEGV.
6407   // Shortest way to fail VM with RIP pointing to this check.
6408   // Store dst register to clearly see what had failed.
6409   lea(tmp, ExternalAddress(badAddress));
6410   movptr(Address(tmp, 0), dst);
6411   hlt();
6412 
6413   bind(done);
6414 
6415   pop(tmp);
6416   pop(dst);
6417   popf();
6418 }
6419 
6420 void MacroAssembler::shenandoah_store_val_check(Register dst, Register value) {
6421   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6422   if (dst == rsp)   return; // Stack-based target
6423   if (value == rsp) return; // Stack-based value // TODO: Handle this.
6424 
6425   // This method temporarily destroys dst and value, but always pushes
6426   // the original values on stack, and restores them on exit.
6427 
6428   Register tmp = NULL;
6429   if (value != rscratch1 && dst != rscratch1) {
6430     tmp = rscratch1;
6431   } else if (value != rscratch2 && dst != rscratch2) {
6432     tmp = rscratch2;
6433   } else if (value != r9 && dst != r9) {
6434     tmp = r9;
6435   } else {
6436     guarantee(false, "able to select the temp register");
6437   }
6438 
6439   // Push tmp regs and flags.
6440   pushf();
6441   push(dst);
6442   push(value);
6443   push(tmp);
6444 
6445   Label done;
6446 
6447   if (ShenandoahUpdateRefsEarly) {
6448     // Do value-check only when update refs is in progress.
6449     movptr(tmp, (intptr_t) ShenandoahHeap::update_refs_in_progress_addr());
6450   } else {
6451     // Do value-check only when concurrent mark is in progress.
6452     movptr(tmp, (intptr_t) ShenandoahHeap::concurrent_mark_in_progress_addr());
6453   }
6454   movbool(tmp, Address(tmp, 0));
6455   testbool(tmp);
6456   jcc(Assembler::zero, done);
6457 
6458   // Null-check dst.
6459   testptr(dst, dst);
6460   jcc(Assembler::zero, done);
6461 
6462   // Check that dst is in heap.
6463   // Rationale: we accept offheap writes to roots, because we will fix them up
6464   // as needed later. Non-root offheap writes are unsafe anyway, allow them.
6465   shenandoah_in_heap_check(dst, tmp, done);
6466 
6467   // Null-check value.
6468   testptr(value, value);
6469   jcc(Assembler::zero, done);
6470 
6471   // Test that value oop is not in to-space.
6472   shenandoah_cset_check(value, tmp, done);
6473 
6474   // Fail.
6475   pop(tmp);
6476   pop(value);
6477   pop(dst);
6478   popf();
6479 
6480   // Stop, provoke SEGV.
6481   // Shortest way to fail VM with RIP pointing to this check.
6482   // Store value register to clearly see what had failed.
6483   lea(tmp, ExternalAddress(badAddress));
6484   movptr(Address(tmp, 0), value);
6485   hlt();
6486 
6487   bind(done);
6488 
6489   // Pop tmp regs and flags.
6490   pop(tmp);
6491   pop(value);
6492   pop(dst);
6493   popf();
6494 }
6495 
6496 void MacroAssembler::shenandoah_store_val_check(Address addr, Register value) {
6497   shenandoah_store_val_check(addr.base(), value);
6498 }
6499 
6500 void MacroAssembler::shenandoah_lock_check(Register dst) {
6501 #ifdef ASSERT
6502   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6503 
6504   push(r8);
6505   movptr(r8, Address(dst, BasicObjectLock::obj_offset_in_bytes()));
6506   shenandoah_store_addr_check(r8);
6507   pop(r8);
6508 #endif
6509 }
6510 #endif // _LP64
6511 
6512 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6513                                                       Register tmp,
6514                                                       int offset) {
6515   intptr_t value = *delayed_value_addr;
6516   if (value != 0)
6517     return RegisterOrConstant(value + offset);
6518 
6519   // load indirectly to solve generation ordering problem
6520   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6521 
6522 #ifdef ASSERT
6523   { Label L;
6524     testptr(tmp, tmp);
6525     if (WizardMode) {
6526       const char* buf = NULL;
6527       {
6528         ResourceMark rm;
6529         stringStream ss;
6530         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6531         buf = code_string(ss.as_string());
6532       }
6533       jcc(Assembler::notZero, L);
6534       STOP(buf);
6535     } else {
6536       jccb(Assembler::notZero, L);
6537       hlt();
6538     }
6539     bind(L);
6540   }
6541 #endif
6542 
6543   if (offset != 0)
6544     addptr(tmp, offset);
6545 
6546   return RegisterOrConstant(tmp);
6547 }
6548 
6549 
6550 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6551                                          int extra_slot_offset) {
6552   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6553   int stackElementSize = Interpreter::stackElementSize;
6554   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6555 #ifdef ASSERT
6556   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6557   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6558 #endif
6559   Register             scale_reg    = noreg;
6560   Address::ScaleFactor scale_factor = Address::no_scale;
6561   if (arg_slot.is_constant()) {
6562     offset += arg_slot.as_constant() * stackElementSize;
6563   } else {
6564     scale_reg    = arg_slot.as_register();
6565     scale_factor = Address::times(stackElementSize);
6566   }
6567   offset += wordSize;           // return PC is on stack
6568   return Address(rsp, scale_reg, scale_factor, offset);
6569 }
6570 
6571 
6572 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6573   if (!VerifyOops) return;
6574 
6575   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6576   // Pass register number to verify_oop_subroutine
6577   const char* b = NULL;
6578   {
6579     ResourceMark rm;
6580     stringStream ss;
6581     ss.print("verify_oop_addr: %s", s);
6582     b = code_string(ss.as_string());
6583   }
6584 #ifdef _LP64
6585   push(rscratch1);                    // save r10, trashed by movptr()
6586 #endif
6587   push(rax);                          // save rax,
6588   // addr may contain rsp so we will have to adjust it based on the push
6589   // we just did (and on 64 bit we do two pushes)
6590   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6591   // stores rax into addr which is backwards of what was intended.
6592   if (addr.uses(rsp)) {
6593     lea(rax, addr);
6594     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6595   } else {
6596     pushptr(addr);
6597   }
6598 
6599   ExternalAddress buffer((address) b);
6600   // pass msg argument
6601   // avoid using pushptr, as it modifies scratch registers
6602   // and our contract is not to modify anything
6603   movptr(rax, buffer.addr());
6604   push(rax);
6605 
6606   // call indirectly to solve generation ordering problem
6607   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6608   call(rax);
6609   // Caller pops the arguments (addr, message) and restores rax, r10.
6610 }
6611 
6612 void MacroAssembler::verify_tlab() {
6613 #ifdef ASSERT
6614   if (UseTLAB && VerifyOops) {
6615     Label next, ok;
6616     Register t1 = rsi;
6617     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6618 
6619     push(t1);
6620     NOT_LP64(push(thread_reg));
6621     NOT_LP64(get_thread(thread_reg));
6622 
6623     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6624     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6625     jcc(Assembler::aboveEqual, next);
6626     STOP("assert(top >= start)");
6627     should_not_reach_here();
6628 
6629     bind(next);
6630     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6631     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6632     jcc(Assembler::aboveEqual, ok);
6633     STOP("assert(top <= end)");
6634     should_not_reach_here();
6635 
6636     bind(ok);
6637     NOT_LP64(pop(thread_reg));
6638     pop(t1);
6639   }
6640 #endif
6641 }
6642 
6643 class ControlWord {
6644  public:
6645   int32_t _value;
6646 
6647   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6648   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6649   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6650   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6651   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6652   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6653   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6654   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6655 
6656   void print() const {
6657     // rounding control
6658     const char* rc;
6659     switch (rounding_control()) {
6660       case 0: rc = "round near"; break;
6661       case 1: rc = "round down"; break;
6662       case 2: rc = "round up  "; break;
6663       case 3: rc = "chop      "; break;
6664     };
6665     // precision control
6666     const char* pc;
6667     switch (precision_control()) {
6668       case 0: pc = "24 bits "; break;
6669       case 1: pc = "reserved"; break;
6670       case 2: pc = "53 bits "; break;
6671       case 3: pc = "64 bits "; break;
6672     };
6673     // flags
6674     char f[9];
6675     f[0] = ' ';
6676     f[1] = ' ';
6677     f[2] = (precision   ()) ? 'P' : 'p';
6678     f[3] = (underflow   ()) ? 'U' : 'u';
6679     f[4] = (overflow    ()) ? 'O' : 'o';
6680     f[5] = (zero_divide ()) ? 'Z' : 'z';
6681     f[6] = (denormalized()) ? 'D' : 'd';
6682     f[7] = (invalid     ()) ? 'I' : 'i';
6683     f[8] = '\x0';
6684     // output
6685     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6686   }
6687 
6688 };
6689 
6690 class StatusWord {
6691  public:
6692   int32_t _value;
6693 
6694   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6695   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6696   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6697   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6698   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6699   int  top() const                     { return  (_value >> 11) & 7      ; }
6700   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6701   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6702   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6703   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6704   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6705   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6706   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6707   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6708 
6709   void print() const {
6710     // condition codes
6711     char c[5];
6712     c[0] = (C3()) ? '3' : '-';
6713     c[1] = (C2()) ? '2' : '-';
6714     c[2] = (C1()) ? '1' : '-';
6715     c[3] = (C0()) ? '0' : '-';
6716     c[4] = '\x0';
6717     // flags
6718     char f[9];
6719     f[0] = (error_status()) ? 'E' : '-';
6720     f[1] = (stack_fault ()) ? 'S' : '-';
6721     f[2] = (precision   ()) ? 'P' : '-';
6722     f[3] = (underflow   ()) ? 'U' : '-';
6723     f[4] = (overflow    ()) ? 'O' : '-';
6724     f[5] = (zero_divide ()) ? 'Z' : '-';
6725     f[6] = (denormalized()) ? 'D' : '-';
6726     f[7] = (invalid     ()) ? 'I' : '-';
6727     f[8] = '\x0';
6728     // output
6729     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6730   }
6731 
6732 };
6733 
6734 class TagWord {
6735  public:
6736   int32_t _value;
6737 
6738   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6739 
6740   void print() const {
6741     printf("%04x", _value & 0xFFFF);
6742   }
6743 
6744 };
6745 
6746 class FPU_Register {
6747  public:
6748   int32_t _m0;
6749   int32_t _m1;
6750   int16_t _ex;
6751 
6752   bool is_indefinite() const           {
6753     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6754   }
6755 
6756   void print() const {
6757     char  sign = (_ex < 0) ? '-' : '+';
6758     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6759     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6760   };
6761 
6762 };
6763 
6764 class FPU_State {
6765  public:
6766   enum {
6767     register_size       = 10,
6768     number_of_registers =  8,
6769     register_mask       =  7
6770   };
6771 
6772   ControlWord  _control_word;
6773   StatusWord   _status_word;
6774   TagWord      _tag_word;
6775   int32_t      _error_offset;
6776   int32_t      _error_selector;
6777   int32_t      _data_offset;
6778   int32_t      _data_selector;
6779   int8_t       _register[register_size * number_of_registers];
6780 
6781   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6782   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6783 
6784   const char* tag_as_string(int tag) const {
6785     switch (tag) {
6786       case 0: return "valid";
6787       case 1: return "zero";
6788       case 2: return "special";
6789       case 3: return "empty";
6790     }
6791     ShouldNotReachHere();
6792     return NULL;
6793   }
6794 
6795   void print() const {
6796     // print computation registers
6797     { int t = _status_word.top();
6798       for (int i = 0; i < number_of_registers; i++) {
6799         int j = (i - t) & register_mask;
6800         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6801         st(j)->print();
6802         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6803       }
6804     }
6805     printf("\n");
6806     // print control registers
6807     printf("ctrl = "); _control_word.print(); printf("\n");
6808     printf("stat = "); _status_word .print(); printf("\n");
6809     printf("tags = "); _tag_word    .print(); printf("\n");
6810   }
6811 
6812 };
6813 
6814 class Flag_Register {
6815  public:
6816   int32_t _value;
6817 
6818   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6819   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6820   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6821   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6822   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6823   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6824   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6825 
6826   void print() const {
6827     // flags
6828     char f[8];
6829     f[0] = (overflow       ()) ? 'O' : '-';
6830     f[1] = (direction      ()) ? 'D' : '-';
6831     f[2] = (sign           ()) ? 'S' : '-';
6832     f[3] = (zero           ()) ? 'Z' : '-';
6833     f[4] = (auxiliary_carry()) ? 'A' : '-';
6834     f[5] = (parity         ()) ? 'P' : '-';
6835     f[6] = (carry          ()) ? 'C' : '-';
6836     f[7] = '\x0';
6837     // output
6838     printf("%08x  flags = %s", _value, f);
6839   }
6840 
6841 };
6842 
6843 class IU_Register {
6844  public:
6845   int32_t _value;
6846 
6847   void print() const {
6848     printf("%08x  %11d", _value, _value);
6849   }
6850 
6851 };
6852 
6853 class IU_State {
6854  public:
6855   Flag_Register _eflags;
6856   IU_Register   _rdi;
6857   IU_Register   _rsi;
6858   IU_Register   _rbp;
6859   IU_Register   _rsp;
6860   IU_Register   _rbx;
6861   IU_Register   _rdx;
6862   IU_Register   _rcx;
6863   IU_Register   _rax;
6864 
6865   void print() const {
6866     // computation registers
6867     printf("rax,  = "); _rax.print(); printf("\n");
6868     printf("rbx,  = "); _rbx.print(); printf("\n");
6869     printf("rcx  = "); _rcx.print(); printf("\n");
6870     printf("rdx  = "); _rdx.print(); printf("\n");
6871     printf("rdi  = "); _rdi.print(); printf("\n");
6872     printf("rsi  = "); _rsi.print(); printf("\n");
6873     printf("rbp,  = "); _rbp.print(); printf("\n");
6874     printf("rsp  = "); _rsp.print(); printf("\n");
6875     printf("\n");
6876     // control registers
6877     printf("flgs = "); _eflags.print(); printf("\n");
6878   }
6879 };
6880 
6881 
6882 class CPU_State {
6883  public:
6884   FPU_State _fpu_state;
6885   IU_State  _iu_state;
6886 
6887   void print() const {
6888     printf("--------------------------------------------------\n");
6889     _iu_state .print();
6890     printf("\n");
6891     _fpu_state.print();
6892     printf("--------------------------------------------------\n");
6893   }
6894 
6895 };
6896 
6897 
6898 static void _print_CPU_state(CPU_State* state) {
6899   state->print();
6900 };
6901 
6902 
6903 void MacroAssembler::print_CPU_state() {
6904   push_CPU_state();
6905   push(rsp);                // pass CPU state
6906   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6907   addptr(rsp, wordSize);       // discard argument
6908   pop_CPU_state();
6909 }
6910 
6911 
6912 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6913   static int counter = 0;
6914   FPU_State* fs = &state->_fpu_state;
6915   counter++;
6916   // For leaf calls, only verify that the top few elements remain empty.
6917   // We only need 1 empty at the top for C2 code.
6918   if( stack_depth < 0 ) {
6919     if( fs->tag_for_st(7) != 3 ) {
6920       printf("FPR7 not empty\n");
6921       state->print();
6922       assert(false, "error");
6923       return false;
6924     }
6925     return true;                // All other stack states do not matter
6926   }
6927 
6928   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6929          "bad FPU control word");
6930 
6931   // compute stack depth
6932   int i = 0;
6933   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6934   int d = i;
6935   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6936   // verify findings
6937   if (i != FPU_State::number_of_registers) {
6938     // stack not contiguous
6939     printf("%s: stack not contiguous at ST%d\n", s, i);
6940     state->print();
6941     assert(false, "error");
6942     return false;
6943   }
6944   // check if computed stack depth corresponds to expected stack depth
6945   if (stack_depth < 0) {
6946     // expected stack depth is -stack_depth or less
6947     if (d > -stack_depth) {
6948       // too many elements on the stack
6949       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6950       state->print();
6951       assert(false, "error");
6952       return false;
6953     }
6954   } else {
6955     // expected stack depth is stack_depth
6956     if (d != stack_depth) {
6957       // wrong stack depth
6958       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6959       state->print();
6960       assert(false, "error");
6961       return false;
6962     }
6963   }
6964   // everything is cool
6965   return true;
6966 }
6967 
6968 
6969 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6970   if (!VerifyFPU) return;
6971   push_CPU_state();
6972   push(rsp);                // pass CPU state
6973   ExternalAddress msg((address) s);
6974   // pass message string s
6975   pushptr(msg.addr());
6976   push(stack_depth);        // pass stack depth
6977   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6978   addptr(rsp, 3 * wordSize);   // discard arguments
6979   // check for error
6980   { Label L;
6981     testl(rax, rax);
6982     jcc(Assembler::notZero, L);
6983     int3();                  // break if error condition
6984     bind(L);
6985   }
6986   pop_CPU_state();
6987 }
6988 
6989 void MacroAssembler::restore_cpu_control_state_after_jni() {
6990   // Either restore the MXCSR register after returning from the JNI Call
6991   // or verify that it wasn't changed (with -Xcheck:jni flag).
6992   if (VM_Version::supports_sse()) {
6993     if (RestoreMXCSROnJNICalls) {
6994       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6995     } else if (CheckJNICalls) {
6996       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6997     }
6998   }
6999   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
7000   vzeroupper();
7001 
7002 #ifndef _LP64
7003   // Either restore the x87 floating pointer control word after returning
7004   // from the JNI call or verify that it wasn't changed.
7005   if (CheckJNICalls) {
7006     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
7007   }
7008 #endif // _LP64
7009 }
7010 
7011 void MacroAssembler::load_mirror(Register mirror, Register method) {
7012   // get mirror
7013   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
7014   movptr(mirror, Address(method, Method::const_offset()));
7015   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
7016   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
7017   movptr(mirror, Address(mirror, mirror_offset));
7018 }
7019 
7020 void MacroAssembler::load_klass(Register dst, Register src) {
7021 #ifdef _LP64
7022   if (UseCompressedClassPointers) {
7023     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
7024     decode_klass_not_null(dst);
7025   } else
7026 #endif
7027     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
7028 }
7029 
7030 void MacroAssembler::load_prototype_header(Register dst, Register src) {
7031   load_klass(dst, src);
7032   movptr(dst, Address(dst, Klass::prototype_header_offset()));
7033 }
7034 
7035 void MacroAssembler::store_klass(Register dst, Register src) {
7036 #ifdef _LP64
7037   if (UseCompressedClassPointers) {
7038     encode_klass_not_null(src);
7039     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
7040   } else
7041 #endif
7042     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
7043 }
7044 
7045 void MacroAssembler::load_heap_oop(Register dst, Address src) {
7046 #ifdef _LP64
7047   // FIXME: Must change all places where we try to load the klass.
7048   if (UseCompressedOops) {
7049     movl(dst, src);
7050     decode_heap_oop(dst);
7051   } else
7052 #endif
7053     movptr(dst, src);
7054 }
7055 
7056 // Doesn't do verfication, generates fixed size code
7057 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
7058 #ifdef _LP64
7059   if (UseCompressedOops) {
7060     movl(dst, src);
7061     decode_heap_oop_not_null(dst);
7062   } else
7063 #endif
7064     movptr(dst, src);
7065 }
7066 
7067 void MacroAssembler::store_heap_oop(Address dst, Register src) {
7068 #ifdef _LP64
7069   if (UseCompressedOops) {
7070     assert(!dst.uses(src), "not enough registers");
7071     encode_heap_oop(src);
7072     movl(dst, src);
7073   } else
7074 #endif
7075     movptr(dst, src);
7076 }
7077 
7078 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
7079   assert_different_registers(src1, tmp);
7080 #ifdef _LP64
7081   if (UseCompressedOops) {
7082     bool did_push = false;
7083     if (tmp == noreg) {
7084       tmp = rax;
7085       push(tmp);
7086       did_push = true;
7087       assert(!src2.uses(rsp), "can't push");
7088     }
7089     load_heap_oop(tmp, src2);
7090     cmpptr(src1, tmp);
7091     if (did_push)  pop(tmp);
7092   } else
7093 #endif
7094     cmpptr(src1, src2);
7095 }
7096 
7097 // Used for storing NULLs.
7098 void MacroAssembler::store_heap_oop_null(Address dst) {
7099 #ifdef _LP64
7100   if (UseCompressedOops) {
7101     movl(dst, (int32_t)NULL_WORD);
7102   } else {
7103     movslq(dst, (int32_t)NULL_WORD);
7104   }
7105 #else
7106   movl(dst, (int32_t)NULL_WORD);
7107 #endif
7108 }
7109 
7110 #ifdef _LP64
7111 void MacroAssembler::store_klass_gap(Register dst, Register src) {
7112   if (UseCompressedClassPointers) {
7113     // Store to klass gap in destination
7114     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
7115   }
7116 }
7117 
7118 #ifdef ASSERT
7119 void MacroAssembler::verify_heapbase(const char* msg) {
7120   assert (UseCompressedOops, "should be compressed");
7121   assert (Universe::heap() != NULL, "java heap should be initialized");
7122   if (CheckCompressedOops) {
7123     Label ok;
7124     push(rscratch1); // cmpptr trashes rscratch1
7125     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7126     jcc(Assembler::equal, ok);
7127     STOP(msg);
7128     bind(ok);
7129     pop(rscratch1);
7130   }
7131 }
7132 #endif
7133 
7134 // Algorithm must match oop.inline.hpp encode_heap_oop.
7135 void MacroAssembler::encode_heap_oop(Register r) {
7136 #ifdef ASSERT
7137   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
7138 #endif
7139   verify_oop(r, "broken oop in encode_heap_oop");
7140   if (Universe::narrow_oop_base() == NULL) {
7141     if (Universe::narrow_oop_shift() != 0) {
7142       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7143       shrq(r, LogMinObjAlignmentInBytes);
7144     }
7145     return;
7146   }
7147   testq(r, r);
7148   cmovq(Assembler::equal, r, r12_heapbase);
7149   subq(r, r12_heapbase);
7150   shrq(r, LogMinObjAlignmentInBytes);
7151 }
7152 
7153 void MacroAssembler::encode_heap_oop_not_null(Register r) {
7154 #ifdef ASSERT
7155   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
7156   if (CheckCompressedOops) {
7157     Label ok;
7158     testq(r, r);
7159     jcc(Assembler::notEqual, ok);
7160     STOP("null oop passed to encode_heap_oop_not_null");
7161     bind(ok);
7162   }
7163 #endif
7164   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7165   if (Universe::narrow_oop_base() != NULL) {
7166     subq(r, r12_heapbase);
7167   }
7168   if (Universe::narrow_oop_shift() != 0) {
7169     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7170     shrq(r, LogMinObjAlignmentInBytes);
7171   }
7172 }
7173 
7174 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7175 #ifdef ASSERT
7176   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7177   if (CheckCompressedOops) {
7178     Label ok;
7179     testq(src, src);
7180     jcc(Assembler::notEqual, ok);
7181     STOP("null oop passed to encode_heap_oop_not_null2");
7182     bind(ok);
7183   }
7184 #endif
7185   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7186   if (dst != src) {
7187     movq(dst, src);
7188   }
7189   if (Universe::narrow_oop_base() != NULL) {
7190     subq(dst, r12_heapbase);
7191   }
7192   if (Universe::narrow_oop_shift() != 0) {
7193     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7194     shrq(dst, LogMinObjAlignmentInBytes);
7195   }
7196 }
7197 
7198 void  MacroAssembler::decode_heap_oop(Register r) {
7199 #ifdef ASSERT
7200   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7201 #endif
7202   if (Universe::narrow_oop_base() == NULL) {
7203     if (Universe::narrow_oop_shift() != 0) {
7204       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7205       shlq(r, LogMinObjAlignmentInBytes);
7206     }
7207   } else {
7208     Label done;
7209     shlq(r, LogMinObjAlignmentInBytes);
7210     jccb(Assembler::equal, done);
7211     addq(r, r12_heapbase);
7212     bind(done);
7213   }
7214   verify_oop(r, "broken oop in decode_heap_oop");
7215 }
7216 
7217 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7218   // Note: it will change flags
7219   assert (UseCompressedOops, "should only be used for compressed headers");
7220   assert (Universe::heap() != NULL, "java heap should be initialized");
7221   // Cannot assert, unverified entry point counts instructions (see .ad file)
7222   // vtableStubs also counts instructions in pd_code_size_limit.
7223   // Also do not verify_oop as this is called by verify_oop.
7224   if (Universe::narrow_oop_shift() != 0) {
7225     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7226     shlq(r, LogMinObjAlignmentInBytes);
7227     if (Universe::narrow_oop_base() != NULL) {
7228       addq(r, r12_heapbase);
7229     }
7230   } else {
7231     assert (Universe::narrow_oop_base() == NULL, "sanity");
7232   }
7233 }
7234 
7235 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7236   // Note: it will change flags
7237   assert (UseCompressedOops, "should only be used for compressed headers");
7238   assert (Universe::heap() != NULL, "java heap should be initialized");
7239   // Cannot assert, unverified entry point counts instructions (see .ad file)
7240   // vtableStubs also counts instructions in pd_code_size_limit.
7241   // Also do not verify_oop as this is called by verify_oop.
7242   if (Universe::narrow_oop_shift() != 0) {
7243     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7244     if (LogMinObjAlignmentInBytes == Address::times_8) {
7245       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7246     } else {
7247       if (dst != src) {
7248         movq(dst, src);
7249       }
7250       shlq(dst, LogMinObjAlignmentInBytes);
7251       if (Universe::narrow_oop_base() != NULL) {
7252         addq(dst, r12_heapbase);
7253       }
7254     }
7255   } else {
7256     assert (Universe::narrow_oop_base() == NULL, "sanity");
7257     if (dst != src) {
7258       movq(dst, src);
7259     }
7260   }
7261 }
7262 
7263 void MacroAssembler::encode_klass_not_null(Register r) {
7264   if (Universe::narrow_klass_base() != NULL) {
7265     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7266     assert(r != r12_heapbase, "Encoding a klass in r12");
7267     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7268     subq(r, r12_heapbase);
7269   }
7270   if (Universe::narrow_klass_shift() != 0) {
7271     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7272     shrq(r, LogKlassAlignmentInBytes);
7273   }
7274   if (Universe::narrow_klass_base() != NULL) {
7275     reinit_heapbase();
7276   }
7277 }
7278 
7279 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7280   if (dst == src) {
7281     encode_klass_not_null(src);
7282   } else {
7283     if (Universe::narrow_klass_base() != NULL) {
7284       mov64(dst, (int64_t)Universe::narrow_klass_base());
7285       negq(dst);
7286       addq(dst, src);
7287     } else {
7288       movptr(dst, src);
7289     }
7290     if (Universe::narrow_klass_shift() != 0) {
7291       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7292       shrq(dst, LogKlassAlignmentInBytes);
7293     }
7294   }
7295 }
7296 
7297 // Function instr_size_for_decode_klass_not_null() counts the instructions
7298 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7299 // when (Universe::heap() != NULL).  Hence, if the instructions they
7300 // generate change, then this method needs to be updated.
7301 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7302   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7303   if (Universe::narrow_klass_base() != NULL) {
7304     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7305     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7306   } else {
7307     // longest load decode klass function, mov64, leaq
7308     return 16;
7309   }
7310 }
7311 
7312 // !!! If the instructions that get generated here change then function
7313 // instr_size_for_decode_klass_not_null() needs to get updated.
7314 void  MacroAssembler::decode_klass_not_null(Register r) {
7315   // Note: it will change flags
7316   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7317   assert(r != r12_heapbase, "Decoding a klass in r12");
7318   // Cannot assert, unverified entry point counts instructions (see .ad file)
7319   // vtableStubs also counts instructions in pd_code_size_limit.
7320   // Also do not verify_oop as this is called by verify_oop.
7321   if (Universe::narrow_klass_shift() != 0) {
7322     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7323     shlq(r, LogKlassAlignmentInBytes);
7324   }
7325   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7326   if (Universe::narrow_klass_base() != NULL) {
7327     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7328     addq(r, r12_heapbase);
7329     reinit_heapbase();
7330   }
7331 }
7332 
7333 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7334   // Note: it will change flags
7335   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7336   if (dst == src) {
7337     decode_klass_not_null(dst);
7338   } else {
7339     // Cannot assert, unverified entry point counts instructions (see .ad file)
7340     // vtableStubs also counts instructions in pd_code_size_limit.
7341     // Also do not verify_oop as this is called by verify_oop.
7342     mov64(dst, (int64_t)Universe::narrow_klass_base());
7343     if (Universe::narrow_klass_shift() != 0) {
7344       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7345       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7346       leaq(dst, Address(dst, src, Address::times_8, 0));
7347     } else {
7348       addq(dst, src);
7349     }
7350   }
7351 }
7352 
7353 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7354   assert (UseCompressedOops, "should only be used for compressed headers");
7355   assert (Universe::heap() != NULL, "java heap should be initialized");
7356   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7357   int oop_index = oop_recorder()->find_index(obj);
7358   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7359   mov_narrow_oop(dst, oop_index, rspec);
7360 }
7361 
7362 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7363   assert (UseCompressedOops, "should only be used for compressed headers");
7364   assert (Universe::heap() != NULL, "java heap should be initialized");
7365   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7366   int oop_index = oop_recorder()->find_index(obj);
7367   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7368   mov_narrow_oop(dst, oop_index, rspec);
7369 }
7370 
7371 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7372   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7373   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7374   int klass_index = oop_recorder()->find_index(k);
7375   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7376   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7377 }
7378 
7379 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7380   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7381   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7382   int klass_index = oop_recorder()->find_index(k);
7383   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7384   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7385 }
7386 
7387 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7388   assert (UseCompressedOops, "should only be used for compressed headers");
7389   assert (Universe::heap() != NULL, "java heap should be initialized");
7390   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7391   int oop_index = oop_recorder()->find_index(obj);
7392   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7393   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7394 }
7395 
7396 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7397   assert (UseCompressedOops, "should only be used for compressed headers");
7398   assert (Universe::heap() != NULL, "java heap should be initialized");
7399   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7400   int oop_index = oop_recorder()->find_index(obj);
7401   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7402   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7403 }
7404 
7405 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7406   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7407   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7408   int klass_index = oop_recorder()->find_index(k);
7409   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7410   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7411 }
7412 
7413 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7414   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7415   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7416   int klass_index = oop_recorder()->find_index(k);
7417   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7418   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7419 }
7420 
7421 void MacroAssembler::reinit_heapbase() {
7422   if (UseCompressedOops || UseCompressedClassPointers) {
7423     if (Universe::heap() != NULL) {
7424       if (Universe::narrow_oop_base() == NULL) {
7425         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7426       } else {
7427         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7428       }
7429     } else {
7430       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7431     }
7432   }
7433 }
7434 
7435 #endif // _LP64
7436 
7437 
7438 // C2 compiled method's prolog code.
7439 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7440 
7441   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7442   // NativeJump::patch_verified_entry will be able to patch out the entry
7443   // code safely. The push to verify stack depth is ok at 5 bytes,
7444   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7445   // stack bang then we must use the 6 byte frame allocation even if
7446   // we have no frame. :-(
7447   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7448 
7449   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7450   // Remove word for return addr
7451   framesize -= wordSize;
7452   stack_bang_size -= wordSize;
7453 
7454   // Calls to C2R adapters often do not accept exceptional returns.
7455   // We require that their callers must bang for them.  But be careful, because
7456   // some VM calls (such as call site linkage) can use several kilobytes of
7457   // stack.  But the stack safety zone should account for that.
7458   // See bugs 4446381, 4468289, 4497237.
7459   if (stack_bang_size > 0) {
7460     generate_stack_overflow_check(stack_bang_size);
7461 
7462     // We always push rbp, so that on return to interpreter rbp, will be
7463     // restored correctly and we can correct the stack.
7464     push(rbp);
7465     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7466     if (PreserveFramePointer) {
7467       mov(rbp, rsp);
7468     }
7469     // Remove word for ebp
7470     framesize -= wordSize;
7471 
7472     // Create frame
7473     if (framesize) {
7474       subptr(rsp, framesize);
7475     }
7476   } else {
7477     // Create frame (force generation of a 4 byte immediate value)
7478     subptr_imm32(rsp, framesize);
7479 
7480     // Save RBP register now.
7481     framesize -= wordSize;
7482     movptr(Address(rsp, framesize), rbp);
7483     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7484     if (PreserveFramePointer) {
7485       movptr(rbp, rsp);
7486       if (framesize > 0) {
7487         addptr(rbp, framesize);
7488       }
7489     }
7490   }
7491 
7492   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7493     framesize -= wordSize;
7494     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7495   }
7496 
7497 #ifndef _LP64
7498   // If method sets FPU control word do it now
7499   if (fp_mode_24b) {
7500     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7501   }
7502   if (UseSSE >= 2 && VerifyFPU) {
7503     verify_FPU(0, "FPU stack must be clean on entry");
7504   }
7505 #endif
7506 
7507 #ifdef ASSERT
7508   if (VerifyStackAtCalls) {
7509     Label L;
7510     push(rax);
7511     mov(rax, rsp);
7512     andptr(rax, StackAlignmentInBytes-1);
7513     cmpptr(rax, StackAlignmentInBytes-wordSize);
7514     pop(rax);
7515     jcc(Assembler::equal, L);
7516     STOP("Stack is not properly aligned!");
7517     bind(L);
7518   }
7519 #endif
7520 
7521 }
7522 
7523 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7524   // cnt - number of qwords (8-byte words).
7525   // base - start address, qword aligned.
7526   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7527   assert(base==rdi, "base register must be edi for rep stos");
7528   assert(tmp==rax,   "tmp register must be eax for rep stos");
7529   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7530   assert(InitArrayShortSize % BytesPerLong == 0,
7531     "InitArrayShortSize should be the multiple of BytesPerLong");
7532 
7533   Label DONE;
7534 
7535   xorptr(tmp, tmp);
7536 
7537   if (!is_large) {
7538     Label LOOP, LONG;
7539     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7540     jccb(Assembler::greater, LONG);
7541 
7542     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7543 
7544     decrement(cnt);
7545     jccb(Assembler::negative, DONE); // Zero length
7546 
7547     // Use individual pointer-sized stores for small counts:
7548     BIND(LOOP);
7549     movptr(Address(base, cnt, Address::times_ptr), tmp);
7550     decrement(cnt);
7551     jccb(Assembler::greaterEqual, LOOP);
7552     jmpb(DONE);
7553 
7554     BIND(LONG);
7555   }
7556 
7557   // Use longer rep-prefixed ops for non-small counts:
7558   if (UseFastStosb) {
7559     shlptr(cnt, 3); // convert to number of bytes
7560     rep_stosb();
7561   } else {
7562     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7563     rep_stos();
7564   }
7565 
7566   BIND(DONE);
7567 }
7568 
7569 #ifdef COMPILER2
7570 
7571 // IndexOf for constant substrings with size >= 8 chars
7572 // which don't need to be loaded through stack.
7573 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7574                                       Register cnt1, Register cnt2,
7575                                       int int_cnt2,  Register result,
7576                                       XMMRegister vec, Register tmp,
7577                                       int ae) {
7578   ShortBranchVerifier sbv(this);
7579   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7580   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7581 
7582   // This method uses the pcmpestri instruction with bound registers
7583   //   inputs:
7584   //     xmm - substring
7585   //     rax - substring length (elements count)
7586   //     mem - scanned string
7587   //     rdx - string length (elements count)
7588   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7589   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7590   //   outputs:
7591   //     rcx - matched index in string
7592   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7593   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7594   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7595   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7596   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7597 
7598   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7599         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7600         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7601 
7602   // Note, inline_string_indexOf() generates checks:
7603   // if (substr.count > string.count) return -1;
7604   // if (substr.count == 0) return 0;
7605   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7606 
7607   // Load substring.
7608   if (ae == StrIntrinsicNode::UL) {
7609     pmovzxbw(vec, Address(str2, 0));
7610   } else {
7611     movdqu(vec, Address(str2, 0));
7612   }
7613   movl(cnt2, int_cnt2);
7614   movptr(result, str1); // string addr
7615 
7616   if (int_cnt2 > stride) {
7617     jmpb(SCAN_TO_SUBSTR);
7618 
7619     // Reload substr for rescan, this code
7620     // is executed only for large substrings (> 8 chars)
7621     bind(RELOAD_SUBSTR);
7622     if (ae == StrIntrinsicNode::UL) {
7623       pmovzxbw(vec, Address(str2, 0));
7624     } else {
7625       movdqu(vec, Address(str2, 0));
7626     }
7627     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7628 
7629     bind(RELOAD_STR);
7630     // We came here after the beginning of the substring was
7631     // matched but the rest of it was not so we need to search
7632     // again. Start from the next element after the previous match.
7633 
7634     // cnt2 is number of substring reminding elements and
7635     // cnt1 is number of string reminding elements when cmp failed.
7636     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7637     subl(cnt1, cnt2);
7638     addl(cnt1, int_cnt2);
7639     movl(cnt2, int_cnt2); // Now restore cnt2
7640 
7641     decrementl(cnt1);     // Shift to next element
7642     cmpl(cnt1, cnt2);
7643     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7644 
7645     addptr(result, (1<<scale1));
7646 
7647   } // (int_cnt2 > 8)
7648 
7649   // Scan string for start of substr in 16-byte vectors
7650   bind(SCAN_TO_SUBSTR);
7651   pcmpestri(vec, Address(result, 0), mode);
7652   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7653   subl(cnt1, stride);
7654   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7655   cmpl(cnt1, cnt2);
7656   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7657   addptr(result, 16);
7658   jmpb(SCAN_TO_SUBSTR);
7659 
7660   // Found a potential substr
7661   bind(FOUND_CANDIDATE);
7662   // Matched whole vector if first element matched (tmp(rcx) == 0).
7663   if (int_cnt2 == stride) {
7664     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7665   } else { // int_cnt2 > 8
7666     jccb(Assembler::overflow, FOUND_SUBSTR);
7667   }
7668   // After pcmpestri tmp(rcx) contains matched element index
7669   // Compute start addr of substr
7670   lea(result, Address(result, tmp, scale1));
7671 
7672   // Make sure string is still long enough
7673   subl(cnt1, tmp);
7674   cmpl(cnt1, cnt2);
7675   if (int_cnt2 == stride) {
7676     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7677   } else { // int_cnt2 > 8
7678     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7679   }
7680   // Left less then substring.
7681 
7682   bind(RET_NOT_FOUND);
7683   movl(result, -1);
7684   jmp(EXIT);
7685 
7686   if (int_cnt2 > stride) {
7687     // This code is optimized for the case when whole substring
7688     // is matched if its head is matched.
7689     bind(MATCH_SUBSTR_HEAD);
7690     pcmpestri(vec, Address(result, 0), mode);
7691     // Reload only string if does not match
7692     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7693 
7694     Label CONT_SCAN_SUBSTR;
7695     // Compare the rest of substring (> 8 chars).
7696     bind(FOUND_SUBSTR);
7697     // First 8 chars are already matched.
7698     negptr(cnt2);
7699     addptr(cnt2, stride);
7700 
7701     bind(SCAN_SUBSTR);
7702     subl(cnt1, stride);
7703     cmpl(cnt2, -stride); // Do not read beyond substring
7704     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7705     // Back-up strings to avoid reading beyond substring:
7706     // cnt1 = cnt1 - cnt2 + 8
7707     addl(cnt1, cnt2); // cnt2 is negative
7708     addl(cnt1, stride);
7709     movl(cnt2, stride); negptr(cnt2);
7710     bind(CONT_SCAN_SUBSTR);
7711     if (int_cnt2 < (int)G) {
7712       int tail_off1 = int_cnt2<<scale1;
7713       int tail_off2 = int_cnt2<<scale2;
7714       if (ae == StrIntrinsicNode::UL) {
7715         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7716       } else {
7717         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7718       }
7719       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7720     } else {
7721       // calculate index in register to avoid integer overflow (int_cnt2*2)
7722       movl(tmp, int_cnt2);
7723       addptr(tmp, cnt2);
7724       if (ae == StrIntrinsicNode::UL) {
7725         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7726       } else {
7727         movdqu(vec, Address(str2, tmp, scale2, 0));
7728       }
7729       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7730     }
7731     // Need to reload strings pointers if not matched whole vector
7732     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7733     addptr(cnt2, stride);
7734     jcc(Assembler::negative, SCAN_SUBSTR);
7735     // Fall through if found full substring
7736 
7737   } // (int_cnt2 > 8)
7738 
7739   bind(RET_FOUND);
7740   // Found result if we matched full small substring.
7741   // Compute substr offset
7742   subptr(result, str1);
7743   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7744     shrl(result, 1); // index
7745   }
7746   bind(EXIT);
7747 
7748 } // string_indexofC8
7749 
7750 // Small strings are loaded through stack if they cross page boundary.
7751 void MacroAssembler::string_indexof(Register str1, Register str2,
7752                                     Register cnt1, Register cnt2,
7753                                     int int_cnt2,  Register result,
7754                                     XMMRegister vec, Register tmp,
7755                                     int ae) {
7756   ShortBranchVerifier sbv(this);
7757   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7758   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7759 
7760   //
7761   // int_cnt2 is length of small (< 8 chars) constant substring
7762   // or (-1) for non constant substring in which case its length
7763   // is in cnt2 register.
7764   //
7765   // Note, inline_string_indexOf() generates checks:
7766   // if (substr.count > string.count) return -1;
7767   // if (substr.count == 0) return 0;
7768   //
7769   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7770   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7771   // This method uses the pcmpestri instruction with bound registers
7772   //   inputs:
7773   //     xmm - substring
7774   //     rax - substring length (elements count)
7775   //     mem - scanned string
7776   //     rdx - string length (elements count)
7777   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7778   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7779   //   outputs:
7780   //     rcx - matched index in string
7781   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7782   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7783   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7784   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7785 
7786   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7787         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7788         FOUND_CANDIDATE;
7789 
7790   { //========================================================
7791     // We don't know where these strings are located
7792     // and we can't read beyond them. Load them through stack.
7793     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7794 
7795     movptr(tmp, rsp); // save old SP
7796 
7797     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7798       if (int_cnt2 == (1>>scale2)) { // One byte
7799         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7800         load_unsigned_byte(result, Address(str2, 0));
7801         movdl(vec, result); // move 32 bits
7802       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7803         // Not enough header space in 32-bit VM: 12+3 = 15.
7804         movl(result, Address(str2, -1));
7805         shrl(result, 8);
7806         movdl(vec, result); // move 32 bits
7807       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7808         load_unsigned_short(result, Address(str2, 0));
7809         movdl(vec, result); // move 32 bits
7810       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7811         movdl(vec, Address(str2, 0)); // move 32 bits
7812       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7813         movq(vec, Address(str2, 0));  // move 64 bits
7814       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7815         // Array header size is 12 bytes in 32-bit VM
7816         // + 6 bytes for 3 chars == 18 bytes,
7817         // enough space to load vec and shift.
7818         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7819         if (ae == StrIntrinsicNode::UL) {
7820           int tail_off = int_cnt2-8;
7821           pmovzxbw(vec, Address(str2, tail_off));
7822           psrldq(vec, -2*tail_off);
7823         }
7824         else {
7825           int tail_off = int_cnt2*(1<<scale2);
7826           movdqu(vec, Address(str2, tail_off-16));
7827           psrldq(vec, 16-tail_off);
7828         }
7829       }
7830     } else { // not constant substring
7831       cmpl(cnt2, stride);
7832       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7833 
7834       // We can read beyond string if srt+16 does not cross page boundary
7835       // since heaps are aligned and mapped by pages.
7836       assert(os::vm_page_size() < (int)G, "default page should be small");
7837       movl(result, str2); // We need only low 32 bits
7838       andl(result, (os::vm_page_size()-1));
7839       cmpl(result, (os::vm_page_size()-16));
7840       jccb(Assembler::belowEqual, CHECK_STR);
7841 
7842       // Move small strings to stack to allow load 16 bytes into vec.
7843       subptr(rsp, 16);
7844       int stk_offset = wordSize-(1<<scale2);
7845       push(cnt2);
7846 
7847       bind(COPY_SUBSTR);
7848       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7849         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7850         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7851       } else if (ae == StrIntrinsicNode::UU) {
7852         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7853         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7854       }
7855       decrement(cnt2);
7856       jccb(Assembler::notZero, COPY_SUBSTR);
7857 
7858       pop(cnt2);
7859       movptr(str2, rsp);  // New substring address
7860     } // non constant
7861 
7862     bind(CHECK_STR);
7863     cmpl(cnt1, stride);
7864     jccb(Assembler::aboveEqual, BIG_STRINGS);
7865 
7866     // Check cross page boundary.
7867     movl(result, str1); // We need only low 32 bits
7868     andl(result, (os::vm_page_size()-1));
7869     cmpl(result, (os::vm_page_size()-16));
7870     jccb(Assembler::belowEqual, BIG_STRINGS);
7871 
7872     subptr(rsp, 16);
7873     int stk_offset = -(1<<scale1);
7874     if (int_cnt2 < 0) { // not constant
7875       push(cnt2);
7876       stk_offset += wordSize;
7877     }
7878     movl(cnt2, cnt1);
7879 
7880     bind(COPY_STR);
7881     if (ae == StrIntrinsicNode::LL) {
7882       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7883       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7884     } else {
7885       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7886       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7887     }
7888     decrement(cnt2);
7889     jccb(Assembler::notZero, COPY_STR);
7890 
7891     if (int_cnt2 < 0) { // not constant
7892       pop(cnt2);
7893     }
7894     movptr(str1, rsp);  // New string address
7895 
7896     bind(BIG_STRINGS);
7897     // Load substring.
7898     if (int_cnt2 < 0) { // -1
7899       if (ae == StrIntrinsicNode::UL) {
7900         pmovzxbw(vec, Address(str2, 0));
7901       } else {
7902         movdqu(vec, Address(str2, 0));
7903       }
7904       push(cnt2);       // substr count
7905       push(str2);       // substr addr
7906       push(str1);       // string addr
7907     } else {
7908       // Small (< 8 chars) constant substrings are loaded already.
7909       movl(cnt2, int_cnt2);
7910     }
7911     push(tmp);  // original SP
7912 
7913   } // Finished loading
7914 
7915   //========================================================
7916   // Start search
7917   //
7918 
7919   movptr(result, str1); // string addr
7920 
7921   if (int_cnt2  < 0) {  // Only for non constant substring
7922     jmpb(SCAN_TO_SUBSTR);
7923 
7924     // SP saved at sp+0
7925     // String saved at sp+1*wordSize
7926     // Substr saved at sp+2*wordSize
7927     // Substr count saved at sp+3*wordSize
7928 
7929     // Reload substr for rescan, this code
7930     // is executed only for large substrings (> 8 chars)
7931     bind(RELOAD_SUBSTR);
7932     movptr(str2, Address(rsp, 2*wordSize));
7933     movl(cnt2, Address(rsp, 3*wordSize));
7934     if (ae == StrIntrinsicNode::UL) {
7935       pmovzxbw(vec, Address(str2, 0));
7936     } else {
7937       movdqu(vec, Address(str2, 0));
7938     }
7939     // We came here after the beginning of the substring was
7940     // matched but the rest of it was not so we need to search
7941     // again. Start from the next element after the previous match.
7942     subptr(str1, result); // Restore counter
7943     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7944       shrl(str1, 1);
7945     }
7946     addl(cnt1, str1);
7947     decrementl(cnt1);   // Shift to next element
7948     cmpl(cnt1, cnt2);
7949     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7950 
7951     addptr(result, (1<<scale1));
7952   } // non constant
7953 
7954   // Scan string for start of substr in 16-byte vectors
7955   bind(SCAN_TO_SUBSTR);
7956   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7957   pcmpestri(vec, Address(result, 0), mode);
7958   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7959   subl(cnt1, stride);
7960   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7961   cmpl(cnt1, cnt2);
7962   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7963   addptr(result, 16);
7964 
7965   bind(ADJUST_STR);
7966   cmpl(cnt1, stride); // Do not read beyond string
7967   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7968   // Back-up string to avoid reading beyond string.
7969   lea(result, Address(result, cnt1, scale1, -16));
7970   movl(cnt1, stride);
7971   jmpb(SCAN_TO_SUBSTR);
7972 
7973   // Found a potential substr
7974   bind(FOUND_CANDIDATE);
7975   // After pcmpestri tmp(rcx) contains matched element index
7976 
7977   // Make sure string is still long enough
7978   subl(cnt1, tmp);
7979   cmpl(cnt1, cnt2);
7980   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7981   // Left less then substring.
7982 
7983   bind(RET_NOT_FOUND);
7984   movl(result, -1);
7985   jmpb(CLEANUP);
7986 
7987   bind(FOUND_SUBSTR);
7988   // Compute start addr of substr
7989   lea(result, Address(result, tmp, scale1));
7990   if (int_cnt2 > 0) { // Constant substring
7991     // Repeat search for small substring (< 8 chars)
7992     // from new point without reloading substring.
7993     // Have to check that we don't read beyond string.
7994     cmpl(tmp, stride-int_cnt2);
7995     jccb(Assembler::greater, ADJUST_STR);
7996     // Fall through if matched whole substring.
7997   } else { // non constant
7998     assert(int_cnt2 == -1, "should be != 0");
7999 
8000     addl(tmp, cnt2);
8001     // Found result if we matched whole substring.
8002     cmpl(tmp, stride);
8003     jccb(Assembler::lessEqual, RET_FOUND);
8004 
8005     // Repeat search for small substring (<= 8 chars)
8006     // from new point 'str1' without reloading substring.
8007     cmpl(cnt2, stride);
8008     // Have to check that we don't read beyond string.
8009     jccb(Assembler::lessEqual, ADJUST_STR);
8010 
8011     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
8012     // Compare the rest of substring (> 8 chars).
8013     movptr(str1, result);
8014 
8015     cmpl(tmp, cnt2);
8016     // First 8 chars are already matched.
8017     jccb(Assembler::equal, CHECK_NEXT);
8018 
8019     bind(SCAN_SUBSTR);
8020     pcmpestri(vec, Address(str1, 0), mode);
8021     // Need to reload strings pointers if not matched whole vector
8022     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
8023 
8024     bind(CHECK_NEXT);
8025     subl(cnt2, stride);
8026     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
8027     addptr(str1, 16);
8028     if (ae == StrIntrinsicNode::UL) {
8029       addptr(str2, 8);
8030     } else {
8031       addptr(str2, 16);
8032     }
8033     subl(cnt1, stride);
8034     cmpl(cnt2, stride); // Do not read beyond substring
8035     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
8036     // Back-up strings to avoid reading beyond substring.
8037 
8038     if (ae == StrIntrinsicNode::UL) {
8039       lea(str2, Address(str2, cnt2, scale2, -8));
8040       lea(str1, Address(str1, cnt2, scale1, -16));
8041     } else {
8042       lea(str2, Address(str2, cnt2, scale2, -16));
8043       lea(str1, Address(str1, cnt2, scale1, -16));
8044     }
8045     subl(cnt1, cnt2);
8046     movl(cnt2, stride);
8047     addl(cnt1, stride);
8048     bind(CONT_SCAN_SUBSTR);
8049     if (ae == StrIntrinsicNode::UL) {
8050       pmovzxbw(vec, Address(str2, 0));
8051     } else {
8052       movdqu(vec, Address(str2, 0));
8053     }
8054     jmp(SCAN_SUBSTR);
8055 
8056     bind(RET_FOUND_LONG);
8057     movptr(str1, Address(rsp, wordSize));
8058   } // non constant
8059 
8060   bind(RET_FOUND);
8061   // Compute substr offset
8062   subptr(result, str1);
8063   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
8064     shrl(result, 1); // index
8065   }
8066   bind(CLEANUP);
8067   pop(rsp); // restore SP
8068 
8069 } // string_indexof
8070 
8071 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
8072                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
8073   ShortBranchVerifier sbv(this);
8074   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
8075 
8076   int stride = 8;
8077 
8078   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
8079         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
8080         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
8081         FOUND_SEQ_CHAR, DONE_LABEL;
8082 
8083   movptr(result, str1);
8084   if (UseAVX >= 2) {
8085     cmpl(cnt1, stride);
8086     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8087     cmpl(cnt1, 2*stride);
8088     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
8089     movdl(vec1, ch);
8090     vpbroadcastw(vec1, vec1);
8091     vpxor(vec2, vec2);
8092     movl(tmp, cnt1);
8093     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
8094     andl(cnt1,0x0000000F);  //tail count (in chars)
8095 
8096     bind(SCAN_TO_16_CHAR_LOOP);
8097     vmovdqu(vec3, Address(result, 0));
8098     vpcmpeqw(vec3, vec3, vec1, 1);
8099     vptest(vec2, vec3);
8100     jcc(Assembler::carryClear, FOUND_CHAR);
8101     addptr(result, 32);
8102     subl(tmp, 2*stride);
8103     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
8104     jmp(SCAN_TO_8_CHAR);
8105     bind(SCAN_TO_8_CHAR_INIT);
8106     movdl(vec1, ch);
8107     pshuflw(vec1, vec1, 0x00);
8108     pshufd(vec1, vec1, 0);
8109     pxor(vec2, vec2);
8110   }
8111   bind(SCAN_TO_8_CHAR);
8112   cmpl(cnt1, stride);
8113   if (UseAVX >= 2) {
8114     jcc(Assembler::less, SCAN_TO_CHAR);
8115   } else {
8116     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8117     movdl(vec1, ch);
8118     pshuflw(vec1, vec1, 0x00);
8119     pshufd(vec1, vec1, 0);
8120     pxor(vec2, vec2);
8121   }
8122   movl(tmp, cnt1);
8123   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
8124   andl(cnt1,0x00000007);  //tail count (in chars)
8125 
8126   bind(SCAN_TO_8_CHAR_LOOP);
8127   movdqu(vec3, Address(result, 0));
8128   pcmpeqw(vec3, vec1);
8129   ptest(vec2, vec3);
8130   jcc(Assembler::carryClear, FOUND_CHAR);
8131   addptr(result, 16);
8132   subl(tmp, stride);
8133   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
8134   bind(SCAN_TO_CHAR);
8135   testl(cnt1, cnt1);
8136   jcc(Assembler::zero, RET_NOT_FOUND);
8137   bind(SCAN_TO_CHAR_LOOP);
8138   load_unsigned_short(tmp, Address(result, 0));
8139   cmpl(ch, tmp);
8140   jccb(Assembler::equal, FOUND_SEQ_CHAR);
8141   addptr(result, 2);
8142   subl(cnt1, 1);
8143   jccb(Assembler::zero, RET_NOT_FOUND);
8144   jmp(SCAN_TO_CHAR_LOOP);
8145 
8146   bind(RET_NOT_FOUND);
8147   movl(result, -1);
8148   jmpb(DONE_LABEL);
8149 
8150   bind(FOUND_CHAR);
8151   if (UseAVX >= 2) {
8152     vpmovmskb(tmp, vec3);
8153   } else {
8154     pmovmskb(tmp, vec3);
8155   }
8156   bsfl(ch, tmp);
8157   addl(result, ch);
8158 
8159   bind(FOUND_SEQ_CHAR);
8160   subptr(result, str1);
8161   shrl(result, 1);
8162 
8163   bind(DONE_LABEL);
8164 } // string_indexof_char
8165 
8166 // helper function for string_compare
8167 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
8168                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
8169                                         Address::ScaleFactor scale2, Register index, int ae) {
8170   if (ae == StrIntrinsicNode::LL) {
8171     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
8172     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
8173   } else if (ae == StrIntrinsicNode::UU) {
8174     load_unsigned_short(elem1, Address(str1, index, scale, 0));
8175     load_unsigned_short(elem2, Address(str2, index, scale, 0));
8176   } else {
8177     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
8178     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
8179   }
8180 }
8181 
8182 // Compare strings, used for char[] and byte[].
8183 void MacroAssembler::string_compare(Register str1, Register str2,
8184                                     Register cnt1, Register cnt2, Register result,
8185                                     XMMRegister vec1, int ae) {
8186   ShortBranchVerifier sbv(this);
8187   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
8188   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
8189   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8190   int stride2x2 = 0x40;
8191   Address::ScaleFactor scale = Address::no_scale;
8192   Address::ScaleFactor scale1 = Address::no_scale;
8193   Address::ScaleFactor scale2 = Address::no_scale;
8194 
8195   if (ae != StrIntrinsicNode::LL) {
8196     stride2x2 = 0x20;
8197   }
8198 
8199   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8200     shrl(cnt2, 1);
8201   }
8202   // Compute the minimum of the string lengths and the
8203   // difference of the string lengths (stack).
8204   // Do the conditional move stuff
8205   movl(result, cnt1);
8206   subl(cnt1, cnt2);
8207   push(cnt1);
8208   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
8209 
8210   // Is the minimum length zero?
8211   testl(cnt2, cnt2);
8212   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8213   if (ae == StrIntrinsicNode::LL) {
8214     // Load first bytes
8215     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
8216     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
8217   } else if (ae == StrIntrinsicNode::UU) {
8218     // Load first characters
8219     load_unsigned_short(result, Address(str1, 0));
8220     load_unsigned_short(cnt1, Address(str2, 0));
8221   } else {
8222     load_unsigned_byte(result, Address(str1, 0));
8223     load_unsigned_short(cnt1, Address(str2, 0));
8224   }
8225   subl(result, cnt1);
8226   jcc(Assembler::notZero,  POP_LABEL);
8227 
8228   if (ae == StrIntrinsicNode::UU) {
8229     // Divide length by 2 to get number of chars
8230     shrl(cnt2, 1);
8231   }
8232   cmpl(cnt2, 1);
8233   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8234 
8235   // Check if the strings start at the same location and setup scale and stride
8236   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8237     cmpptr(str1, str2);
8238     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8239     if (ae == StrIntrinsicNode::LL) {
8240       scale = Address::times_1;
8241       stride = 16;
8242     } else {
8243       scale = Address::times_2;
8244       stride = 8;
8245     }
8246   } else {
8247     scale1 = Address::times_1;
8248     scale2 = Address::times_2;
8249     // scale not used
8250     stride = 8;
8251   }
8252 
8253   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8254     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8255     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8256     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
8257     Label COMPARE_TAIL_LONG;
8258     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
8259 
8260     int pcmpmask = 0x19;
8261     if (ae == StrIntrinsicNode::LL) {
8262       pcmpmask &= ~0x01;
8263     }
8264 
8265     // Setup to compare 16-chars (32-bytes) vectors,
8266     // start from first character again because it has aligned address.
8267     if (ae == StrIntrinsicNode::LL) {
8268       stride2 = 32;
8269     } else {
8270       stride2 = 16;
8271     }
8272     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8273       adr_stride = stride << scale;
8274     } else {
8275       adr_stride1 = 8;  //stride << scale1;
8276       adr_stride2 = 16; //stride << scale2;
8277     }
8278 
8279     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8280     // rax and rdx are used by pcmpestri as elements counters
8281     movl(result, cnt2);
8282     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8283     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8284 
8285     // fast path : compare first 2 8-char vectors.
8286     bind(COMPARE_16_CHARS);
8287     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8288       movdqu(vec1, Address(str1, 0));
8289     } else {
8290       pmovzxbw(vec1, Address(str1, 0));
8291     }
8292     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8293     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8294 
8295     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8296       movdqu(vec1, Address(str1, adr_stride));
8297       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8298     } else {
8299       pmovzxbw(vec1, Address(str1, adr_stride1));
8300       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8301     }
8302     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8303     addl(cnt1, stride);
8304 
8305     // Compare the characters at index in cnt1
8306     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8307     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8308     subl(result, cnt2);
8309     jmp(POP_LABEL);
8310 
8311     // Setup the registers to start vector comparison loop
8312     bind(COMPARE_WIDE_VECTORS);
8313     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8314       lea(str1, Address(str1, result, scale));
8315       lea(str2, Address(str2, result, scale));
8316     } else {
8317       lea(str1, Address(str1, result, scale1));
8318       lea(str2, Address(str2, result, scale2));
8319     }
8320     subl(result, stride2);
8321     subl(cnt2, stride2);
8322     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8323     negptr(result);
8324 
8325     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8326     bind(COMPARE_WIDE_VECTORS_LOOP);
8327 
8328 #ifdef _LP64
8329     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8330       cmpl(cnt2, stride2x2);
8331       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8332       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8333       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8334 
8335       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8336       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8337         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8338         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8339       } else {
8340         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8341         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8342       }
8343       kortestql(k7, k7);
8344       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8345       addptr(result, stride2x2);  // update since we already compared at this addr
8346       subl(cnt2, stride2x2);      // and sub the size too
8347       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8348 
8349       vpxor(vec1, vec1);
8350       jmpb(COMPARE_WIDE_TAIL);
8351     }//if (VM_Version::supports_avx512vlbw())
8352 #endif // _LP64
8353 
8354 
8355     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8356     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8357       vmovdqu(vec1, Address(str1, result, scale));
8358       vpxor(vec1, Address(str2, result, scale));
8359     } else {
8360       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8361       vpxor(vec1, Address(str2, result, scale2));
8362     }
8363     vptest(vec1, vec1);
8364     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8365     addptr(result, stride2);
8366     subl(cnt2, stride2);
8367     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8368     // clean upper bits of YMM registers
8369     vpxor(vec1, vec1);
8370 
8371     // compare wide vectors tail
8372     bind(COMPARE_WIDE_TAIL);
8373     testptr(result, result);
8374     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8375 
8376     movl(result, stride2);
8377     movl(cnt2, result);
8378     negptr(result);
8379     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8380 
8381     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8382     bind(VECTOR_NOT_EQUAL);
8383     // clean upper bits of YMM registers
8384     vpxor(vec1, vec1);
8385     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8386       lea(str1, Address(str1, result, scale));
8387       lea(str2, Address(str2, result, scale));
8388     } else {
8389       lea(str1, Address(str1, result, scale1));
8390       lea(str2, Address(str2, result, scale2));
8391     }
8392     jmp(COMPARE_16_CHARS);
8393 
8394     // Compare tail chars, length between 1 to 15 chars
8395     bind(COMPARE_TAIL_LONG);
8396     movl(cnt2, result);
8397     cmpl(cnt2, stride);
8398     jcc(Assembler::less, COMPARE_SMALL_STR);
8399 
8400     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8401       movdqu(vec1, Address(str1, 0));
8402     } else {
8403       pmovzxbw(vec1, Address(str1, 0));
8404     }
8405     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8406     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8407     subptr(cnt2, stride);
8408     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8409     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8410       lea(str1, Address(str1, result, scale));
8411       lea(str2, Address(str2, result, scale));
8412     } else {
8413       lea(str1, Address(str1, result, scale1));
8414       lea(str2, Address(str2, result, scale2));
8415     }
8416     negptr(cnt2);
8417     jmpb(WHILE_HEAD_LABEL);
8418 
8419     bind(COMPARE_SMALL_STR);
8420   } else if (UseSSE42Intrinsics) {
8421     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8422     int pcmpmask = 0x19;
8423     // Setup to compare 8-char (16-byte) vectors,
8424     // start from first character again because it has aligned address.
8425     movl(result, cnt2);
8426     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8427     if (ae == StrIntrinsicNode::LL) {
8428       pcmpmask &= ~0x01;
8429     }
8430     jcc(Assembler::zero, COMPARE_TAIL);
8431     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8432       lea(str1, Address(str1, result, scale));
8433       lea(str2, Address(str2, result, scale));
8434     } else {
8435       lea(str1, Address(str1, result, scale1));
8436       lea(str2, Address(str2, result, scale2));
8437     }
8438     negptr(result);
8439 
8440     // pcmpestri
8441     //   inputs:
8442     //     vec1- substring
8443     //     rax - negative string length (elements count)
8444     //     mem - scanned string
8445     //     rdx - string length (elements count)
8446     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8447     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8448     //   outputs:
8449     //     rcx - first mismatched element index
8450     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8451 
8452     bind(COMPARE_WIDE_VECTORS);
8453     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8454       movdqu(vec1, Address(str1, result, scale));
8455       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8456     } else {
8457       pmovzxbw(vec1, Address(str1, result, scale1));
8458       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8459     }
8460     // After pcmpestri cnt1(rcx) contains mismatched element index
8461 
8462     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8463     addptr(result, stride);
8464     subptr(cnt2, stride);
8465     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8466 
8467     // compare wide vectors tail
8468     testptr(result, result);
8469     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8470 
8471     movl(cnt2, stride);
8472     movl(result, stride);
8473     negptr(result);
8474     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8475       movdqu(vec1, Address(str1, result, scale));
8476       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8477     } else {
8478       pmovzxbw(vec1, Address(str1, result, scale1));
8479       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8480     }
8481     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8482 
8483     // Mismatched characters in the vectors
8484     bind(VECTOR_NOT_EQUAL);
8485     addptr(cnt1, result);
8486     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8487     subl(result, cnt2);
8488     jmpb(POP_LABEL);
8489 
8490     bind(COMPARE_TAIL); // limit is zero
8491     movl(cnt2, result);
8492     // Fallthru to tail compare
8493   }
8494   // Shift str2 and str1 to the end of the arrays, negate min
8495   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8496     lea(str1, Address(str1, cnt2, scale));
8497     lea(str2, Address(str2, cnt2, scale));
8498   } else {
8499     lea(str1, Address(str1, cnt2, scale1));
8500     lea(str2, Address(str2, cnt2, scale2));
8501   }
8502   decrementl(cnt2);  // first character was compared already
8503   negptr(cnt2);
8504 
8505   // Compare the rest of the elements
8506   bind(WHILE_HEAD_LABEL);
8507   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8508   subl(result, cnt1);
8509   jccb(Assembler::notZero, POP_LABEL);
8510   increment(cnt2);
8511   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8512 
8513   // Strings are equal up to min length.  Return the length difference.
8514   bind(LENGTH_DIFF_LABEL);
8515   pop(result);
8516   if (ae == StrIntrinsicNode::UU) {
8517     // Divide diff by 2 to get number of chars
8518     sarl(result, 1);
8519   }
8520   jmpb(DONE_LABEL);
8521 
8522 #ifdef _LP64
8523   if (VM_Version::supports_avx512vlbw()) {
8524 
8525     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8526 
8527     kmovql(cnt1, k7);
8528     notq(cnt1);
8529     bsfq(cnt2, cnt1);
8530     if (ae != StrIntrinsicNode::LL) {
8531       // Divide diff by 2 to get number of chars
8532       sarl(cnt2, 1);
8533     }
8534     addq(result, cnt2);
8535     if (ae == StrIntrinsicNode::LL) {
8536       load_unsigned_byte(cnt1, Address(str2, result));
8537       load_unsigned_byte(result, Address(str1, result));
8538     } else if (ae == StrIntrinsicNode::UU) {
8539       load_unsigned_short(cnt1, Address(str2, result, scale));
8540       load_unsigned_short(result, Address(str1, result, scale));
8541     } else {
8542       load_unsigned_short(cnt1, Address(str2, result, scale2));
8543       load_unsigned_byte(result, Address(str1, result, scale1));
8544     }
8545     subl(result, cnt1);
8546     jmpb(POP_LABEL);
8547   }//if (VM_Version::supports_avx512vlbw())
8548 #endif // _LP64
8549 
8550   // Discard the stored length difference
8551   bind(POP_LABEL);
8552   pop(cnt1);
8553 
8554   // That's it
8555   bind(DONE_LABEL);
8556   if(ae == StrIntrinsicNode::UL) {
8557     negl(result);
8558   }
8559 
8560 }
8561 
8562 // Search for Non-ASCII character (Negative byte value) in a byte array,
8563 // return true if it has any and false otherwise.
8564 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8565 //   @HotSpotIntrinsicCandidate
8566 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8567 //     for (int i = off; i < off + len; i++) {
8568 //       if (ba[i] < 0) {
8569 //         return true;
8570 //       }
8571 //     }
8572 //     return false;
8573 //   }
8574 void MacroAssembler::has_negatives(Register ary1, Register len,
8575   Register result, Register tmp1,
8576   XMMRegister vec1, XMMRegister vec2) {
8577   // rsi: byte array
8578   // rcx: len
8579   // rax: result
8580   ShortBranchVerifier sbv(this);
8581   assert_different_registers(ary1, len, result, tmp1);
8582   assert_different_registers(vec1, vec2);
8583   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8584 
8585   // len == 0
8586   testl(len, len);
8587   jcc(Assembler::zero, FALSE_LABEL);
8588 
8589   if ((UseAVX > 2) && // AVX512
8590     VM_Version::supports_avx512vlbw() &&
8591     VM_Version::supports_bmi2()) {
8592 
8593     set_vector_masking();  // opening of the stub context for programming mask registers
8594 
8595     Label test_64_loop, test_tail;
8596     Register tmp3_aliased = len;
8597 
8598     movl(tmp1, len);
8599     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8600 
8601     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8602     andl(len, ~(64 - 1));    // vector count (in chars)
8603     jccb(Assembler::zero, test_tail);
8604 
8605     lea(ary1, Address(ary1, len, Address::times_1));
8606     negptr(len);
8607 
8608     bind(test_64_loop);
8609     // Check whether our 64 elements of size byte contain negatives
8610     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8611     kortestql(k2, k2);
8612     jcc(Assembler::notZero, TRUE_LABEL);
8613 
8614     addptr(len, 64);
8615     jccb(Assembler::notZero, test_64_loop);
8616 
8617 
8618     bind(test_tail);
8619     // bail out when there is nothing to be done
8620     testl(tmp1, -1);
8621     jcc(Assembler::zero, FALSE_LABEL);
8622 
8623     // Save k1
8624     kmovql(k3, k1);
8625 
8626     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8627 #ifdef _LP64
8628     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8629     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8630     notq(tmp3_aliased);
8631     kmovql(k1, tmp3_aliased);
8632 #else
8633     Label k_init;
8634     jmp(k_init);
8635 
8636     // We could not read 64-bits from a general purpose register thus we move
8637     // data required to compose 64 1's to the instruction stream
8638     // We emit 64 byte wide series of elements from 0..63 which later on would
8639     // be used as a compare targets with tail count contained in tmp1 register.
8640     // Result would be a k1 register having tmp1 consecutive number or 1
8641     // counting from least significant bit.
8642     address tmp = pc();
8643     emit_int64(0x0706050403020100);
8644     emit_int64(0x0F0E0D0C0B0A0908);
8645     emit_int64(0x1716151413121110);
8646     emit_int64(0x1F1E1D1C1B1A1918);
8647     emit_int64(0x2726252423222120);
8648     emit_int64(0x2F2E2D2C2B2A2928);
8649     emit_int64(0x3736353433323130);
8650     emit_int64(0x3F3E3D3C3B3A3938);
8651 
8652     bind(k_init);
8653     lea(len, InternalAddress(tmp));
8654     // create mask to test for negative byte inside a vector
8655     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8656     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8657 
8658 #endif
8659     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8660     ktestq(k2, k1);
8661     // Restore k1
8662     kmovql(k1, k3);
8663     jcc(Assembler::notZero, TRUE_LABEL);
8664 
8665     jmp(FALSE_LABEL);
8666 
8667     clear_vector_masking();   // closing of the stub context for programming mask registers
8668   } else {
8669     movl(result, len); // copy
8670 
8671     if (UseAVX == 2 && UseSSE >= 2) {
8672       // With AVX2, use 32-byte vector compare
8673       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8674 
8675       // Compare 32-byte vectors
8676       andl(result, 0x0000001f);  //   tail count (in bytes)
8677       andl(len, 0xffffffe0);   // vector count (in bytes)
8678       jccb(Assembler::zero, COMPARE_TAIL);
8679 
8680       lea(ary1, Address(ary1, len, Address::times_1));
8681       negptr(len);
8682 
8683       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8684       movdl(vec2, tmp1);
8685       vpbroadcastd(vec2, vec2);
8686 
8687       bind(COMPARE_WIDE_VECTORS);
8688       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8689       vptest(vec1, vec2);
8690       jccb(Assembler::notZero, TRUE_LABEL);
8691       addptr(len, 32);
8692       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8693 
8694       testl(result, result);
8695       jccb(Assembler::zero, FALSE_LABEL);
8696 
8697       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8698       vptest(vec1, vec2);
8699       jccb(Assembler::notZero, TRUE_LABEL);
8700       jmpb(FALSE_LABEL);
8701 
8702       bind(COMPARE_TAIL); // len is zero
8703       movl(len, result);
8704       // Fallthru to tail compare
8705     } else if (UseSSE42Intrinsics) {
8706       // With SSE4.2, use double quad vector compare
8707       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8708 
8709       // Compare 16-byte vectors
8710       andl(result, 0x0000000f);  //   tail count (in bytes)
8711       andl(len, 0xfffffff0);   // vector count (in bytes)
8712       jccb(Assembler::zero, COMPARE_TAIL);
8713 
8714       lea(ary1, Address(ary1, len, Address::times_1));
8715       negptr(len);
8716 
8717       movl(tmp1, 0x80808080);
8718       movdl(vec2, tmp1);
8719       pshufd(vec2, vec2, 0);
8720 
8721       bind(COMPARE_WIDE_VECTORS);
8722       movdqu(vec1, Address(ary1, len, Address::times_1));
8723       ptest(vec1, vec2);
8724       jccb(Assembler::notZero, TRUE_LABEL);
8725       addptr(len, 16);
8726       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8727 
8728       testl(result, result);
8729       jccb(Assembler::zero, FALSE_LABEL);
8730 
8731       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8732       ptest(vec1, vec2);
8733       jccb(Assembler::notZero, TRUE_LABEL);
8734       jmpb(FALSE_LABEL);
8735 
8736       bind(COMPARE_TAIL); // len is zero
8737       movl(len, result);
8738       // Fallthru to tail compare
8739     }
8740   }
8741   // Compare 4-byte vectors
8742   andl(len, 0xfffffffc); // vector count (in bytes)
8743   jccb(Assembler::zero, COMPARE_CHAR);
8744 
8745   lea(ary1, Address(ary1, len, Address::times_1));
8746   negptr(len);
8747 
8748   bind(COMPARE_VECTORS);
8749   movl(tmp1, Address(ary1, len, Address::times_1));
8750   andl(tmp1, 0x80808080);
8751   jccb(Assembler::notZero, TRUE_LABEL);
8752   addptr(len, 4);
8753   jcc(Assembler::notZero, COMPARE_VECTORS);
8754 
8755   // Compare trailing char (final 2 bytes), if any
8756   bind(COMPARE_CHAR);
8757   testl(result, 0x2);   // tail  char
8758   jccb(Assembler::zero, COMPARE_BYTE);
8759   load_unsigned_short(tmp1, Address(ary1, 0));
8760   andl(tmp1, 0x00008080);
8761   jccb(Assembler::notZero, TRUE_LABEL);
8762   subptr(result, 2);
8763   lea(ary1, Address(ary1, 2));
8764 
8765   bind(COMPARE_BYTE);
8766   testl(result, 0x1);   // tail  byte
8767   jccb(Assembler::zero, FALSE_LABEL);
8768   load_unsigned_byte(tmp1, Address(ary1, 0));
8769   andl(tmp1, 0x00000080);
8770   jccb(Assembler::notEqual, TRUE_LABEL);
8771   jmpb(FALSE_LABEL);
8772 
8773   bind(TRUE_LABEL);
8774   movl(result, 1);   // return true
8775   jmpb(DONE);
8776 
8777   bind(FALSE_LABEL);
8778   xorl(result, result); // return false
8779 
8780   // That's it
8781   bind(DONE);
8782   if (UseAVX >= 2 && UseSSE >= 2) {
8783     // clean upper bits of YMM registers
8784     vpxor(vec1, vec1);
8785     vpxor(vec2, vec2);
8786   }
8787 }
8788 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8789 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8790                                    Register limit, Register result, Register chr,
8791                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8792   ShortBranchVerifier sbv(this);
8793   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8794 
8795   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8796   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8797 
8798   if (is_array_equ) {
8799     // Check the input args
8800     cmpoops(ary1, ary2);
8801     jcc(Assembler::equal, TRUE_LABEL);
8802 
8803     // Need additional checks for arrays_equals.
8804     testptr(ary1, ary1);
8805     jcc(Assembler::zero, FALSE_LABEL);
8806     testptr(ary2, ary2);
8807     jcc(Assembler::zero, FALSE_LABEL);
8808 
8809     // Check the lengths
8810     movl(limit, Address(ary1, length_offset));
8811     cmpl(limit, Address(ary2, length_offset));
8812     jcc(Assembler::notEqual, FALSE_LABEL);
8813   }
8814 
8815   // count == 0
8816   testl(limit, limit);
8817   jcc(Assembler::zero, TRUE_LABEL);
8818 
8819   if (is_array_equ) {
8820     // Load array address
8821     lea(ary1, Address(ary1, base_offset));
8822     lea(ary2, Address(ary2, base_offset));
8823   }
8824 
8825   if (is_array_equ && is_char) {
8826     // arrays_equals when used for char[].
8827     shll(limit, 1);      // byte count != 0
8828   }
8829   movl(result, limit); // copy
8830 
8831   if (UseAVX >= 2) {
8832     // With AVX2, use 32-byte vector compare
8833     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8834 
8835     // Compare 32-byte vectors
8836     andl(result, 0x0000001f);  //   tail count (in bytes)
8837     andl(limit, 0xffffffe0);   // vector count (in bytes)
8838     jcc(Assembler::zero, COMPARE_TAIL);
8839 
8840     lea(ary1, Address(ary1, limit, Address::times_1));
8841     lea(ary2, Address(ary2, limit, Address::times_1));
8842     negptr(limit);
8843 
8844     bind(COMPARE_WIDE_VECTORS);
8845 
8846 #ifdef _LP64
8847     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8848       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8849 
8850       cmpl(limit, -64);
8851       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8852 
8853       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8854 
8855       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8856       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8857       kortestql(k7, k7);
8858       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8859       addptr(limit, 64);  // update since we already compared at this addr
8860       cmpl(limit, -64);
8861       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8862 
8863       // At this point we may still need to compare -limit+result bytes.
8864       // We could execute the next two instruction and just continue via non-wide path:
8865       //  cmpl(limit, 0);
8866       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8867       // But since we stopped at the points ary{1,2}+limit which are
8868       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8869       // (|limit| <= 32 and result < 32),
8870       // we may just compare the last 64 bytes.
8871       //
8872       addptr(result, -64);   // it is safe, bc we just came from this area
8873       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8874       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8875       kortestql(k7, k7);
8876       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8877 
8878       jmp(TRUE_LABEL);
8879 
8880       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8881 
8882     }//if (VM_Version::supports_avx512vlbw())
8883 #endif //_LP64
8884 
8885     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8886     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8887     vpxor(vec1, vec2);
8888 
8889     vptest(vec1, vec1);
8890     jcc(Assembler::notZero, FALSE_LABEL);
8891     addptr(limit, 32);
8892     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8893 
8894     testl(result, result);
8895     jcc(Assembler::zero, TRUE_LABEL);
8896 
8897     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8898     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8899     vpxor(vec1, vec2);
8900 
8901     vptest(vec1, vec1);
8902     jccb(Assembler::notZero, FALSE_LABEL);
8903     jmpb(TRUE_LABEL);
8904 
8905     bind(COMPARE_TAIL); // limit is zero
8906     movl(limit, result);
8907     // Fallthru to tail compare
8908   } else if (UseSSE42Intrinsics) {
8909     // With SSE4.2, use double quad vector compare
8910     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8911 
8912     // Compare 16-byte vectors
8913     andl(result, 0x0000000f);  //   tail count (in bytes)
8914     andl(limit, 0xfffffff0);   // vector count (in bytes)
8915     jcc(Assembler::zero, COMPARE_TAIL);
8916 
8917     lea(ary1, Address(ary1, limit, Address::times_1));
8918     lea(ary2, Address(ary2, limit, Address::times_1));
8919     negptr(limit);
8920 
8921     bind(COMPARE_WIDE_VECTORS);
8922     movdqu(vec1, Address(ary1, limit, Address::times_1));
8923     movdqu(vec2, Address(ary2, limit, Address::times_1));
8924     pxor(vec1, vec2);
8925 
8926     ptest(vec1, vec1);
8927     jcc(Assembler::notZero, FALSE_LABEL);
8928     addptr(limit, 16);
8929     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8930 
8931     testl(result, result);
8932     jcc(Assembler::zero, TRUE_LABEL);
8933 
8934     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8935     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8936     pxor(vec1, vec2);
8937 
8938     ptest(vec1, vec1);
8939     jccb(Assembler::notZero, FALSE_LABEL);
8940     jmpb(TRUE_LABEL);
8941 
8942     bind(COMPARE_TAIL); // limit is zero
8943     movl(limit, result);
8944     // Fallthru to tail compare
8945   }
8946 
8947   // Compare 4-byte vectors
8948   andl(limit, 0xfffffffc); // vector count (in bytes)
8949   jccb(Assembler::zero, COMPARE_CHAR);
8950 
8951   lea(ary1, Address(ary1, limit, Address::times_1));
8952   lea(ary2, Address(ary2, limit, Address::times_1));
8953   negptr(limit);
8954 
8955   bind(COMPARE_VECTORS);
8956   movl(chr, Address(ary1, limit, Address::times_1));
8957   cmpl(chr, Address(ary2, limit, Address::times_1));
8958   jccb(Assembler::notEqual, FALSE_LABEL);
8959   addptr(limit, 4);
8960   jcc(Assembler::notZero, COMPARE_VECTORS);
8961 
8962   // Compare trailing char (final 2 bytes), if any
8963   bind(COMPARE_CHAR);
8964   testl(result, 0x2);   // tail  char
8965   jccb(Assembler::zero, COMPARE_BYTE);
8966   load_unsigned_short(chr, Address(ary1, 0));
8967   load_unsigned_short(limit, Address(ary2, 0));
8968   cmpl(chr, limit);
8969   jccb(Assembler::notEqual, FALSE_LABEL);
8970 
8971   if (is_array_equ && is_char) {
8972     bind(COMPARE_BYTE);
8973   } else {
8974     lea(ary1, Address(ary1, 2));
8975     lea(ary2, Address(ary2, 2));
8976 
8977     bind(COMPARE_BYTE);
8978     testl(result, 0x1);   // tail  byte
8979     jccb(Assembler::zero, TRUE_LABEL);
8980     load_unsigned_byte(chr, Address(ary1, 0));
8981     load_unsigned_byte(limit, Address(ary2, 0));
8982     cmpl(chr, limit);
8983     jccb(Assembler::notEqual, FALSE_LABEL);
8984   }
8985   bind(TRUE_LABEL);
8986   movl(result, 1);   // return true
8987   jmpb(DONE);
8988 
8989   bind(FALSE_LABEL);
8990   xorl(result, result); // return false
8991 
8992   // That's it
8993   bind(DONE);
8994   if (UseAVX >= 2) {
8995     // clean upper bits of YMM registers
8996     vpxor(vec1, vec1);
8997     vpxor(vec2, vec2);
8998   }
8999 }
9000 
9001 #endif
9002 
9003 void MacroAssembler::generate_fill(BasicType t, bool aligned,
9004                                    Register to, Register value, Register count,
9005                                    Register rtmp, XMMRegister xtmp) {
9006   ShortBranchVerifier sbv(this);
9007   assert_different_registers(to, value, count, rtmp);
9008   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
9009   Label L_fill_2_bytes, L_fill_4_bytes;
9010 
9011   int shift = -1;
9012   switch (t) {
9013     case T_BYTE:
9014       shift = 2;
9015       break;
9016     case T_SHORT:
9017       shift = 1;
9018       break;
9019     case T_INT:
9020       shift = 0;
9021       break;
9022     default: ShouldNotReachHere();
9023   }
9024 
9025   if (t == T_BYTE) {
9026     andl(value, 0xff);
9027     movl(rtmp, value);
9028     shll(rtmp, 8);
9029     orl(value, rtmp);
9030   }
9031   if (t == T_SHORT) {
9032     andl(value, 0xffff);
9033   }
9034   if (t == T_BYTE || t == T_SHORT) {
9035     movl(rtmp, value);
9036     shll(rtmp, 16);
9037     orl(value, rtmp);
9038   }
9039 
9040   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
9041   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
9042   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
9043     // align source address at 4 bytes address boundary
9044     if (t == T_BYTE) {
9045       // One byte misalignment happens only for byte arrays
9046       testptr(to, 1);
9047       jccb(Assembler::zero, L_skip_align1);
9048       movb(Address(to, 0), value);
9049       increment(to);
9050       decrement(count);
9051       BIND(L_skip_align1);
9052     }
9053     // Two bytes misalignment happens only for byte and short (char) arrays
9054     testptr(to, 2);
9055     jccb(Assembler::zero, L_skip_align2);
9056     movw(Address(to, 0), value);
9057     addptr(to, 2);
9058     subl(count, 1<<(shift-1));
9059     BIND(L_skip_align2);
9060   }
9061   if (UseSSE < 2) {
9062     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9063     // Fill 32-byte chunks
9064     subl(count, 8 << shift);
9065     jcc(Assembler::less, L_check_fill_8_bytes);
9066     align(16);
9067 
9068     BIND(L_fill_32_bytes_loop);
9069 
9070     for (int i = 0; i < 32; i += 4) {
9071       movl(Address(to, i), value);
9072     }
9073 
9074     addptr(to, 32);
9075     subl(count, 8 << shift);
9076     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9077     BIND(L_check_fill_8_bytes);
9078     addl(count, 8 << shift);
9079     jccb(Assembler::zero, L_exit);
9080     jmpb(L_fill_8_bytes);
9081 
9082     //
9083     // length is too short, just fill qwords
9084     //
9085     BIND(L_fill_8_bytes_loop);
9086     movl(Address(to, 0), value);
9087     movl(Address(to, 4), value);
9088     addptr(to, 8);
9089     BIND(L_fill_8_bytes);
9090     subl(count, 1 << (shift + 1));
9091     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9092     // fall through to fill 4 bytes
9093   } else {
9094     Label L_fill_32_bytes;
9095     if (!UseUnalignedLoadStores) {
9096       // align to 8 bytes, we know we are 4 byte aligned to start
9097       testptr(to, 4);
9098       jccb(Assembler::zero, L_fill_32_bytes);
9099       movl(Address(to, 0), value);
9100       addptr(to, 4);
9101       subl(count, 1<<shift);
9102     }
9103     BIND(L_fill_32_bytes);
9104     {
9105       assert( UseSSE >= 2, "supported cpu only" );
9106       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9107       if (UseAVX > 2) {
9108         movl(rtmp, 0xffff);
9109         kmovwl(k1, rtmp);
9110       }
9111       movdl(xtmp, value);
9112       if (UseAVX > 2 && UseUnalignedLoadStores) {
9113         // Fill 64-byte chunks
9114         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9115         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
9116 
9117         subl(count, 16 << shift);
9118         jcc(Assembler::less, L_check_fill_32_bytes);
9119         align(16);
9120 
9121         BIND(L_fill_64_bytes_loop);
9122         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
9123         addptr(to, 64);
9124         subl(count, 16 << shift);
9125         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9126 
9127         BIND(L_check_fill_32_bytes);
9128         addl(count, 8 << shift);
9129         jccb(Assembler::less, L_check_fill_8_bytes);
9130         vmovdqu(Address(to, 0), xtmp);
9131         addptr(to, 32);
9132         subl(count, 8 << shift);
9133 
9134         BIND(L_check_fill_8_bytes);
9135       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
9136         // Fill 64-byte chunks
9137         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9138         vpbroadcastd(xtmp, xtmp);
9139 
9140         subl(count, 16 << shift);
9141         jcc(Assembler::less, L_check_fill_32_bytes);
9142         align(16);
9143 
9144         BIND(L_fill_64_bytes_loop);
9145         vmovdqu(Address(to, 0), xtmp);
9146         vmovdqu(Address(to, 32), xtmp);
9147         addptr(to, 64);
9148         subl(count, 16 << shift);
9149         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9150 
9151         BIND(L_check_fill_32_bytes);
9152         addl(count, 8 << shift);
9153         jccb(Assembler::less, L_check_fill_8_bytes);
9154         vmovdqu(Address(to, 0), xtmp);
9155         addptr(to, 32);
9156         subl(count, 8 << shift);
9157 
9158         BIND(L_check_fill_8_bytes);
9159         // clean upper bits of YMM registers
9160         movdl(xtmp, value);
9161         pshufd(xtmp, xtmp, 0);
9162       } else {
9163         // Fill 32-byte chunks
9164         pshufd(xtmp, xtmp, 0);
9165 
9166         subl(count, 8 << shift);
9167         jcc(Assembler::less, L_check_fill_8_bytes);
9168         align(16);
9169 
9170         BIND(L_fill_32_bytes_loop);
9171 
9172         if (UseUnalignedLoadStores) {
9173           movdqu(Address(to, 0), xtmp);
9174           movdqu(Address(to, 16), xtmp);
9175         } else {
9176           movq(Address(to, 0), xtmp);
9177           movq(Address(to, 8), xtmp);
9178           movq(Address(to, 16), xtmp);
9179           movq(Address(to, 24), xtmp);
9180         }
9181 
9182         addptr(to, 32);
9183         subl(count, 8 << shift);
9184         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9185 
9186         BIND(L_check_fill_8_bytes);
9187       }
9188       addl(count, 8 << shift);
9189       jccb(Assembler::zero, L_exit);
9190       jmpb(L_fill_8_bytes);
9191 
9192       //
9193       // length is too short, just fill qwords
9194       //
9195       BIND(L_fill_8_bytes_loop);
9196       movq(Address(to, 0), xtmp);
9197       addptr(to, 8);
9198       BIND(L_fill_8_bytes);
9199       subl(count, 1 << (shift + 1));
9200       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9201     }
9202   }
9203   // fill trailing 4 bytes
9204   BIND(L_fill_4_bytes);
9205   testl(count, 1<<shift);
9206   jccb(Assembler::zero, L_fill_2_bytes);
9207   movl(Address(to, 0), value);
9208   if (t == T_BYTE || t == T_SHORT) {
9209     addptr(to, 4);
9210     BIND(L_fill_2_bytes);
9211     // fill trailing 2 bytes
9212     testl(count, 1<<(shift-1));
9213     jccb(Assembler::zero, L_fill_byte);
9214     movw(Address(to, 0), value);
9215     if (t == T_BYTE) {
9216       addptr(to, 2);
9217       BIND(L_fill_byte);
9218       // fill trailing byte
9219       testl(count, 1);
9220       jccb(Assembler::zero, L_exit);
9221       movb(Address(to, 0), value);
9222     } else {
9223       BIND(L_fill_byte);
9224     }
9225   } else {
9226     BIND(L_fill_2_bytes);
9227   }
9228   BIND(L_exit);
9229 }
9230 
9231 // encode char[] to byte[] in ISO_8859_1
9232    //@HotSpotIntrinsicCandidate
9233    //private static int implEncodeISOArray(byte[] sa, int sp,
9234    //byte[] da, int dp, int len) {
9235    //  int i = 0;
9236    //  for (; i < len; i++) {
9237    //    char c = StringUTF16.getChar(sa, sp++);
9238    //    if (c > '\u00FF')
9239    //      break;
9240    //    da[dp++] = (byte)c;
9241    //  }
9242    //  return i;
9243    //}
9244 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
9245   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9246   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9247   Register tmp5, Register result) {
9248 
9249   // rsi: src
9250   // rdi: dst
9251   // rdx: len
9252   // rcx: tmp5
9253   // rax: result
9254   ShortBranchVerifier sbv(this);
9255   assert_different_registers(src, dst, len, tmp5, result);
9256   Label L_done, L_copy_1_char, L_copy_1_char_exit;
9257 
9258   // set result
9259   xorl(result, result);
9260   // check for zero length
9261   testl(len, len);
9262   jcc(Assembler::zero, L_done);
9263 
9264   movl(result, len);
9265 
9266   // Setup pointers
9267   lea(src, Address(src, len, Address::times_2)); // char[]
9268   lea(dst, Address(dst, len, Address::times_1)); // byte[]
9269   negptr(len);
9270 
9271   if (UseSSE42Intrinsics || UseAVX >= 2) {
9272     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
9273     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
9274 
9275     if (UseAVX >= 2) {
9276       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
9277       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9278       movdl(tmp1Reg, tmp5);
9279       vpbroadcastd(tmp1Reg, tmp1Reg);
9280       jmp(L_chars_32_check);
9281 
9282       bind(L_copy_32_chars);
9283       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
9284       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
9285       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9286       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9287       jccb(Assembler::notZero, L_copy_32_chars_exit);
9288       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9289       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
9290       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
9291 
9292       bind(L_chars_32_check);
9293       addptr(len, 32);
9294       jcc(Assembler::lessEqual, L_copy_32_chars);
9295 
9296       bind(L_copy_32_chars_exit);
9297       subptr(len, 16);
9298       jccb(Assembler::greater, L_copy_16_chars_exit);
9299 
9300     } else if (UseSSE42Intrinsics) {
9301       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9302       movdl(tmp1Reg, tmp5);
9303       pshufd(tmp1Reg, tmp1Reg, 0);
9304       jmpb(L_chars_16_check);
9305     }
9306 
9307     bind(L_copy_16_chars);
9308     if (UseAVX >= 2) {
9309       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9310       vptest(tmp2Reg, tmp1Reg);
9311       jcc(Assembler::notZero, L_copy_16_chars_exit);
9312       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9313       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9314     } else {
9315       if (UseAVX > 0) {
9316         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9317         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9318         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9319       } else {
9320         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9321         por(tmp2Reg, tmp3Reg);
9322         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9323         por(tmp2Reg, tmp4Reg);
9324       }
9325       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9326       jccb(Assembler::notZero, L_copy_16_chars_exit);
9327       packuswb(tmp3Reg, tmp4Reg);
9328     }
9329     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9330 
9331     bind(L_chars_16_check);
9332     addptr(len, 16);
9333     jcc(Assembler::lessEqual, L_copy_16_chars);
9334 
9335     bind(L_copy_16_chars_exit);
9336     if (UseAVX >= 2) {
9337       // clean upper bits of YMM registers
9338       vpxor(tmp2Reg, tmp2Reg);
9339       vpxor(tmp3Reg, tmp3Reg);
9340       vpxor(tmp4Reg, tmp4Reg);
9341       movdl(tmp1Reg, tmp5);
9342       pshufd(tmp1Reg, tmp1Reg, 0);
9343     }
9344     subptr(len, 8);
9345     jccb(Assembler::greater, L_copy_8_chars_exit);
9346 
9347     bind(L_copy_8_chars);
9348     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9349     ptest(tmp3Reg, tmp1Reg);
9350     jccb(Assembler::notZero, L_copy_8_chars_exit);
9351     packuswb(tmp3Reg, tmp1Reg);
9352     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9353     addptr(len, 8);
9354     jccb(Assembler::lessEqual, L_copy_8_chars);
9355 
9356     bind(L_copy_8_chars_exit);
9357     subptr(len, 8);
9358     jccb(Assembler::zero, L_done);
9359   }
9360 
9361   bind(L_copy_1_char);
9362   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9363   testl(tmp5, 0xff00);      // check if Unicode char
9364   jccb(Assembler::notZero, L_copy_1_char_exit);
9365   movb(Address(dst, len, Address::times_1, 0), tmp5);
9366   addptr(len, 1);
9367   jccb(Assembler::less, L_copy_1_char);
9368 
9369   bind(L_copy_1_char_exit);
9370   addptr(result, len); // len is negative count of not processed elements
9371 
9372   bind(L_done);
9373 }
9374 
9375 #ifdef _LP64
9376 /**
9377  * Helper for multiply_to_len().
9378  */
9379 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9380   addq(dest_lo, src1);
9381   adcq(dest_hi, 0);
9382   addq(dest_lo, src2);
9383   adcq(dest_hi, 0);
9384 }
9385 
9386 /**
9387  * Multiply 64 bit by 64 bit first loop.
9388  */
9389 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9390                                            Register y, Register y_idx, Register z,
9391                                            Register carry, Register product,
9392                                            Register idx, Register kdx) {
9393   //
9394   //  jlong carry, x[], y[], z[];
9395   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9396   //    huge_128 product = y[idx] * x[xstart] + carry;
9397   //    z[kdx] = (jlong)product;
9398   //    carry  = (jlong)(product >>> 64);
9399   //  }
9400   //  z[xstart] = carry;
9401   //
9402 
9403   Label L_first_loop, L_first_loop_exit;
9404   Label L_one_x, L_one_y, L_multiply;
9405 
9406   decrementl(xstart);
9407   jcc(Assembler::negative, L_one_x);
9408 
9409   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9410   rorq(x_xstart, 32); // convert big-endian to little-endian
9411 
9412   bind(L_first_loop);
9413   decrementl(idx);
9414   jcc(Assembler::negative, L_first_loop_exit);
9415   decrementl(idx);
9416   jcc(Assembler::negative, L_one_y);
9417   movq(y_idx, Address(y, idx, Address::times_4,  0));
9418   rorq(y_idx, 32); // convert big-endian to little-endian
9419   bind(L_multiply);
9420   movq(product, x_xstart);
9421   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9422   addq(product, carry);
9423   adcq(rdx, 0);
9424   subl(kdx, 2);
9425   movl(Address(z, kdx, Address::times_4,  4), product);
9426   shrq(product, 32);
9427   movl(Address(z, kdx, Address::times_4,  0), product);
9428   movq(carry, rdx);
9429   jmp(L_first_loop);
9430 
9431   bind(L_one_y);
9432   movl(y_idx, Address(y,  0));
9433   jmp(L_multiply);
9434 
9435   bind(L_one_x);
9436   movl(x_xstart, Address(x,  0));
9437   jmp(L_first_loop);
9438 
9439   bind(L_first_loop_exit);
9440 }
9441 
9442 /**
9443  * Multiply 64 bit by 64 bit and add 128 bit.
9444  */
9445 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9446                                             Register yz_idx, Register idx,
9447                                             Register carry, Register product, int offset) {
9448   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9449   //     z[kdx] = (jlong)product;
9450 
9451   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9452   rorq(yz_idx, 32); // convert big-endian to little-endian
9453   movq(product, x_xstart);
9454   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9455   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9456   rorq(yz_idx, 32); // convert big-endian to little-endian
9457 
9458   add2_with_carry(rdx, product, carry, yz_idx);
9459 
9460   movl(Address(z, idx, Address::times_4,  offset+4), product);
9461   shrq(product, 32);
9462   movl(Address(z, idx, Address::times_4,  offset), product);
9463 
9464 }
9465 
9466 /**
9467  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9468  */
9469 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9470                                              Register yz_idx, Register idx, Register jdx,
9471                                              Register carry, Register product,
9472                                              Register carry2) {
9473   //   jlong carry, x[], y[], z[];
9474   //   int kdx = ystart+1;
9475   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9476   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9477   //     z[kdx+idx+1] = (jlong)product;
9478   //     jlong carry2  = (jlong)(product >>> 64);
9479   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9480   //     z[kdx+idx] = (jlong)product;
9481   //     carry  = (jlong)(product >>> 64);
9482   //   }
9483   //   idx += 2;
9484   //   if (idx > 0) {
9485   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9486   //     z[kdx+idx] = (jlong)product;
9487   //     carry  = (jlong)(product >>> 64);
9488   //   }
9489   //
9490 
9491   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9492 
9493   movl(jdx, idx);
9494   andl(jdx, 0xFFFFFFFC);
9495   shrl(jdx, 2);
9496 
9497   bind(L_third_loop);
9498   subl(jdx, 1);
9499   jcc(Assembler::negative, L_third_loop_exit);
9500   subl(idx, 4);
9501 
9502   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9503   movq(carry2, rdx);
9504 
9505   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9506   movq(carry, rdx);
9507   jmp(L_third_loop);
9508 
9509   bind (L_third_loop_exit);
9510 
9511   andl (idx, 0x3);
9512   jcc(Assembler::zero, L_post_third_loop_done);
9513 
9514   Label L_check_1;
9515   subl(idx, 2);
9516   jcc(Assembler::negative, L_check_1);
9517 
9518   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9519   movq(carry, rdx);
9520 
9521   bind (L_check_1);
9522   addl (idx, 0x2);
9523   andl (idx, 0x1);
9524   subl(idx, 1);
9525   jcc(Assembler::negative, L_post_third_loop_done);
9526 
9527   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9528   movq(product, x_xstart);
9529   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9530   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9531 
9532   add2_with_carry(rdx, product, yz_idx, carry);
9533 
9534   movl(Address(z, idx, Address::times_4,  0), product);
9535   shrq(product, 32);
9536 
9537   shlq(rdx, 32);
9538   orq(product, rdx);
9539   movq(carry, product);
9540 
9541   bind(L_post_third_loop_done);
9542 }
9543 
9544 /**
9545  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9546  *
9547  */
9548 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9549                                                   Register carry, Register carry2,
9550                                                   Register idx, Register jdx,
9551                                                   Register yz_idx1, Register yz_idx2,
9552                                                   Register tmp, Register tmp3, Register tmp4) {
9553   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9554 
9555   //   jlong carry, x[], y[], z[];
9556   //   int kdx = ystart+1;
9557   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9558   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9559   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9560   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9561   //     carry  = (jlong)(tmp4 >>> 64);
9562   //     z[kdx+idx+1] = (jlong)tmp3;
9563   //     z[kdx+idx] = (jlong)tmp4;
9564   //   }
9565   //   idx += 2;
9566   //   if (idx > 0) {
9567   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9568   //     z[kdx+idx] = (jlong)yz_idx1;
9569   //     carry  = (jlong)(yz_idx1 >>> 64);
9570   //   }
9571   //
9572 
9573   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9574 
9575   movl(jdx, idx);
9576   andl(jdx, 0xFFFFFFFC);
9577   shrl(jdx, 2);
9578 
9579   bind(L_third_loop);
9580   subl(jdx, 1);
9581   jcc(Assembler::negative, L_third_loop_exit);
9582   subl(idx, 4);
9583 
9584   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9585   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9586   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9587   rorxq(yz_idx2, yz_idx2, 32);
9588 
9589   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9590   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9591 
9592   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9593   rorxq(yz_idx1, yz_idx1, 32);
9594   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9595   rorxq(yz_idx2, yz_idx2, 32);
9596 
9597   if (VM_Version::supports_adx()) {
9598     adcxq(tmp3, carry);
9599     adoxq(tmp3, yz_idx1);
9600 
9601     adcxq(tmp4, tmp);
9602     adoxq(tmp4, yz_idx2);
9603 
9604     movl(carry, 0); // does not affect flags
9605     adcxq(carry2, carry);
9606     adoxq(carry2, carry);
9607   } else {
9608     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9609     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9610   }
9611   movq(carry, carry2);
9612 
9613   movl(Address(z, idx, Address::times_4, 12), tmp3);
9614   shrq(tmp3, 32);
9615   movl(Address(z, idx, Address::times_4,  8), tmp3);
9616 
9617   movl(Address(z, idx, Address::times_4,  4), tmp4);
9618   shrq(tmp4, 32);
9619   movl(Address(z, idx, Address::times_4,  0), tmp4);
9620 
9621   jmp(L_third_loop);
9622 
9623   bind (L_third_loop_exit);
9624 
9625   andl (idx, 0x3);
9626   jcc(Assembler::zero, L_post_third_loop_done);
9627 
9628   Label L_check_1;
9629   subl(idx, 2);
9630   jcc(Assembler::negative, L_check_1);
9631 
9632   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9633   rorxq(yz_idx1, yz_idx1, 32);
9634   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9635   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9636   rorxq(yz_idx2, yz_idx2, 32);
9637 
9638   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9639 
9640   movl(Address(z, idx, Address::times_4,  4), tmp3);
9641   shrq(tmp3, 32);
9642   movl(Address(z, idx, Address::times_4,  0), tmp3);
9643   movq(carry, tmp4);
9644 
9645   bind (L_check_1);
9646   addl (idx, 0x2);
9647   andl (idx, 0x1);
9648   subl(idx, 1);
9649   jcc(Assembler::negative, L_post_third_loop_done);
9650   movl(tmp4, Address(y, idx, Address::times_4,  0));
9651   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9652   movl(tmp4, Address(z, idx, Address::times_4,  0));
9653 
9654   add2_with_carry(carry2, tmp3, tmp4, carry);
9655 
9656   movl(Address(z, idx, Address::times_4,  0), tmp3);
9657   shrq(tmp3, 32);
9658 
9659   shlq(carry2, 32);
9660   orq(tmp3, carry2);
9661   movq(carry, tmp3);
9662 
9663   bind(L_post_third_loop_done);
9664 }
9665 
9666 /**
9667  * Code for BigInteger::multiplyToLen() instrinsic.
9668  *
9669  * rdi: x
9670  * rax: xlen
9671  * rsi: y
9672  * rcx: ylen
9673  * r8:  z
9674  * r11: zlen
9675  * r12: tmp1
9676  * r13: tmp2
9677  * r14: tmp3
9678  * r15: tmp4
9679  * rbx: tmp5
9680  *
9681  */
9682 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9683                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9684   ShortBranchVerifier sbv(this);
9685   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9686 
9687   push(tmp1);
9688   push(tmp2);
9689   push(tmp3);
9690   push(tmp4);
9691   push(tmp5);
9692 
9693   push(xlen);
9694   push(zlen);
9695 
9696   const Register idx = tmp1;
9697   const Register kdx = tmp2;
9698   const Register xstart = tmp3;
9699 
9700   const Register y_idx = tmp4;
9701   const Register carry = tmp5;
9702   const Register product  = xlen;
9703   const Register x_xstart = zlen;  // reuse register
9704 
9705   // First Loop.
9706   //
9707   //  final static long LONG_MASK = 0xffffffffL;
9708   //  int xstart = xlen - 1;
9709   //  int ystart = ylen - 1;
9710   //  long carry = 0;
9711   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9712   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9713   //    z[kdx] = (int)product;
9714   //    carry = product >>> 32;
9715   //  }
9716   //  z[xstart] = (int)carry;
9717   //
9718 
9719   movl(idx, ylen);      // idx = ylen;
9720   movl(kdx, zlen);      // kdx = xlen+ylen;
9721   xorq(carry, carry);   // carry = 0;
9722 
9723   Label L_done;
9724 
9725   movl(xstart, xlen);
9726   decrementl(xstart);
9727   jcc(Assembler::negative, L_done);
9728 
9729   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9730 
9731   Label L_second_loop;
9732   testl(kdx, kdx);
9733   jcc(Assembler::zero, L_second_loop);
9734 
9735   Label L_carry;
9736   subl(kdx, 1);
9737   jcc(Assembler::zero, L_carry);
9738 
9739   movl(Address(z, kdx, Address::times_4,  0), carry);
9740   shrq(carry, 32);
9741   subl(kdx, 1);
9742 
9743   bind(L_carry);
9744   movl(Address(z, kdx, Address::times_4,  0), carry);
9745 
9746   // Second and third (nested) loops.
9747   //
9748   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9749   //   carry = 0;
9750   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9751   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9752   //                    (z[k] & LONG_MASK) + carry;
9753   //     z[k] = (int)product;
9754   //     carry = product >>> 32;
9755   //   }
9756   //   z[i] = (int)carry;
9757   // }
9758   //
9759   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9760 
9761   const Register jdx = tmp1;
9762 
9763   bind(L_second_loop);
9764   xorl(carry, carry);    // carry = 0;
9765   movl(jdx, ylen);       // j = ystart+1
9766 
9767   subl(xstart, 1);       // i = xstart-1;
9768   jcc(Assembler::negative, L_done);
9769 
9770   push (z);
9771 
9772   Label L_last_x;
9773   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9774   subl(xstart, 1);       // i = xstart-1;
9775   jcc(Assembler::negative, L_last_x);
9776 
9777   if (UseBMI2Instructions) {
9778     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9779     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9780   } else {
9781     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9782     rorq(x_xstart, 32);  // convert big-endian to little-endian
9783   }
9784 
9785   Label L_third_loop_prologue;
9786   bind(L_third_loop_prologue);
9787 
9788   push (x);
9789   push (xstart);
9790   push (ylen);
9791 
9792 
9793   if (UseBMI2Instructions) {
9794     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9795   } else { // !UseBMI2Instructions
9796     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9797   }
9798 
9799   pop(ylen);
9800   pop(xlen);
9801   pop(x);
9802   pop(z);
9803 
9804   movl(tmp3, xlen);
9805   addl(tmp3, 1);
9806   movl(Address(z, tmp3, Address::times_4,  0), carry);
9807   subl(tmp3, 1);
9808   jccb(Assembler::negative, L_done);
9809 
9810   shrq(carry, 32);
9811   movl(Address(z, tmp3, Address::times_4,  0), carry);
9812   jmp(L_second_loop);
9813 
9814   // Next infrequent code is moved outside loops.
9815   bind(L_last_x);
9816   if (UseBMI2Instructions) {
9817     movl(rdx, Address(x,  0));
9818   } else {
9819     movl(x_xstart, Address(x,  0));
9820   }
9821   jmp(L_third_loop_prologue);
9822 
9823   bind(L_done);
9824 
9825   pop(zlen);
9826   pop(xlen);
9827 
9828   pop(tmp5);
9829   pop(tmp4);
9830   pop(tmp3);
9831   pop(tmp2);
9832   pop(tmp1);
9833 }
9834 
9835 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9836   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9837   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9838   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9839   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9840   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9841   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9842   Label SAME_TILL_END, DONE;
9843   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9844 
9845   //scale is in rcx in both Win64 and Unix
9846   ShortBranchVerifier sbv(this);
9847 
9848   shlq(length);
9849   xorq(result, result);
9850 
9851   if ((UseAVX > 2) &&
9852       VM_Version::supports_avx512vlbw()) {
9853     set_vector_masking();  // opening of the stub context for programming mask registers
9854     cmpq(length, 64);
9855     jcc(Assembler::less, VECTOR32_TAIL);
9856     movq(tmp1, length);
9857     andq(tmp1, 0x3F);      // tail count
9858     andq(length, ~(0x3F)); //vector count
9859 
9860     bind(VECTOR64_LOOP);
9861     // AVX512 code to compare 64 byte vectors.
9862     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9863     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9864     kortestql(k7, k7);
9865     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9866     addq(result, 64);
9867     subq(length, 64);
9868     jccb(Assembler::notZero, VECTOR64_LOOP);
9869 
9870     //bind(VECTOR64_TAIL);
9871     testq(tmp1, tmp1);
9872     jcc(Assembler::zero, SAME_TILL_END);
9873 
9874     bind(VECTOR64_TAIL);
9875     // AVX512 code to compare upto 63 byte vectors.
9876     // Save k1
9877     kmovql(k3, k1);
9878     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9879     shlxq(tmp2, tmp2, tmp1);
9880     notq(tmp2);
9881     kmovql(k1, tmp2);
9882 
9883     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9884     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9885 
9886     ktestql(k7, k1);
9887     // Restore k1
9888     kmovql(k1, k3);
9889     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9890 
9891     bind(VECTOR64_NOT_EQUAL);
9892     kmovql(tmp1, k7);
9893     notq(tmp1);
9894     tzcntq(tmp1, tmp1);
9895     addq(result, tmp1);
9896     shrq(result);
9897     jmp(DONE);
9898     bind(VECTOR32_TAIL);
9899     clear_vector_masking();   // closing of the stub context for programming mask registers
9900   }
9901 
9902   cmpq(length, 8);
9903   jcc(Assembler::equal, VECTOR8_LOOP);
9904   jcc(Assembler::less, VECTOR4_TAIL);
9905 
9906   if (UseAVX >= 2) {
9907 
9908     cmpq(length, 16);
9909     jcc(Assembler::equal, VECTOR16_LOOP);
9910     jcc(Assembler::less, VECTOR8_LOOP);
9911 
9912     cmpq(length, 32);
9913     jccb(Assembler::less, VECTOR16_TAIL);
9914 
9915     subq(length, 32);
9916     bind(VECTOR32_LOOP);
9917     vmovdqu(rymm0, Address(obja, result));
9918     vmovdqu(rymm1, Address(objb, result));
9919     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9920     vptest(rymm2, rymm2);
9921     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9922     addq(result, 32);
9923     subq(length, 32);
9924     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9925     addq(length, 32);
9926     jcc(Assembler::equal, SAME_TILL_END);
9927     //falling through if less than 32 bytes left //close the branch here.
9928 
9929     bind(VECTOR16_TAIL);
9930     cmpq(length, 16);
9931     jccb(Assembler::less, VECTOR8_TAIL);
9932     bind(VECTOR16_LOOP);
9933     movdqu(rymm0, Address(obja, result));
9934     movdqu(rymm1, Address(objb, result));
9935     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9936     ptest(rymm2, rymm2);
9937     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9938     addq(result, 16);
9939     subq(length, 16);
9940     jcc(Assembler::equal, SAME_TILL_END);
9941     //falling through if less than 16 bytes left
9942   } else {//regular intrinsics
9943 
9944     cmpq(length, 16);
9945     jccb(Assembler::less, VECTOR8_TAIL);
9946 
9947     subq(length, 16);
9948     bind(VECTOR16_LOOP);
9949     movdqu(rymm0, Address(obja, result));
9950     movdqu(rymm1, Address(objb, result));
9951     pxor(rymm0, rymm1);
9952     ptest(rymm0, rymm0);
9953     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9954     addq(result, 16);
9955     subq(length, 16);
9956     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9957     addq(length, 16);
9958     jcc(Assembler::equal, SAME_TILL_END);
9959     //falling through if less than 16 bytes left
9960   }
9961 
9962   bind(VECTOR8_TAIL);
9963   cmpq(length, 8);
9964   jccb(Assembler::less, VECTOR4_TAIL);
9965   bind(VECTOR8_LOOP);
9966   movq(tmp1, Address(obja, result));
9967   movq(tmp2, Address(objb, result));
9968   xorq(tmp1, tmp2);
9969   testq(tmp1, tmp1);
9970   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9971   addq(result, 8);
9972   subq(length, 8);
9973   jcc(Assembler::equal, SAME_TILL_END);
9974   //falling through if less than 8 bytes left
9975 
9976   bind(VECTOR4_TAIL);
9977   cmpq(length, 4);
9978   jccb(Assembler::less, BYTES_TAIL);
9979   bind(VECTOR4_LOOP);
9980   movl(tmp1, Address(obja, result));
9981   xorl(tmp1, Address(objb, result));
9982   testl(tmp1, tmp1);
9983   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9984   addq(result, 4);
9985   subq(length, 4);
9986   jcc(Assembler::equal, SAME_TILL_END);
9987   //falling through if less than 4 bytes left
9988 
9989   bind(BYTES_TAIL);
9990   bind(BYTES_LOOP);
9991   load_unsigned_byte(tmp1, Address(obja, result));
9992   load_unsigned_byte(tmp2, Address(objb, result));
9993   xorl(tmp1, tmp2);
9994   testl(tmp1, tmp1);
9995   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9996   decq(length);
9997   jccb(Assembler::zero, SAME_TILL_END);
9998   incq(result);
9999   load_unsigned_byte(tmp1, Address(obja, result));
10000   load_unsigned_byte(tmp2, Address(objb, result));
10001   xorl(tmp1, tmp2);
10002   testl(tmp1, tmp1);
10003   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
10004   decq(length);
10005   jccb(Assembler::zero, SAME_TILL_END);
10006   incq(result);
10007   load_unsigned_byte(tmp1, Address(obja, result));
10008   load_unsigned_byte(tmp2, Address(objb, result));
10009   xorl(tmp1, tmp2);
10010   testl(tmp1, tmp1);
10011   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
10012   jmpb(SAME_TILL_END);
10013 
10014   if (UseAVX >= 2) {
10015     bind(VECTOR32_NOT_EQUAL);
10016     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
10017     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
10018     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
10019     vpmovmskb(tmp1, rymm0);
10020     bsfq(tmp1, tmp1);
10021     addq(result, tmp1);
10022     shrq(result);
10023     jmpb(DONE);
10024   }
10025 
10026   bind(VECTOR16_NOT_EQUAL);
10027   if (UseAVX >= 2) {
10028     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
10029     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
10030     pxor(rymm0, rymm2);
10031   } else {
10032     pcmpeqb(rymm2, rymm2);
10033     pxor(rymm0, rymm1);
10034     pcmpeqb(rymm0, rymm1);
10035     pxor(rymm0, rymm2);
10036   }
10037   pmovmskb(tmp1, rymm0);
10038   bsfq(tmp1, tmp1);
10039   addq(result, tmp1);
10040   shrq(result);
10041   jmpb(DONE);
10042 
10043   bind(VECTOR8_NOT_EQUAL);
10044   bind(VECTOR4_NOT_EQUAL);
10045   bsfq(tmp1, tmp1);
10046   shrq(tmp1, 3);
10047   addq(result, tmp1);
10048   bind(BYTES_NOT_EQUAL);
10049   shrq(result);
10050   jmpb(DONE);
10051 
10052   bind(SAME_TILL_END);
10053   mov64(result, -1);
10054 
10055   bind(DONE);
10056 }
10057 
10058 //Helper functions for square_to_len()
10059 
10060 /**
10061  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
10062  * Preserves x and z and modifies rest of the registers.
10063  */
10064 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10065   // Perform square and right shift by 1
10066   // Handle odd xlen case first, then for even xlen do the following
10067   // jlong carry = 0;
10068   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
10069   //     huge_128 product = x[j:j+1] * x[j:j+1];
10070   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
10071   //     z[i+2:i+3] = (jlong)(product >>> 1);
10072   //     carry = (jlong)product;
10073   // }
10074 
10075   xorq(tmp5, tmp5);     // carry
10076   xorq(rdxReg, rdxReg);
10077   xorl(tmp1, tmp1);     // index for x
10078   xorl(tmp4, tmp4);     // index for z
10079 
10080   Label L_first_loop, L_first_loop_exit;
10081 
10082   testl(xlen, 1);
10083   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
10084 
10085   // Square and right shift by 1 the odd element using 32 bit multiply
10086   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
10087   imulq(raxReg, raxReg);
10088   shrq(raxReg, 1);
10089   adcq(tmp5, 0);
10090   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
10091   incrementl(tmp1);
10092   addl(tmp4, 2);
10093 
10094   // Square and  right shift by 1 the rest using 64 bit multiply
10095   bind(L_first_loop);
10096   cmpptr(tmp1, xlen);
10097   jccb(Assembler::equal, L_first_loop_exit);
10098 
10099   // Square
10100   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
10101   rorq(raxReg, 32);    // convert big-endian to little-endian
10102   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
10103 
10104   // Right shift by 1 and save carry
10105   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
10106   rcrq(rdxReg, 1);
10107   rcrq(raxReg, 1);
10108   adcq(tmp5, 0);
10109 
10110   // Store result in z
10111   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
10112   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
10113 
10114   // Update indices for x and z
10115   addl(tmp1, 2);
10116   addl(tmp4, 4);
10117   jmp(L_first_loop);
10118 
10119   bind(L_first_loop_exit);
10120 }
10121 
10122 
10123 /**
10124  * Perform the following multiply add operation using BMI2 instructions
10125  * carry:sum = sum + op1*op2 + carry
10126  * op2 should be in rdx
10127  * op2 is preserved, all other registers are modified
10128  */
10129 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
10130   // assert op2 is rdx
10131   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
10132   addq(sum, carry);
10133   adcq(tmp2, 0);
10134   addq(sum, op1);
10135   adcq(tmp2, 0);
10136   movq(carry, tmp2);
10137 }
10138 
10139 /**
10140  * Perform the following multiply add operation:
10141  * carry:sum = sum + op1*op2 + carry
10142  * Preserves op1, op2 and modifies rest of registers
10143  */
10144 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
10145   // rdx:rax = op1 * op2
10146   movq(raxReg, op2);
10147   mulq(op1);
10148 
10149   //  rdx:rax = sum + carry + rdx:rax
10150   addq(sum, carry);
10151   adcq(rdxReg, 0);
10152   addq(sum, raxReg);
10153   adcq(rdxReg, 0);
10154 
10155   // carry:sum = rdx:sum
10156   movq(carry, rdxReg);
10157 }
10158 
10159 /**
10160  * Add 64 bit long carry into z[] with carry propogation.
10161  * Preserves z and carry register values and modifies rest of registers.
10162  *
10163  */
10164 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
10165   Label L_fourth_loop, L_fourth_loop_exit;
10166 
10167   movl(tmp1, 1);
10168   subl(zlen, 2);
10169   addq(Address(z, zlen, Address::times_4, 0), carry);
10170 
10171   bind(L_fourth_loop);
10172   jccb(Assembler::carryClear, L_fourth_loop_exit);
10173   subl(zlen, 2);
10174   jccb(Assembler::negative, L_fourth_loop_exit);
10175   addq(Address(z, zlen, Address::times_4, 0), tmp1);
10176   jmp(L_fourth_loop);
10177   bind(L_fourth_loop_exit);
10178 }
10179 
10180 /**
10181  * Shift z[] left by 1 bit.
10182  * Preserves x, len, z and zlen registers and modifies rest of the registers.
10183  *
10184  */
10185 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
10186 
10187   Label L_fifth_loop, L_fifth_loop_exit;
10188 
10189   // Fifth loop
10190   // Perform primitiveLeftShift(z, zlen, 1)
10191 
10192   const Register prev_carry = tmp1;
10193   const Register new_carry = tmp4;
10194   const Register value = tmp2;
10195   const Register zidx = tmp3;
10196 
10197   // int zidx, carry;
10198   // long value;
10199   // carry = 0;
10200   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
10201   //    (carry:value)  = (z[i] << 1) | carry ;
10202   //    z[i] = value;
10203   // }
10204 
10205   movl(zidx, zlen);
10206   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
10207 
10208   bind(L_fifth_loop);
10209   decl(zidx);  // Use decl to preserve carry flag
10210   decl(zidx);
10211   jccb(Assembler::negative, L_fifth_loop_exit);
10212 
10213   if (UseBMI2Instructions) {
10214      movq(value, Address(z, zidx, Address::times_4, 0));
10215      rclq(value, 1);
10216      rorxq(value, value, 32);
10217      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10218   }
10219   else {
10220     // clear new_carry
10221     xorl(new_carry, new_carry);
10222 
10223     // Shift z[i] by 1, or in previous carry and save new carry
10224     movq(value, Address(z, zidx, Address::times_4, 0));
10225     shlq(value, 1);
10226     adcl(new_carry, 0);
10227 
10228     orq(value, prev_carry);
10229     rorq(value, 0x20);
10230     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10231 
10232     // Set previous carry = new carry
10233     movl(prev_carry, new_carry);
10234   }
10235   jmp(L_fifth_loop);
10236 
10237   bind(L_fifth_loop_exit);
10238 }
10239 
10240 
10241 /**
10242  * Code for BigInteger::squareToLen() intrinsic
10243  *
10244  * rdi: x
10245  * rsi: len
10246  * r8:  z
10247  * rcx: zlen
10248  * r12: tmp1
10249  * r13: tmp2
10250  * r14: tmp3
10251  * r15: tmp4
10252  * rbx: tmp5
10253  *
10254  */
10255 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) {
10256 
10257   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;
10258   push(tmp1);
10259   push(tmp2);
10260   push(tmp3);
10261   push(tmp4);
10262   push(tmp5);
10263 
10264   // First loop
10265   // Store the squares, right shifted one bit (i.e., divided by 2).
10266   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
10267 
10268   // Add in off-diagonal sums.
10269   //
10270   // Second, third (nested) and fourth loops.
10271   // zlen +=2;
10272   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
10273   //    carry = 0;
10274   //    long op2 = x[xidx:xidx+1];
10275   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
10276   //       k -= 2;
10277   //       long op1 = x[j:j+1];
10278   //       long sum = z[k:k+1];
10279   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
10280   //       z[k:k+1] = sum;
10281   //    }
10282   //    add_one_64(z, k, carry, tmp_regs);
10283   // }
10284 
10285   const Register carry = tmp5;
10286   const Register sum = tmp3;
10287   const Register op1 = tmp4;
10288   Register op2 = tmp2;
10289 
10290   push(zlen);
10291   push(len);
10292   addl(zlen,2);
10293   bind(L_second_loop);
10294   xorq(carry, carry);
10295   subl(zlen, 4);
10296   subl(len, 2);
10297   push(zlen);
10298   push(len);
10299   cmpl(len, 0);
10300   jccb(Assembler::lessEqual, L_second_loop_exit);
10301 
10302   // Multiply an array by one 64 bit long.
10303   if (UseBMI2Instructions) {
10304     op2 = rdxReg;
10305     movq(op2, Address(x, len, Address::times_4,  0));
10306     rorxq(op2, op2, 32);
10307   }
10308   else {
10309     movq(op2, Address(x, len, Address::times_4,  0));
10310     rorq(op2, 32);
10311   }
10312 
10313   bind(L_third_loop);
10314   decrementl(len);
10315   jccb(Assembler::negative, L_third_loop_exit);
10316   decrementl(len);
10317   jccb(Assembler::negative, L_last_x);
10318 
10319   movq(op1, Address(x, len, Address::times_4,  0));
10320   rorq(op1, 32);
10321 
10322   bind(L_multiply);
10323   subl(zlen, 2);
10324   movq(sum, Address(z, zlen, Address::times_4,  0));
10325 
10326   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10327   if (UseBMI2Instructions) {
10328     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10329   }
10330   else {
10331     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10332   }
10333 
10334   movq(Address(z, zlen, Address::times_4, 0), sum);
10335 
10336   jmp(L_third_loop);
10337   bind(L_third_loop_exit);
10338 
10339   // Fourth loop
10340   // Add 64 bit long carry into z with carry propogation.
10341   // Uses offsetted zlen.
10342   add_one_64(z, zlen, carry, tmp1);
10343 
10344   pop(len);
10345   pop(zlen);
10346   jmp(L_second_loop);
10347 
10348   // Next infrequent code is moved outside loops.
10349   bind(L_last_x);
10350   movl(op1, Address(x, 0));
10351   jmp(L_multiply);
10352 
10353   bind(L_second_loop_exit);
10354   pop(len);
10355   pop(zlen);
10356   pop(len);
10357   pop(zlen);
10358 
10359   // Fifth loop
10360   // Shift z left 1 bit.
10361   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10362 
10363   // z[zlen-1] |= x[len-1] & 1;
10364   movl(tmp3, Address(x, len, Address::times_4, -4));
10365   andl(tmp3, 1);
10366   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10367 
10368   pop(tmp5);
10369   pop(tmp4);
10370   pop(tmp3);
10371   pop(tmp2);
10372   pop(tmp1);
10373 }
10374 
10375 /**
10376  * Helper function for mul_add()
10377  * Multiply the in[] by int k and add to out[] starting at offset offs using
10378  * 128 bit by 32 bit multiply and return the carry in tmp5.
10379  * Only quad int aligned length of in[] is operated on in this function.
10380  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10381  * This function preserves out, in and k registers.
10382  * len and offset point to the appropriate index in "in" & "out" correspondingly
10383  * tmp5 has the carry.
10384  * other registers are temporary and are modified.
10385  *
10386  */
10387 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10388   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10389   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10390 
10391   Label L_first_loop, L_first_loop_exit;
10392 
10393   movl(tmp1, len);
10394   shrl(tmp1, 2);
10395 
10396   bind(L_first_loop);
10397   subl(tmp1, 1);
10398   jccb(Assembler::negative, L_first_loop_exit);
10399 
10400   subl(len, 4);
10401   subl(offset, 4);
10402 
10403   Register op2 = tmp2;
10404   const Register sum = tmp3;
10405   const Register op1 = tmp4;
10406   const Register carry = tmp5;
10407 
10408   if (UseBMI2Instructions) {
10409     op2 = rdxReg;
10410   }
10411 
10412   movq(op1, Address(in, len, Address::times_4,  8));
10413   rorq(op1, 32);
10414   movq(sum, Address(out, offset, Address::times_4,  8));
10415   rorq(sum, 32);
10416   if (UseBMI2Instructions) {
10417     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10418   }
10419   else {
10420     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10421   }
10422   // Store back in big endian from little endian
10423   rorq(sum, 0x20);
10424   movq(Address(out, offset, Address::times_4,  8), sum);
10425 
10426   movq(op1, Address(in, len, Address::times_4,  0));
10427   rorq(op1, 32);
10428   movq(sum, Address(out, offset, Address::times_4,  0));
10429   rorq(sum, 32);
10430   if (UseBMI2Instructions) {
10431     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10432   }
10433   else {
10434     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10435   }
10436   // Store back in big endian from little endian
10437   rorq(sum, 0x20);
10438   movq(Address(out, offset, Address::times_4,  0), sum);
10439 
10440   jmp(L_first_loop);
10441   bind(L_first_loop_exit);
10442 }
10443 
10444 /**
10445  * Code for BigInteger::mulAdd() intrinsic
10446  *
10447  * rdi: out
10448  * rsi: in
10449  * r11: offs (out.length - offset)
10450  * rcx: len
10451  * r8:  k
10452  * r12: tmp1
10453  * r13: tmp2
10454  * r14: tmp3
10455  * r15: tmp4
10456  * rbx: tmp5
10457  * Multiply the in[] by word k and add to out[], return the carry in rax
10458  */
10459 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10460    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10461    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10462 
10463   Label L_carry, L_last_in, L_done;
10464 
10465 // carry = 0;
10466 // for (int j=len-1; j >= 0; j--) {
10467 //    long product = (in[j] & LONG_MASK) * kLong +
10468 //                   (out[offs] & LONG_MASK) + carry;
10469 //    out[offs--] = (int)product;
10470 //    carry = product >>> 32;
10471 // }
10472 //
10473   push(tmp1);
10474   push(tmp2);
10475   push(tmp3);
10476   push(tmp4);
10477   push(tmp5);
10478 
10479   Register op2 = tmp2;
10480   const Register sum = tmp3;
10481   const Register op1 = tmp4;
10482   const Register carry =  tmp5;
10483 
10484   if (UseBMI2Instructions) {
10485     op2 = rdxReg;
10486     movl(op2, k);
10487   }
10488   else {
10489     movl(op2, k);
10490   }
10491 
10492   xorq(carry, carry);
10493 
10494   //First loop
10495 
10496   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10497   //The carry is in tmp5
10498   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10499 
10500   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10501   decrementl(len);
10502   jccb(Assembler::negative, L_carry);
10503   decrementl(len);
10504   jccb(Assembler::negative, L_last_in);
10505 
10506   movq(op1, Address(in, len, Address::times_4,  0));
10507   rorq(op1, 32);
10508 
10509   subl(offs, 2);
10510   movq(sum, Address(out, offs, Address::times_4,  0));
10511   rorq(sum, 32);
10512 
10513   if (UseBMI2Instructions) {
10514     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10515   }
10516   else {
10517     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10518   }
10519 
10520   // Store back in big endian from little endian
10521   rorq(sum, 0x20);
10522   movq(Address(out, offs, Address::times_4,  0), sum);
10523 
10524   testl(len, len);
10525   jccb(Assembler::zero, L_carry);
10526 
10527   //Multiply the last in[] entry, if any
10528   bind(L_last_in);
10529   movl(op1, Address(in, 0));
10530   movl(sum, Address(out, offs, Address::times_4,  -4));
10531 
10532   movl(raxReg, k);
10533   mull(op1); //tmp4 * eax -> edx:eax
10534   addl(sum, carry);
10535   adcl(rdxReg, 0);
10536   addl(sum, raxReg);
10537   adcl(rdxReg, 0);
10538   movl(carry, rdxReg);
10539 
10540   movl(Address(out, offs, Address::times_4,  -4), sum);
10541 
10542   bind(L_carry);
10543   //return tmp5/carry as carry in rax
10544   movl(rax, carry);
10545 
10546   bind(L_done);
10547   pop(tmp5);
10548   pop(tmp4);
10549   pop(tmp3);
10550   pop(tmp2);
10551   pop(tmp1);
10552 }
10553 #endif
10554 
10555 /**
10556  * Emits code to update CRC-32 with a byte value according to constants in table
10557  *
10558  * @param [in,out]crc   Register containing the crc.
10559  * @param [in]val       Register containing the byte to fold into the CRC.
10560  * @param [in]table     Register containing the table of crc constants.
10561  *
10562  * uint32_t crc;
10563  * val = crc_table[(val ^ crc) & 0xFF];
10564  * crc = val ^ (crc >> 8);
10565  *
10566  */
10567 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10568   xorl(val, crc);
10569   andl(val, 0xFF);
10570   shrl(crc, 8); // unsigned shift
10571   xorl(crc, Address(table, val, Address::times_4, 0));
10572 }
10573 
10574 /**
10575  * Fold 128-bit data chunk
10576  */
10577 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10578   if (UseAVX > 0) {
10579     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10580     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10581     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10582     pxor(xcrc, xtmp);
10583   } else {
10584     movdqa(xtmp, xcrc);
10585     pclmulhdq(xtmp, xK);   // [123:64]
10586     pclmulldq(xcrc, xK);   // [63:0]
10587     pxor(xcrc, xtmp);
10588     movdqu(xtmp, Address(buf, offset));
10589     pxor(xcrc, xtmp);
10590   }
10591 }
10592 
10593 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10594   if (UseAVX > 0) {
10595     vpclmulhdq(xtmp, xK, xcrc);
10596     vpclmulldq(xcrc, xK, xcrc);
10597     pxor(xcrc, xbuf);
10598     pxor(xcrc, xtmp);
10599   } else {
10600     movdqa(xtmp, xcrc);
10601     pclmulhdq(xtmp, xK);
10602     pclmulldq(xcrc, xK);
10603     pxor(xcrc, xbuf);
10604     pxor(xcrc, xtmp);
10605   }
10606 }
10607 
10608 /**
10609  * 8-bit folds to compute 32-bit CRC
10610  *
10611  * uint64_t xcrc;
10612  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10613  */
10614 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10615   movdl(tmp, xcrc);
10616   andl(tmp, 0xFF);
10617   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10618   psrldq(xcrc, 1); // unsigned shift one byte
10619   pxor(xcrc, xtmp);
10620 }
10621 
10622 /**
10623  * uint32_t crc;
10624  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10625  */
10626 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10627   movl(tmp, crc);
10628   andl(tmp, 0xFF);
10629   shrl(crc, 8);
10630   xorl(crc, Address(table, tmp, Address::times_4, 0));
10631 }
10632 
10633 /**
10634  * @param crc   register containing existing CRC (32-bit)
10635  * @param buf   register pointing to input byte buffer (byte*)
10636  * @param len   register containing number of bytes
10637  * @param table register that will contain address of CRC table
10638  * @param tmp   scratch register
10639  */
10640 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10641   assert_different_registers(crc, buf, len, table, tmp, rax);
10642 
10643   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10644   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10645 
10646   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10647   // context for the registers used, where all instructions below are using 128-bit mode
10648   // On EVEX without VL and BW, these instructions will all be AVX.
10649   if (VM_Version::supports_avx512vlbw()) {
10650     movl(tmp, 0xffff);
10651     kmovwl(k1, tmp);
10652   }
10653 
10654   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10655   notl(crc); // ~crc
10656   cmpl(len, 16);
10657   jcc(Assembler::less, L_tail);
10658 
10659   // Align buffer to 16 bytes
10660   movl(tmp, buf);
10661   andl(tmp, 0xF);
10662   jccb(Assembler::zero, L_aligned);
10663   subl(tmp,  16);
10664   addl(len, tmp);
10665 
10666   align(4);
10667   BIND(L_align_loop);
10668   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10669   update_byte_crc32(crc, rax, table);
10670   increment(buf);
10671   incrementl(tmp);
10672   jccb(Assembler::less, L_align_loop);
10673 
10674   BIND(L_aligned);
10675   movl(tmp, len); // save
10676   shrl(len, 4);
10677   jcc(Assembler::zero, L_tail_restore);
10678 
10679   // Fold crc into first bytes of vector
10680   movdqa(xmm1, Address(buf, 0));
10681   movdl(rax, xmm1);
10682   xorl(crc, rax);
10683   if (VM_Version::supports_sse4_1()) {
10684     pinsrd(xmm1, crc, 0);
10685   } else {
10686     pinsrw(xmm1, crc, 0);
10687     shrl(crc, 16);
10688     pinsrw(xmm1, crc, 1);
10689   }
10690   addptr(buf, 16);
10691   subl(len, 4); // len > 0
10692   jcc(Assembler::less, L_fold_tail);
10693 
10694   movdqa(xmm2, Address(buf,  0));
10695   movdqa(xmm3, Address(buf, 16));
10696   movdqa(xmm4, Address(buf, 32));
10697   addptr(buf, 48);
10698   subl(len, 3);
10699   jcc(Assembler::lessEqual, L_fold_512b);
10700 
10701   // Fold total 512 bits of polynomial on each iteration,
10702   // 128 bits per each of 4 parallel streams.
10703   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10704 
10705   align(32);
10706   BIND(L_fold_512b_loop);
10707   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10708   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10709   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10710   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10711   addptr(buf, 64);
10712   subl(len, 4);
10713   jcc(Assembler::greater, L_fold_512b_loop);
10714 
10715   // Fold 512 bits to 128 bits.
10716   BIND(L_fold_512b);
10717   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10718   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10719   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10720   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10721 
10722   // Fold the rest of 128 bits data chunks
10723   BIND(L_fold_tail);
10724   addl(len, 3);
10725   jccb(Assembler::lessEqual, L_fold_128b);
10726   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10727 
10728   BIND(L_fold_tail_loop);
10729   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10730   addptr(buf, 16);
10731   decrementl(len);
10732   jccb(Assembler::greater, L_fold_tail_loop);
10733 
10734   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10735   BIND(L_fold_128b);
10736   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10737   if (UseAVX > 0) {
10738     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10739     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10740     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10741   } else {
10742     movdqa(xmm2, xmm0);
10743     pclmulqdq(xmm2, xmm1, 0x1);
10744     movdqa(xmm3, xmm0);
10745     pand(xmm3, xmm2);
10746     pclmulqdq(xmm0, xmm3, 0x1);
10747   }
10748   psrldq(xmm1, 8);
10749   psrldq(xmm2, 4);
10750   pxor(xmm0, xmm1);
10751   pxor(xmm0, xmm2);
10752 
10753   // 8 8-bit folds to compute 32-bit CRC.
10754   for (int j = 0; j < 4; j++) {
10755     fold_8bit_crc32(xmm0, table, xmm1, rax);
10756   }
10757   movdl(crc, xmm0); // mov 32 bits to general register
10758   for (int j = 0; j < 4; j++) {
10759     fold_8bit_crc32(crc, table, rax);
10760   }
10761 
10762   BIND(L_tail_restore);
10763   movl(len, tmp); // restore
10764   BIND(L_tail);
10765   andl(len, 0xf);
10766   jccb(Assembler::zero, L_exit);
10767 
10768   // Fold the rest of bytes
10769   align(4);
10770   BIND(L_tail_loop);
10771   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10772   update_byte_crc32(crc, rax, table);
10773   increment(buf);
10774   decrementl(len);
10775   jccb(Assembler::greater, L_tail_loop);
10776 
10777   BIND(L_exit);
10778   notl(crc); // ~c
10779 }
10780 
10781 #ifdef _LP64
10782 // S. Gueron / Information Processing Letters 112 (2012) 184
10783 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10784 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10785 // Output: the 64-bit carry-less product of B * CONST
10786 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10787                                      Register tmp1, Register tmp2, Register tmp3) {
10788   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10789   if (n > 0) {
10790     addq(tmp3, n * 256 * 8);
10791   }
10792   //    Q1 = TABLEExt[n][B & 0xFF];
10793   movl(tmp1, in);
10794   andl(tmp1, 0x000000FF);
10795   shll(tmp1, 3);
10796   addq(tmp1, tmp3);
10797   movq(tmp1, Address(tmp1, 0));
10798 
10799   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10800   movl(tmp2, in);
10801   shrl(tmp2, 8);
10802   andl(tmp2, 0x000000FF);
10803   shll(tmp2, 3);
10804   addq(tmp2, tmp3);
10805   movq(tmp2, Address(tmp2, 0));
10806 
10807   shlq(tmp2, 8);
10808   xorq(tmp1, tmp2);
10809 
10810   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10811   movl(tmp2, in);
10812   shrl(tmp2, 16);
10813   andl(tmp2, 0x000000FF);
10814   shll(tmp2, 3);
10815   addq(tmp2, tmp3);
10816   movq(tmp2, Address(tmp2, 0));
10817 
10818   shlq(tmp2, 16);
10819   xorq(tmp1, tmp2);
10820 
10821   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10822   shrl(in, 24);
10823   andl(in, 0x000000FF);
10824   shll(in, 3);
10825   addq(in, tmp3);
10826   movq(in, Address(in, 0));
10827 
10828   shlq(in, 24);
10829   xorq(in, tmp1);
10830   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10831 }
10832 
10833 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10834                                       Register in_out,
10835                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10836                                       XMMRegister w_xtmp2,
10837                                       Register tmp1,
10838                                       Register n_tmp2, Register n_tmp3) {
10839   if (is_pclmulqdq_supported) {
10840     movdl(w_xtmp1, in_out); // modified blindly
10841 
10842     movl(tmp1, const_or_pre_comp_const_index);
10843     movdl(w_xtmp2, tmp1);
10844     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10845 
10846     movdq(in_out, w_xtmp1);
10847   } else {
10848     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10849   }
10850 }
10851 
10852 // Recombination Alternative 2: No bit-reflections
10853 // T1 = (CRC_A * U1) << 1
10854 // T2 = (CRC_B * U2) << 1
10855 // C1 = T1 >> 32
10856 // C2 = T2 >> 32
10857 // T1 = T1 & 0xFFFFFFFF
10858 // T2 = T2 & 0xFFFFFFFF
10859 // T1 = CRC32(0, T1)
10860 // T2 = CRC32(0, T2)
10861 // C1 = C1 ^ T1
10862 // C2 = C2 ^ T2
10863 // CRC = C1 ^ C2 ^ CRC_C
10864 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,
10865                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10866                                      Register tmp1, Register tmp2,
10867                                      Register n_tmp3) {
10868   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10869   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10870   shlq(in_out, 1);
10871   movl(tmp1, in_out);
10872   shrq(in_out, 32);
10873   xorl(tmp2, tmp2);
10874   crc32(tmp2, tmp1, 4);
10875   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10876   shlq(in1, 1);
10877   movl(tmp1, in1);
10878   shrq(in1, 32);
10879   xorl(tmp2, tmp2);
10880   crc32(tmp2, tmp1, 4);
10881   xorl(in1, tmp2);
10882   xorl(in_out, in1);
10883   xorl(in_out, in2);
10884 }
10885 
10886 // Set N to predefined value
10887 // Subtract from a lenght of a buffer
10888 // execute in a loop:
10889 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10890 // for i = 1 to N do
10891 //  CRC_A = CRC32(CRC_A, A[i])
10892 //  CRC_B = CRC32(CRC_B, B[i])
10893 //  CRC_C = CRC32(CRC_C, C[i])
10894 // end for
10895 // Recombine
10896 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,
10897                                        Register in_out1, Register in_out2, Register in_out3,
10898                                        Register tmp1, Register tmp2, Register tmp3,
10899                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10900                                        Register tmp4, Register tmp5,
10901                                        Register n_tmp6) {
10902   Label L_processPartitions;
10903   Label L_processPartition;
10904   Label L_exit;
10905 
10906   bind(L_processPartitions);
10907   cmpl(in_out1, 3 * size);
10908   jcc(Assembler::less, L_exit);
10909     xorl(tmp1, tmp1);
10910     xorl(tmp2, tmp2);
10911     movq(tmp3, in_out2);
10912     addq(tmp3, size);
10913 
10914     bind(L_processPartition);
10915       crc32(in_out3, Address(in_out2, 0), 8);
10916       crc32(tmp1, Address(in_out2, size), 8);
10917       crc32(tmp2, Address(in_out2, size * 2), 8);
10918       addq(in_out2, 8);
10919       cmpq(in_out2, tmp3);
10920       jcc(Assembler::less, L_processPartition);
10921     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10922             w_xtmp1, w_xtmp2, w_xtmp3,
10923             tmp4, tmp5,
10924             n_tmp6);
10925     addq(in_out2, 2 * size);
10926     subl(in_out1, 3 * size);
10927     jmp(L_processPartitions);
10928 
10929   bind(L_exit);
10930 }
10931 #else
10932 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10933                                      Register tmp1, Register tmp2, Register tmp3,
10934                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10935   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10936   if (n > 0) {
10937     addl(tmp3, n * 256 * 8);
10938   }
10939   //    Q1 = TABLEExt[n][B & 0xFF];
10940   movl(tmp1, in_out);
10941   andl(tmp1, 0x000000FF);
10942   shll(tmp1, 3);
10943   addl(tmp1, tmp3);
10944   movq(xtmp1, Address(tmp1, 0));
10945 
10946   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10947   movl(tmp2, in_out);
10948   shrl(tmp2, 8);
10949   andl(tmp2, 0x000000FF);
10950   shll(tmp2, 3);
10951   addl(tmp2, tmp3);
10952   movq(xtmp2, Address(tmp2, 0));
10953 
10954   psllq(xtmp2, 8);
10955   pxor(xtmp1, xtmp2);
10956 
10957   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10958   movl(tmp2, in_out);
10959   shrl(tmp2, 16);
10960   andl(tmp2, 0x000000FF);
10961   shll(tmp2, 3);
10962   addl(tmp2, tmp3);
10963   movq(xtmp2, Address(tmp2, 0));
10964 
10965   psllq(xtmp2, 16);
10966   pxor(xtmp1, xtmp2);
10967 
10968   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10969   shrl(in_out, 24);
10970   andl(in_out, 0x000000FF);
10971   shll(in_out, 3);
10972   addl(in_out, tmp3);
10973   movq(xtmp2, Address(in_out, 0));
10974 
10975   psllq(xtmp2, 24);
10976   pxor(xtmp1, xtmp2); // Result in CXMM
10977   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10978 }
10979 
10980 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10981                                       Register in_out,
10982                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10983                                       XMMRegister w_xtmp2,
10984                                       Register tmp1,
10985                                       Register n_tmp2, Register n_tmp3) {
10986   if (is_pclmulqdq_supported) {
10987     movdl(w_xtmp1, in_out);
10988 
10989     movl(tmp1, const_or_pre_comp_const_index);
10990     movdl(w_xtmp2, tmp1);
10991     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10992     // Keep result in XMM since GPR is 32 bit in length
10993   } else {
10994     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10995   }
10996 }
10997 
10998 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,
10999                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11000                                      Register tmp1, Register tmp2,
11001                                      Register n_tmp3) {
11002   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
11003   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
11004 
11005   psllq(w_xtmp1, 1);
11006   movdl(tmp1, w_xtmp1);
11007   psrlq(w_xtmp1, 32);
11008   movdl(in_out, w_xtmp1);
11009 
11010   xorl(tmp2, tmp2);
11011   crc32(tmp2, tmp1, 4);
11012   xorl(in_out, tmp2);
11013 
11014   psllq(w_xtmp2, 1);
11015   movdl(tmp1, w_xtmp2);
11016   psrlq(w_xtmp2, 32);
11017   movdl(in1, w_xtmp2);
11018 
11019   xorl(tmp2, tmp2);
11020   crc32(tmp2, tmp1, 4);
11021   xorl(in1, tmp2);
11022   xorl(in_out, in1);
11023   xorl(in_out, in2);
11024 }
11025 
11026 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,
11027                                        Register in_out1, Register in_out2, Register in_out3,
11028                                        Register tmp1, Register tmp2, Register tmp3,
11029                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11030                                        Register tmp4, Register tmp5,
11031                                        Register n_tmp6) {
11032   Label L_processPartitions;
11033   Label L_processPartition;
11034   Label L_exit;
11035 
11036   bind(L_processPartitions);
11037   cmpl(in_out1, 3 * size);
11038   jcc(Assembler::less, L_exit);
11039     xorl(tmp1, tmp1);
11040     xorl(tmp2, tmp2);
11041     movl(tmp3, in_out2);
11042     addl(tmp3, size);
11043 
11044     bind(L_processPartition);
11045       crc32(in_out3, Address(in_out2, 0), 4);
11046       crc32(tmp1, Address(in_out2, size), 4);
11047       crc32(tmp2, Address(in_out2, size*2), 4);
11048       crc32(in_out3, Address(in_out2, 0+4), 4);
11049       crc32(tmp1, Address(in_out2, size+4), 4);
11050       crc32(tmp2, Address(in_out2, size*2+4), 4);
11051       addl(in_out2, 8);
11052       cmpl(in_out2, tmp3);
11053       jcc(Assembler::less, L_processPartition);
11054 
11055         push(tmp3);
11056         push(in_out1);
11057         push(in_out2);
11058         tmp4 = tmp3;
11059         tmp5 = in_out1;
11060         n_tmp6 = in_out2;
11061 
11062       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
11063             w_xtmp1, w_xtmp2, w_xtmp3,
11064             tmp4, tmp5,
11065             n_tmp6);
11066 
11067         pop(in_out2);
11068         pop(in_out1);
11069         pop(tmp3);
11070 
11071     addl(in_out2, 2 * size);
11072     subl(in_out1, 3 * size);
11073     jmp(L_processPartitions);
11074 
11075   bind(L_exit);
11076 }
11077 #endif //LP64
11078 
11079 #ifdef _LP64
11080 // Algorithm 2: Pipelined usage of the CRC32 instruction.
11081 // Input: A buffer I of L bytes.
11082 // Output: the CRC32C value of the buffer.
11083 // Notations:
11084 // Write L = 24N + r, with N = floor (L/24).
11085 // r = L mod 24 (0 <= r < 24).
11086 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
11087 // N quadwords, and R consists of r bytes.
11088 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
11089 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
11090 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
11091 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
11092 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11093                                           Register tmp1, Register tmp2, Register tmp3,
11094                                           Register tmp4, Register tmp5, Register tmp6,
11095                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11096                                           bool is_pclmulqdq_supported) {
11097   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11098   Label L_wordByWord;
11099   Label L_byteByByteProlog;
11100   Label L_byteByByte;
11101   Label L_exit;
11102 
11103   if (is_pclmulqdq_supported ) {
11104     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11105     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
11106 
11107     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11108     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11109 
11110     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11111     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11112     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
11113   } else {
11114     const_or_pre_comp_const_index[0] = 1;
11115     const_or_pre_comp_const_index[1] = 0;
11116 
11117     const_or_pre_comp_const_index[2] = 3;
11118     const_or_pre_comp_const_index[3] = 2;
11119 
11120     const_or_pre_comp_const_index[4] = 5;
11121     const_or_pre_comp_const_index[5] = 4;
11122    }
11123   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11124                     in2, in1, in_out,
11125                     tmp1, tmp2, tmp3,
11126                     w_xtmp1, w_xtmp2, w_xtmp3,
11127                     tmp4, tmp5,
11128                     tmp6);
11129   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11130                     in2, in1, in_out,
11131                     tmp1, tmp2, tmp3,
11132                     w_xtmp1, w_xtmp2, w_xtmp3,
11133                     tmp4, tmp5,
11134                     tmp6);
11135   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11136                     in2, in1, in_out,
11137                     tmp1, tmp2, tmp3,
11138                     w_xtmp1, w_xtmp2, w_xtmp3,
11139                     tmp4, tmp5,
11140                     tmp6);
11141   movl(tmp1, in2);
11142   andl(tmp1, 0x00000007);
11143   negl(tmp1);
11144   addl(tmp1, in2);
11145   addq(tmp1, in1);
11146 
11147   BIND(L_wordByWord);
11148   cmpq(in1, tmp1);
11149   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11150     crc32(in_out, Address(in1, 0), 4);
11151     addq(in1, 4);
11152     jmp(L_wordByWord);
11153 
11154   BIND(L_byteByByteProlog);
11155   andl(in2, 0x00000007);
11156   movl(tmp2, 1);
11157 
11158   BIND(L_byteByByte);
11159   cmpl(tmp2, in2);
11160   jccb(Assembler::greater, L_exit);
11161     crc32(in_out, Address(in1, 0), 1);
11162     incq(in1);
11163     incl(tmp2);
11164     jmp(L_byteByByte);
11165 
11166   BIND(L_exit);
11167 }
11168 #else
11169 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11170                                           Register tmp1, Register  tmp2, Register tmp3,
11171                                           Register tmp4, Register  tmp5, Register tmp6,
11172                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11173                                           bool is_pclmulqdq_supported) {
11174   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11175   Label L_wordByWord;
11176   Label L_byteByByteProlog;
11177   Label L_byteByByte;
11178   Label L_exit;
11179 
11180   if (is_pclmulqdq_supported) {
11181     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11182     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
11183 
11184     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11185     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11186 
11187     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11188     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11189   } else {
11190     const_or_pre_comp_const_index[0] = 1;
11191     const_or_pre_comp_const_index[1] = 0;
11192 
11193     const_or_pre_comp_const_index[2] = 3;
11194     const_or_pre_comp_const_index[3] = 2;
11195 
11196     const_or_pre_comp_const_index[4] = 5;
11197     const_or_pre_comp_const_index[5] = 4;
11198   }
11199   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11200                     in2, in1, in_out,
11201                     tmp1, tmp2, tmp3,
11202                     w_xtmp1, w_xtmp2, w_xtmp3,
11203                     tmp4, tmp5,
11204                     tmp6);
11205   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11206                     in2, in1, in_out,
11207                     tmp1, tmp2, tmp3,
11208                     w_xtmp1, w_xtmp2, w_xtmp3,
11209                     tmp4, tmp5,
11210                     tmp6);
11211   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11212                     in2, in1, in_out,
11213                     tmp1, tmp2, tmp3,
11214                     w_xtmp1, w_xtmp2, w_xtmp3,
11215                     tmp4, tmp5,
11216                     tmp6);
11217   movl(tmp1, in2);
11218   andl(tmp1, 0x00000007);
11219   negl(tmp1);
11220   addl(tmp1, in2);
11221   addl(tmp1, in1);
11222 
11223   BIND(L_wordByWord);
11224   cmpl(in1, tmp1);
11225   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11226     crc32(in_out, Address(in1,0), 4);
11227     addl(in1, 4);
11228     jmp(L_wordByWord);
11229 
11230   BIND(L_byteByByteProlog);
11231   andl(in2, 0x00000007);
11232   movl(tmp2, 1);
11233 
11234   BIND(L_byteByByte);
11235   cmpl(tmp2, in2);
11236   jccb(Assembler::greater, L_exit);
11237     movb(tmp1, Address(in1, 0));
11238     crc32(in_out, tmp1, 1);
11239     incl(in1);
11240     incl(tmp2);
11241     jmp(L_byteByByte);
11242 
11243   BIND(L_exit);
11244 }
11245 #endif // LP64
11246 #undef BIND
11247 #undef BLOCK_COMMENT
11248 
11249 // Compress char[] array to byte[].
11250 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
11251 //   @HotSpotIntrinsicCandidate
11252 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
11253 //     for (int i = 0; i < len; i++) {
11254 //       int c = src[srcOff++];
11255 //       if (c >>> 8 != 0) {
11256 //         return 0;
11257 //       }
11258 //       dst[dstOff++] = (byte)c;
11259 //     }
11260 //     return len;
11261 //   }
11262 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
11263   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
11264   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
11265   Register tmp5, Register result) {
11266   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
11267 
11268   // rsi: src
11269   // rdi: dst
11270   // rdx: len
11271   // rcx: tmp5
11272   // rax: result
11273 
11274   // rsi holds start addr of source char[] to be compressed
11275   // rdi holds start addr of destination byte[]
11276   // rdx holds length
11277 
11278   assert(len != result, "");
11279 
11280   // save length for return
11281   push(len);
11282 
11283   if ((UseAVX > 2) && // AVX512
11284     VM_Version::supports_avx512vlbw() &&
11285     VM_Version::supports_bmi2()) {
11286 
11287     set_vector_masking();  // opening of the stub context for programming mask registers
11288 
11289     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
11290 
11291     // alignement
11292     Label post_alignement;
11293 
11294     // if length of the string is less than 16, handle it in an old fashioned
11295     // way
11296     testl(len, -32);
11297     jcc(Assembler::zero, below_threshold);
11298 
11299     // First check whether a character is compressable ( <= 0xFF).
11300     // Create mask to test for Unicode chars inside zmm vector
11301     movl(result, 0x00FF);
11302     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
11303 
11304     // Save k1
11305     kmovql(k3, k1);
11306 
11307     testl(len, -64);
11308     jcc(Assembler::zero, post_alignement);
11309 
11310     movl(tmp5, dst);
11311     andl(tmp5, (32 - 1));
11312     negl(tmp5);
11313     andl(tmp5, (32 - 1));
11314 
11315     // bail out when there is nothing to be done
11316     testl(tmp5, 0xFFFFFFFF);
11317     jcc(Assembler::zero, post_alignement);
11318 
11319     // ~(~0 << len), where len is the # of remaining elements to process
11320     movl(result, 0xFFFFFFFF);
11321     shlxl(result, result, tmp5);
11322     notl(result);
11323     kmovdl(k1, result);
11324 
11325     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11326     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11327     ktestd(k2, k1);
11328     jcc(Assembler::carryClear, restore_k1_return_zero);
11329 
11330     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11331 
11332     addptr(src, tmp5);
11333     addptr(src, tmp5);
11334     addptr(dst, tmp5);
11335     subl(len, tmp5);
11336 
11337     bind(post_alignement);
11338     // end of alignement
11339 
11340     movl(tmp5, len);
11341     andl(tmp5, (32 - 1));    // tail count (in chars)
11342     andl(len, ~(32 - 1));    // vector count (in chars)
11343     jcc(Assembler::zero, copy_loop_tail);
11344 
11345     lea(src, Address(src, len, Address::times_2));
11346     lea(dst, Address(dst, len, Address::times_1));
11347     negptr(len);
11348 
11349     bind(copy_32_loop);
11350     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11351     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11352     kortestdl(k2, k2);
11353     jcc(Assembler::carryClear, restore_k1_return_zero);
11354 
11355     // All elements in current processed chunk are valid candidates for
11356     // compression. Write a truncated byte elements to the memory.
11357     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11358     addptr(len, 32);
11359     jcc(Assembler::notZero, copy_32_loop);
11360 
11361     bind(copy_loop_tail);
11362     // bail out when there is nothing to be done
11363     testl(tmp5, 0xFFFFFFFF);
11364     // Restore k1
11365     kmovql(k1, k3);
11366     jcc(Assembler::zero, return_length);
11367 
11368     movl(len, tmp5);
11369 
11370     // ~(~0 << len), where len is the # of remaining elements to process
11371     movl(result, 0xFFFFFFFF);
11372     shlxl(result, result, len);
11373     notl(result);
11374 
11375     kmovdl(k1, result);
11376 
11377     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11378     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11379     ktestd(k2, k1);
11380     jcc(Assembler::carryClear, restore_k1_return_zero);
11381 
11382     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11383     // Restore k1
11384     kmovql(k1, k3);
11385     jmp(return_length);
11386 
11387     bind(restore_k1_return_zero);
11388     // Restore k1
11389     kmovql(k1, k3);
11390     jmp(return_zero);
11391 
11392     clear_vector_masking();   // closing of the stub context for programming mask registers
11393   }
11394   if (UseSSE42Intrinsics) {
11395     Label copy_32_loop, copy_16, copy_tail;
11396 
11397     bind(below_threshold);
11398 
11399     movl(result, len);
11400 
11401     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11402 
11403     // vectored compression
11404     andl(len, 0xfffffff0);    // vector count (in chars)
11405     andl(result, 0x0000000f);    // tail count (in chars)
11406     testl(len, len);
11407     jccb(Assembler::zero, copy_16);
11408 
11409     // compress 16 chars per iter
11410     movdl(tmp1Reg, tmp5);
11411     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11412     pxor(tmp4Reg, tmp4Reg);
11413 
11414     lea(src, Address(src, len, Address::times_2));
11415     lea(dst, Address(dst, len, Address::times_1));
11416     negptr(len);
11417 
11418     bind(copy_32_loop);
11419     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11420     por(tmp4Reg, tmp2Reg);
11421     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11422     por(tmp4Reg, tmp3Reg);
11423     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11424     jcc(Assembler::notZero, return_zero);
11425     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11426     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11427     addptr(len, 16);
11428     jcc(Assembler::notZero, copy_32_loop);
11429 
11430     // compress next vector of 8 chars (if any)
11431     bind(copy_16);
11432     movl(len, result);
11433     andl(len, 0xfffffff8);    // vector count (in chars)
11434     andl(result, 0x00000007);    // tail count (in chars)
11435     testl(len, len);
11436     jccb(Assembler::zero, copy_tail);
11437 
11438     movdl(tmp1Reg, tmp5);
11439     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11440     pxor(tmp3Reg, tmp3Reg);
11441 
11442     movdqu(tmp2Reg, Address(src, 0));
11443     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11444     jccb(Assembler::notZero, return_zero);
11445     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11446     movq(Address(dst, 0), tmp2Reg);
11447     addptr(src, 16);
11448     addptr(dst, 8);
11449 
11450     bind(copy_tail);
11451     movl(len, result);
11452   }
11453   // compress 1 char per iter
11454   testl(len, len);
11455   jccb(Assembler::zero, return_length);
11456   lea(src, Address(src, len, Address::times_2));
11457   lea(dst, Address(dst, len, Address::times_1));
11458   negptr(len);
11459 
11460   bind(copy_chars_loop);
11461   load_unsigned_short(result, Address(src, len, Address::times_2));
11462   testl(result, 0xff00);      // check if Unicode char
11463   jccb(Assembler::notZero, return_zero);
11464   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11465   increment(len);
11466   jcc(Assembler::notZero, copy_chars_loop);
11467 
11468   // if compression succeeded, return length
11469   bind(return_length);
11470   pop(result);
11471   jmpb(done);
11472 
11473   // if compression failed, return 0
11474   bind(return_zero);
11475   xorl(result, result);
11476   addptr(rsp, wordSize);
11477 
11478   bind(done);
11479 }
11480 
11481 // Inflate byte[] array to char[].
11482 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11483 //   @HotSpotIntrinsicCandidate
11484 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11485 //     for (int i = 0; i < len; i++) {
11486 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11487 //     }
11488 //   }
11489 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11490   XMMRegister tmp1, Register tmp2) {
11491   Label copy_chars_loop, done, below_threshold;
11492   // rsi: src
11493   // rdi: dst
11494   // rdx: len
11495   // rcx: tmp2
11496 
11497   // rsi holds start addr of source byte[] to be inflated
11498   // rdi holds start addr of destination char[]
11499   // rdx holds length
11500   assert_different_registers(src, dst, len, tmp2);
11501 
11502   if ((UseAVX > 2) && // AVX512
11503     VM_Version::supports_avx512vlbw() &&
11504     VM_Version::supports_bmi2()) {
11505 
11506     set_vector_masking();  // opening of the stub context for programming mask registers
11507 
11508     Label copy_32_loop, copy_tail;
11509     Register tmp3_aliased = len;
11510 
11511     // if length of the string is less than 16, handle it in an old fashioned
11512     // way
11513     testl(len, -16);
11514     jcc(Assembler::zero, below_threshold);
11515 
11516     // In order to use only one arithmetic operation for the main loop we use
11517     // this pre-calculation
11518     movl(tmp2, len);
11519     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11520     andl(len, -32);     // vector count
11521     jccb(Assembler::zero, copy_tail);
11522 
11523     lea(src, Address(src, len, Address::times_1));
11524     lea(dst, Address(dst, len, Address::times_2));
11525     negptr(len);
11526 
11527 
11528     // inflate 32 chars per iter
11529     bind(copy_32_loop);
11530     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11531     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11532     addptr(len, 32);
11533     jcc(Assembler::notZero, copy_32_loop);
11534 
11535     bind(copy_tail);
11536     // bail out when there is nothing to be done
11537     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11538     jcc(Assembler::zero, done);
11539 
11540     // Save k1
11541     kmovql(k2, k1);
11542 
11543     // ~(~0 << length), where length is the # of remaining elements to process
11544     movl(tmp3_aliased, -1);
11545     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11546     notl(tmp3_aliased);
11547     kmovdl(k1, tmp3_aliased);
11548     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11549     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11550 
11551     // Restore k1
11552     kmovql(k1, k2);
11553     jmp(done);
11554 
11555     clear_vector_masking();   // closing of the stub context for programming mask registers
11556   }
11557   if (UseSSE42Intrinsics) {
11558     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11559 
11560     movl(tmp2, len);
11561 
11562     if (UseAVX > 1) {
11563       andl(tmp2, (16 - 1));
11564       andl(len, -16);
11565       jccb(Assembler::zero, copy_new_tail);
11566     } else {
11567       andl(tmp2, 0x00000007);   // tail count (in chars)
11568       andl(len, 0xfffffff8);    // vector count (in chars)
11569       jccb(Assembler::zero, copy_tail);
11570     }
11571 
11572     // vectored inflation
11573     lea(src, Address(src, len, Address::times_1));
11574     lea(dst, Address(dst, len, Address::times_2));
11575     negptr(len);
11576 
11577     if (UseAVX > 1) {
11578       bind(copy_16_loop);
11579       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11580       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11581       addptr(len, 16);
11582       jcc(Assembler::notZero, copy_16_loop);
11583 
11584       bind(below_threshold);
11585       bind(copy_new_tail);
11586       if ((UseAVX > 2) &&
11587         VM_Version::supports_avx512vlbw() &&
11588         VM_Version::supports_bmi2()) {
11589         movl(tmp2, len);
11590       } else {
11591         movl(len, tmp2);
11592       }
11593       andl(tmp2, 0x00000007);
11594       andl(len, 0xFFFFFFF8);
11595       jccb(Assembler::zero, copy_tail);
11596 
11597       pmovzxbw(tmp1, Address(src, 0));
11598       movdqu(Address(dst, 0), tmp1);
11599       addptr(src, 8);
11600       addptr(dst, 2 * 8);
11601 
11602       jmp(copy_tail, true);
11603     }
11604 
11605     // inflate 8 chars per iter
11606     bind(copy_8_loop);
11607     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11608     movdqu(Address(dst, len, Address::times_2), tmp1);
11609     addptr(len, 8);
11610     jcc(Assembler::notZero, copy_8_loop);
11611 
11612     bind(copy_tail);
11613     movl(len, tmp2);
11614 
11615     cmpl(len, 4);
11616     jccb(Assembler::less, copy_bytes);
11617 
11618     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11619     pmovzxbw(tmp1, tmp1);
11620     movq(Address(dst, 0), tmp1);
11621     subptr(len, 4);
11622     addptr(src, 4);
11623     addptr(dst, 8);
11624 
11625     bind(copy_bytes);
11626   }
11627   testl(len, len);
11628   jccb(Assembler::zero, done);
11629   lea(src, Address(src, len, Address::times_1));
11630   lea(dst, Address(dst, len, Address::times_2));
11631   negptr(len);
11632 
11633   // inflate 1 char per iter
11634   bind(copy_chars_loop);
11635   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11636   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11637   increment(len);
11638   jcc(Assembler::notZero, copy_chars_loop);
11639 
11640   bind(done);
11641 }
11642 
11643 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11644   switch (cond) {
11645     // Note some conditions are synonyms for others
11646     case Assembler::zero:         return Assembler::notZero;
11647     case Assembler::notZero:      return Assembler::zero;
11648     case Assembler::less:         return Assembler::greaterEqual;
11649     case Assembler::lessEqual:    return Assembler::greater;
11650     case Assembler::greater:      return Assembler::lessEqual;
11651     case Assembler::greaterEqual: return Assembler::less;
11652     case Assembler::below:        return Assembler::aboveEqual;
11653     case Assembler::belowEqual:   return Assembler::above;
11654     case Assembler::above:        return Assembler::belowEqual;
11655     case Assembler::aboveEqual:   return Assembler::below;
11656     case Assembler::overflow:     return Assembler::noOverflow;
11657     case Assembler::noOverflow:   return Assembler::overflow;
11658     case Assembler::negative:     return Assembler::positive;
11659     case Assembler::positive:     return Assembler::negative;
11660     case Assembler::parity:       return Assembler::noParity;
11661     case Assembler::noParity:     return Assembler::parity;
11662   }
11663   ShouldNotReachHere(); return Assembler::overflow;
11664 }
11665 
11666 SkipIfEqual::SkipIfEqual(
11667     MacroAssembler* masm, const bool* flag_addr, bool value) {
11668   _masm = masm;
11669   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11670   _masm->jcc(Assembler::equal, _label);
11671 }
11672 
11673 SkipIfEqual::~SkipIfEqual() {
11674   _masm->bind(_label);
11675 }
11676 
11677 // 32-bit Windows has its own fast-path implementation
11678 // of get_thread
11679 #if !defined(WIN32) || defined(_LP64)
11680 
11681 // This is simply a call to Thread::current()
11682 void MacroAssembler::get_thread(Register thread) {
11683   if (thread != rax) {
11684     push(rax);
11685   }
11686   LP64_ONLY(push(rdi);)
11687   LP64_ONLY(push(rsi);)
11688   push(rdx);
11689   push(rcx);
11690 #ifdef _LP64
11691   push(r8);
11692   push(r9);
11693   push(r10);
11694   push(r11);
11695 #endif
11696 
11697   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11698 
11699 #ifdef _LP64
11700   pop(r11);
11701   pop(r10);
11702   pop(r9);
11703   pop(r8);
11704 #endif
11705   pop(rcx);
11706   pop(rdx);
11707   LP64_ONLY(pop(rsi);)
11708   LP64_ONLY(pop(rdi);)
11709   if (thread != rax) {
11710     mov(thread, rax);
11711     pop(rax);
11712   }
11713 }
11714 
11715 #endif
11716 
11717 void MacroAssembler::save_vector_registers() {
11718   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11719   if (UseAVX > 2) {
11720     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11721   }
11722 
11723   if (UseSSE == 1)  {
11724     subptr(rsp, sizeof(jdouble)*8);
11725     for (int n = 0; n < 8; n++) {
11726       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11727     }
11728   } else if (UseSSE >= 2)  {
11729     if (UseAVX > 2) {
11730       push(rbx);
11731       movl(rbx, 0xffff);
11732       kmovwl(k1, rbx);
11733       pop(rbx);
11734     }
11735 #ifdef COMPILER2
11736     if (MaxVectorSize > 16) {
11737       if(UseAVX > 2) {
11738         // Save upper half of ZMM registers
11739         subptr(rsp, 32*num_xmm_regs);
11740         for (int n = 0; n < num_xmm_regs; n++) {
11741           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11742         }
11743       }
11744       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11745       // Save upper half of YMM registers
11746       subptr(rsp, 16*num_xmm_regs);
11747       for (int n = 0; n < num_xmm_regs; n++) {
11748         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11749       }
11750     }
11751 #endif
11752     // Save whole 128bit (16 bytes) XMM registers
11753     subptr(rsp, 16*num_xmm_regs);
11754 #ifdef _LP64
11755     if (VM_Version::supports_evex()) {
11756       for (int n = 0; n < num_xmm_regs; n++) {
11757         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11758       }
11759     } else {
11760       for (int n = 0; n < num_xmm_regs; n++) {
11761         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11762       }
11763     }
11764 #else
11765     for (int n = 0; n < num_xmm_regs; n++) {
11766       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11767     }
11768 #endif
11769   }
11770 }
11771 
11772 void MacroAssembler::restore_vector_registers() {
11773   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11774   if (UseAVX > 2) {
11775     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11776   }
11777   if (UseSSE == 1)  {
11778     for (int n = 0; n < 8; n++) {
11779       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11780     }
11781     addptr(rsp, sizeof(jdouble)*8);
11782   } else if (UseSSE >= 2)  {
11783     // Restore whole 128bit (16 bytes) XMM registers
11784 #ifdef _LP64
11785   if (VM_Version::supports_evex()) {
11786     for (int n = 0; n < num_xmm_regs; n++) {
11787       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11788     }
11789   } else {
11790     for (int n = 0; n < num_xmm_regs; n++) {
11791       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11792     }
11793   }
11794 #else
11795   for (int n = 0; n < num_xmm_regs; n++) {
11796     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11797   }
11798 #endif
11799     addptr(rsp, 16*num_xmm_regs);
11800 
11801 #ifdef COMPILER2
11802     if (MaxVectorSize > 16) {
11803       // Restore upper half of YMM registers.
11804       for (int n = 0; n < num_xmm_regs; n++) {
11805         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11806       }
11807       addptr(rsp, 16*num_xmm_regs);
11808       if(UseAVX > 2) {
11809         for (int n = 0; n < num_xmm_regs; n++) {
11810           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11811         }
11812         addptr(rsp, 32*num_xmm_regs);
11813       }
11814     }
11815 #endif
11816   }
11817 }
11818 
11819 void MacroAssembler::cmpoops(Register src1, Register src2) {
11820   cmpptr(src1, src2);
11821   oopDesc::bs()->asm_acmp_barrier(this, src1, src2);
11822 }
11823 
11824 void MacroAssembler::cmpoops(Register src1, Address src2) {
11825   cmpptr(src1, src2);
11826   if (UseShenandoahGC && ShenandoahAcmpBarrier) {
11827     Label done;
11828     jccb(Assembler::equal, done);
11829     movptr(rscratch2, src2);
11830     oopDesc::bs()->interpreter_read_barrier(this, src1);
11831     oopDesc::bs()->interpreter_read_barrier(this, rscratch2);
11832     cmpptr(src1, rscratch2);
11833     bind(done);
11834   }
11835 }