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_shift_jint());
5486   // Compute from-region index
5487   movptr(tmp2, store_addr);
5488   subptr(tmp2, rscratch1);
5489   shrptr(tmp2, ShenandoahHeapRegion::region_size_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 #ifndef _LP64
5595 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5596   Unimplemented();
5597 }
5598 #else
5599 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5600   assert(UseShenandoahGC, "must only be called with Shenandoah GC active");
5601   assert(ShenandoahWriteBarrier, "must only be called when write barriers are enabled");
5602 
5603   Label done;
5604 
5605   // Check for evacuation-in-progress
5606   Address evacuation_in_progress = Address(r15_thread, in_bytes(JavaThread::evacuation_in_progress_offset()));
5607   cmpb(evacuation_in_progress, 0);
5608 
5609   // The read-barrier.
5610   movptr(dst, Address(dst, BrooksPointer::byte_offset()));
5611 
5612   jccb(Assembler::equal, done);
5613 
5614   if (dst != rax) {
5615     xchgptr(dst, rax); // Move obj into rax and save rax into obj.
5616   }
5617 
5618   assert(StubRoutines::x86::shenandoah_wb() != NULL, "need write barrier stub");
5619   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::shenandoah_wb())));
5620 
5621   if (dst != rax) {
5622     xchgptr(rax, dst); // Swap back obj with rax.
5623   }
5624 
5625   bind(done);
5626 }
5627 #endif // _LP64
5628 
5629 #endif // INCLUDE_ALL_GCS
5630 //////////////////////////////////////////////////////////////////////////////////
5631 
5632 
5633 void MacroAssembler::store_check(Register obj, Address dst) {
5634   store_check(obj);
5635 }
5636 
5637 void MacroAssembler::store_check(Register obj) {
5638   // Does a store check for the oop in register obj. The content of
5639   // register obj is destroyed afterwards.
5640   BarrierSet* bs = Universe::heap()->barrier_set();
5641   assert(bs->kind() == BarrierSet::CardTableForRS ||
5642          bs->kind() == BarrierSet::CardTableExtension,
5643          "Wrong barrier set kind");
5644 
5645   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5646   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5647 
5648   shrptr(obj, CardTableModRefBS::card_shift);
5649 
5650   Address card_addr;
5651 
5652   // The calculation for byte_map_base is as follows:
5653   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5654   // So this essentially converts an address to a displacement and it will
5655   // never need to be relocated. On 64bit however the value may be too
5656   // large for a 32bit displacement.
5657   intptr_t disp = (intptr_t) ct->byte_map_base;
5658   if (is_simm32(disp)) {
5659     card_addr = Address(noreg, obj, Address::times_1, disp);
5660   } else {
5661     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5662     // displacement and done in a single instruction given favorable mapping and a
5663     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5664     // entry and that entry is not properly handled by the relocation code.
5665     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5666     Address index(noreg, obj, Address::times_1);
5667     card_addr = as_Address(ArrayAddress(cardtable, index));
5668   }
5669 
5670   int dirty = CardTableModRefBS::dirty_card_val();
5671   if (UseCondCardMark) {
5672     Label L_already_dirty;
5673     if (UseConcMarkSweepGC) {
5674       membar(Assembler::StoreLoad);
5675     }
5676     cmpb(card_addr, dirty);
5677     jcc(Assembler::equal, L_already_dirty);
5678     movb(card_addr, dirty);
5679     bind(L_already_dirty);
5680   } else {
5681     movb(card_addr, dirty);
5682   }
5683 }
5684 
5685 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5686   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5687 }
5688 
5689 // Force generation of a 4 byte immediate value even if it fits into 8bit
5690 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5691   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5692 }
5693 
5694 void MacroAssembler::subptr(Register dst, Register src) {
5695   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5696 }
5697 
5698 // C++ bool manipulation
5699 void MacroAssembler::testbool(Register dst) {
5700   if(sizeof(bool) == 1)
5701     testb(dst, 0xff);
5702   else if(sizeof(bool) == 2) {
5703     // testw implementation needed for two byte bools
5704     ShouldNotReachHere();
5705   } else if(sizeof(bool) == 4)
5706     testl(dst, dst);
5707   else
5708     // unsupported
5709     ShouldNotReachHere();
5710 }
5711 
5712 void MacroAssembler::testptr(Register dst, Register src) {
5713   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5714 }
5715 
5716 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5717 void MacroAssembler::tlab_allocate(Register obj,
5718                                    Register var_size_in_bytes,
5719                                    int con_size_in_bytes,
5720                                    Register t1,
5721                                    Register t2,
5722                                    Label& slow_case) {
5723   assert_different_registers(obj, t1, t2);
5724   assert_different_registers(obj, var_size_in_bytes, t1);
5725   Register end = t2;
5726   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5727 
5728   verify_tlab();
5729 
5730   NOT_LP64(get_thread(thread));
5731 
5732   uint oop_extra_words = Universe::heap()->oop_extra_words();
5733 
5734   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5735   if (var_size_in_bytes == noreg) {
5736     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5737   } else {
5738     if (oop_extra_words > 0) {
5739       addptr(var_size_in_bytes, oop_extra_words * HeapWordSize);
5740     }
5741     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5742   }
5743   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5744   jcc(Assembler::above, slow_case);
5745 
5746   // update the tlab top pointer
5747   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5748 
5749   Universe::heap()->compile_prepare_oop(this, obj);
5750 
5751   // recover var_size_in_bytes if necessary
5752   if (var_size_in_bytes == end) {
5753     subptr(var_size_in_bytes, obj);
5754   }
5755   verify_tlab();
5756 }
5757 
5758 // Preserves rbx, and rdx.
5759 Register MacroAssembler::tlab_refill(Label& retry,
5760                                      Label& try_eden,
5761                                      Label& slow_case) {
5762   Register top = rax;
5763   Register t1  = rcx; // object size
5764   Register t2  = rsi;
5765   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5766   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5767   Label do_refill, discard_tlab;
5768 
5769   if (!Universe::heap()->supports_inline_contig_alloc()) {
5770     // No allocation in the shared eden.
5771     jmp(slow_case);
5772   }
5773 
5774   NOT_LP64(get_thread(thread_reg));
5775 
5776   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5777   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5778 
5779   // calculate amount of free space
5780   subptr(t1, top);
5781   shrptr(t1, LogHeapWordSize);
5782 
5783   // Retain tlab and allocate object in shared space if
5784   // the amount free in the tlab is too large to discard.
5785   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5786   jcc(Assembler::lessEqual, discard_tlab);
5787 
5788   // Retain
5789   // %%% yuck as movptr...
5790   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5791   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5792   if (TLABStats) {
5793     // increment number of slow_allocations
5794     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5795   }
5796   jmp(try_eden);
5797 
5798   bind(discard_tlab);
5799   if (TLABStats) {
5800     // increment number of refills
5801     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5802     // accumulate wastage -- t1 is amount free in tlab
5803     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5804   }
5805 
5806   // if tlab is currently allocated (top or end != null) then
5807   // fill [top, end + alignment_reserve) with array object
5808   testptr(top, top);
5809   jcc(Assembler::zero, do_refill);
5810 
5811   // set up the mark word
5812   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5813   // set the length to the remaining space
5814   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5815   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5816   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5817   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5818   // set klass to intArrayKlass
5819   // dubious reloc why not an oop reloc?
5820   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5821   // store klass last.  concurrent gcs assumes klass length is valid if
5822   // klass field is not null.
5823   store_klass(top, t1);
5824 
5825   movptr(t1, top);
5826   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5827   incr_allocated_bytes(thread_reg, t1, 0);
5828 
5829   // refill the tlab with an eden allocation
5830   bind(do_refill);
5831   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5832   shlptr(t1, LogHeapWordSize);
5833   // allocate new tlab, address returned in top
5834   eden_allocate(top, t1, 0, t2, slow_case);
5835 
5836   // Check that t1 was preserved in eden_allocate.
5837 #ifdef ASSERT
5838   if (UseTLAB) {
5839     Label ok;
5840     Register tsize = rsi;
5841     assert_different_registers(tsize, thread_reg, t1);
5842     push(tsize);
5843     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5844     shlptr(tsize, LogHeapWordSize);
5845     cmpptr(t1, tsize);
5846     jcc(Assembler::equal, ok);
5847     STOP("assert(t1 != tlab size)");
5848     should_not_reach_here();
5849 
5850     bind(ok);
5851     pop(tsize);
5852   }
5853 #endif
5854   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5855   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5856   addptr(top, t1);
5857   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5858   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5859 
5860   if (ZeroTLAB) {
5861     // This is a fast TLAB refill, therefore the GC is not notified of it.
5862     // So compiled code must fill the new TLAB with zeroes.
5863     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5864     zero_memory(top, t1, 0, t2);
5865   }
5866 
5867   verify_tlab();
5868   jmp(retry);
5869 
5870   return thread_reg; // for use by caller
5871 }
5872 
5873 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5874 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5875   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5876   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5877   Label done;
5878 
5879   testptr(length_in_bytes, length_in_bytes);
5880   jcc(Assembler::zero, done);
5881 
5882   // initialize topmost word, divide index by 2, check if odd and test if zero
5883   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5884 #ifdef ASSERT
5885   {
5886     Label L;
5887     testptr(length_in_bytes, BytesPerWord - 1);
5888     jcc(Assembler::zero, L);
5889     stop("length must be a multiple of BytesPerWord");
5890     bind(L);
5891   }
5892 #endif
5893   Register index = length_in_bytes;
5894   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5895   if (UseIncDec) {
5896     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5897   } else {
5898     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5899     shrptr(index, 1);
5900   }
5901 #ifndef _LP64
5902   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5903   {
5904     Label even;
5905     // note: if index was a multiple of 8, then it cannot
5906     //       be 0 now otherwise it must have been 0 before
5907     //       => if it is even, we don't need to check for 0 again
5908     jcc(Assembler::carryClear, even);
5909     // clear topmost word (no jump would be needed if conditional assignment worked here)
5910     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5911     // index could be 0 now, must check again
5912     jcc(Assembler::zero, done);
5913     bind(even);
5914   }
5915 #endif // !_LP64
5916   // initialize remaining object fields: index is a multiple of 2 now
5917   {
5918     Label loop;
5919     bind(loop);
5920     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5921     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5922     decrement(index);
5923     jcc(Assembler::notZero, loop);
5924   }
5925 
5926   bind(done);
5927 }
5928 
5929 void MacroAssembler::incr_allocated_bytes(Register thread,
5930                                           Register var_size_in_bytes,
5931                                           int con_size_in_bytes,
5932                                           Register t1) {
5933   if (!thread->is_valid()) {
5934 #ifdef _LP64
5935     thread = r15_thread;
5936 #else
5937     assert(t1->is_valid(), "need temp reg");
5938     thread = t1;
5939     get_thread(thread);
5940 #endif
5941   }
5942 
5943 #ifdef _LP64
5944   if (var_size_in_bytes->is_valid()) {
5945     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5946   } else {
5947     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5948   }
5949 #else
5950   if (var_size_in_bytes->is_valid()) {
5951     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5952   } else {
5953     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5954   }
5955   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5956 #endif
5957 }
5958 
5959 // Look up the method for a megamorphic invokeinterface call.
5960 // The target method is determined by <intf_klass, itable_index>.
5961 // The receiver klass is in recv_klass.
5962 // On success, the result will be in method_result, and execution falls through.
5963 // On failure, execution transfers to the given label.
5964 void MacroAssembler::lookup_interface_method(Register recv_klass,
5965                                              Register intf_klass,
5966                                              RegisterOrConstant itable_index,
5967                                              Register method_result,
5968                                              Register scan_temp,
5969                                              Label& L_no_such_interface) {
5970   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5971   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5972          "caller must use same register for non-constant itable index as for method");
5973 
5974   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5975   int vtable_base = in_bytes(Klass::vtable_start_offset());
5976   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5977   int scan_step   = itableOffsetEntry::size() * wordSize;
5978   int vte_size    = vtableEntry::size_in_bytes();
5979   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5980   assert(vte_size == wordSize, "else adjust times_vte_scale");
5981 
5982   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5983 
5984   // %%% Could store the aligned, prescaled offset in the klassoop.
5985   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5986 
5987   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5988   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5989   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5990 
5991   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5992   //   if (scan->interface() == intf) {
5993   //     result = (klass + scan->offset() + itable_index);
5994   //   }
5995   // }
5996   Label search, found_method;
5997 
5998   for (int peel = 1; peel >= 0; peel--) {
5999     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
6000     cmpptr(intf_klass, method_result);
6001 
6002     if (peel) {
6003       jccb(Assembler::equal, found_method);
6004     } else {
6005       jccb(Assembler::notEqual, search);
6006       // (invert the test to fall through to found_method...)
6007     }
6008 
6009     if (!peel)  break;
6010 
6011     bind(search);
6012 
6013     // Check that the previous entry is non-null.  A null entry means that
6014     // the receiver class doesn't implement the interface, and wasn't the
6015     // same as when the caller was compiled.
6016     testptr(method_result, method_result);
6017     jcc(Assembler::zero, L_no_such_interface);
6018     addptr(scan_temp, scan_step);
6019   }
6020 
6021   bind(found_method);
6022 
6023   // Got a hit.
6024   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
6025   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
6026 }
6027 
6028 
6029 // virtual method calling
6030 void MacroAssembler::lookup_virtual_method(Register recv_klass,
6031                                            RegisterOrConstant vtable_index,
6032                                            Register method_result) {
6033   const int base = in_bytes(Klass::vtable_start_offset());
6034   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
6035   Address vtable_entry_addr(recv_klass,
6036                             vtable_index, Address::times_ptr,
6037                             base + vtableEntry::method_offset_in_bytes());
6038   movptr(method_result, vtable_entry_addr);
6039 }
6040 
6041 
6042 void MacroAssembler::check_klass_subtype(Register sub_klass,
6043                            Register super_klass,
6044                            Register temp_reg,
6045                            Label& L_success) {
6046   Label L_failure;
6047   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
6048   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
6049   bind(L_failure);
6050 }
6051 
6052 
6053 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
6054                                                    Register super_klass,
6055                                                    Register temp_reg,
6056                                                    Label* L_success,
6057                                                    Label* L_failure,
6058                                                    Label* L_slow_path,
6059                                         RegisterOrConstant super_check_offset) {
6060   assert_different_registers(sub_klass, super_klass, temp_reg);
6061   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
6062   if (super_check_offset.is_register()) {
6063     assert_different_registers(sub_klass, super_klass,
6064                                super_check_offset.as_register());
6065   } else if (must_load_sco) {
6066     assert(temp_reg != noreg, "supply either a temp or a register offset");
6067   }
6068 
6069   Label L_fallthrough;
6070   int label_nulls = 0;
6071   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6072   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6073   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6074   assert(label_nulls <= 1, "at most one NULL in the batch");
6075 
6076   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6077   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6078   Address super_check_offset_addr(super_klass, sco_offset);
6079 
6080   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6081   // range of a jccb.  If this routine grows larger, reconsider at
6082   // least some of these.
6083 #define local_jcc(assembler_cond, label)                                \
6084   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6085   else                             jcc( assembler_cond, label) /*omit semi*/
6086 
6087   // Hacked jmp, which may only be used just before L_fallthrough.
6088 #define final_jmp(label)                                                \
6089   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6090   else                            jmp(label)                /*omit semi*/
6091 
6092   // If the pointers are equal, we are done (e.g., String[] elements).
6093   // This self-check enables sharing of secondary supertype arrays among
6094   // non-primary types such as array-of-interface.  Otherwise, each such
6095   // type would need its own customized SSA.
6096   // We move this check to the front of the fast path because many
6097   // type checks are in fact trivially successful in this manner,
6098   // so we get a nicely predicted branch right at the start of the check.
6099   cmpptr(sub_klass, super_klass);
6100   local_jcc(Assembler::equal, *L_success);
6101 
6102   // Check the supertype display:
6103   if (must_load_sco) {
6104     // Positive movl does right thing on LP64.
6105     movl(temp_reg, super_check_offset_addr);
6106     super_check_offset = RegisterOrConstant(temp_reg);
6107   }
6108   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6109   cmpptr(super_klass, super_check_addr); // load displayed supertype
6110 
6111   // This check has worked decisively for primary supers.
6112   // Secondary supers are sought in the super_cache ('super_cache_addr').
6113   // (Secondary supers are interfaces and very deeply nested subtypes.)
6114   // This works in the same check above because of a tricky aliasing
6115   // between the super_cache and the primary super display elements.
6116   // (The 'super_check_addr' can address either, as the case requires.)
6117   // Note that the cache is updated below if it does not help us find
6118   // what we need immediately.
6119   // So if it was a primary super, we can just fail immediately.
6120   // Otherwise, it's the slow path for us (no success at this point).
6121 
6122   if (super_check_offset.is_register()) {
6123     local_jcc(Assembler::equal, *L_success);
6124     cmpl(super_check_offset.as_register(), sc_offset);
6125     if (L_failure == &L_fallthrough) {
6126       local_jcc(Assembler::equal, *L_slow_path);
6127     } else {
6128       local_jcc(Assembler::notEqual, *L_failure);
6129       final_jmp(*L_slow_path);
6130     }
6131   } else if (super_check_offset.as_constant() == sc_offset) {
6132     // Need a slow path; fast failure is impossible.
6133     if (L_slow_path == &L_fallthrough) {
6134       local_jcc(Assembler::equal, *L_success);
6135     } else {
6136       local_jcc(Assembler::notEqual, *L_slow_path);
6137       final_jmp(*L_success);
6138     }
6139   } else {
6140     // No slow path; it's a fast decision.
6141     if (L_failure == &L_fallthrough) {
6142       local_jcc(Assembler::equal, *L_success);
6143     } else {
6144       local_jcc(Assembler::notEqual, *L_failure);
6145       final_jmp(*L_success);
6146     }
6147   }
6148 
6149   bind(L_fallthrough);
6150 
6151 #undef local_jcc
6152 #undef final_jmp
6153 }
6154 
6155 
6156 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6157                                                    Register super_klass,
6158                                                    Register temp_reg,
6159                                                    Register temp2_reg,
6160                                                    Label* L_success,
6161                                                    Label* L_failure,
6162                                                    bool set_cond_codes) {
6163   assert_different_registers(sub_klass, super_klass, temp_reg);
6164   if (temp2_reg != noreg)
6165     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6166 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6167 
6168   Label L_fallthrough;
6169   int label_nulls = 0;
6170   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6171   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6172   assert(label_nulls <= 1, "at most one NULL in the batch");
6173 
6174   // a couple of useful fields in sub_klass:
6175   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6176   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6177   Address secondary_supers_addr(sub_klass, ss_offset);
6178   Address super_cache_addr(     sub_klass, sc_offset);
6179 
6180   // Do a linear scan of the secondary super-klass chain.
6181   // This code is rarely used, so simplicity is a virtue here.
6182   // The repne_scan instruction uses fixed registers, which we must spill.
6183   // Don't worry too much about pre-existing connections with the input regs.
6184 
6185   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6186   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6187 
6188   // Get super_klass value into rax (even if it was in rdi or rcx).
6189   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6190   if (super_klass != rax || UseCompressedOops) {
6191     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6192     mov(rax, super_klass);
6193   }
6194   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6195   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6196 
6197 #ifndef PRODUCT
6198   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6199   ExternalAddress pst_counter_addr((address) pst_counter);
6200   NOT_LP64(  incrementl(pst_counter_addr) );
6201   LP64_ONLY( lea(rcx, pst_counter_addr) );
6202   LP64_ONLY( incrementl(Address(rcx, 0)) );
6203 #endif //PRODUCT
6204 
6205   // We will consult the secondary-super array.
6206   movptr(rdi, secondary_supers_addr);
6207   // Load the array length.  (Positive movl does right thing on LP64.)
6208   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6209   // Skip to start of data.
6210   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6211 
6212   // Scan RCX words at [RDI] for an occurrence of RAX.
6213   // Set NZ/Z based on last compare.
6214   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6215   // not change flags (only scas instruction which is repeated sets flags).
6216   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6217 
6218     testptr(rax,rax); // Set Z = 0
6219     repne_scan();
6220 
6221   // Unspill the temp. registers:
6222   if (pushed_rdi)  pop(rdi);
6223   if (pushed_rcx)  pop(rcx);
6224   if (pushed_rax)  pop(rax);
6225 
6226   if (set_cond_codes) {
6227     // Special hack for the AD files:  rdi is guaranteed non-zero.
6228     assert(!pushed_rdi, "rdi must be left non-NULL");
6229     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6230   }
6231 
6232   if (L_failure == &L_fallthrough)
6233         jccb(Assembler::notEqual, *L_failure);
6234   else  jcc(Assembler::notEqual, *L_failure);
6235 
6236   // Success.  Cache the super we found and proceed in triumph.
6237   movptr(super_cache_addr, super_klass);
6238 
6239   if (L_success != &L_fallthrough) {
6240     jmp(*L_success);
6241   }
6242 
6243 #undef IS_A_TEMP
6244 
6245   bind(L_fallthrough);
6246 }
6247 
6248 
6249 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6250   if (VM_Version::supports_cmov()) {
6251     cmovl(cc, dst, src);
6252   } else {
6253     Label L;
6254     jccb(negate_condition(cc), L);
6255     movl(dst, src);
6256     bind(L);
6257   }
6258 }
6259 
6260 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6261   if (VM_Version::supports_cmov()) {
6262     cmovl(cc, dst, src);
6263   } else {
6264     Label L;
6265     jccb(negate_condition(cc), L);
6266     movl(dst, src);
6267     bind(L);
6268   }
6269 }
6270 
6271 void MacroAssembler::verify_oop(Register reg, const char* s) {
6272   if (!VerifyOops) return;
6273 
6274   // Pass register number to verify_oop_subroutine
6275   const char* b = NULL;
6276   {
6277     ResourceMark rm;
6278     stringStream ss;
6279     ss.print("verify_oop: %s: %s", reg->name(), s);
6280     b = code_string(ss.as_string());
6281   }
6282   BLOCK_COMMENT("verify_oop {");
6283 #ifdef _LP64
6284   push(rscratch1);                    // save r10, trashed by movptr()
6285 #endif
6286   push(rax);                          // save rax,
6287   push(reg);                          // pass register argument
6288   ExternalAddress buffer((address) b);
6289   // avoid using pushptr, as it modifies scratch registers
6290   // and our contract is not to modify anything
6291   movptr(rax, buffer.addr());
6292   push(rax);
6293   // call indirectly to solve generation ordering problem
6294   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6295   call(rax);
6296   // Caller pops the arguments (oop, message) and restores rax, r10
6297   BLOCK_COMMENT("} verify_oop");
6298 }
6299 
6300 
6301 void MacroAssembler::shenandoah_in_heap_check(Register dst, Register tmp, Label& done) {
6302   // Converts dst to biased region index
6303 
6304   // Test that oop is not in to-space.
6305   shrptr(dst, ShenandoahHeapRegion::region_size_shift_jint());
6306 
6307   // Check if in bounds for cset check. This implicitly checks if target is in heap.
6308   // Since heap might not start at zero, we want to bias the low/high boundaries.
6309   uintx bias = (uintx) ShenandoahHeap::heap()->base() >> ShenandoahHeapRegion::region_size_shift();
6310   int32_t low = (int32_t) (0 + bias);
6311   int32_t high = (int32_t) (ShenandoahHeap::heap()->max_regions() + bias);
6312 
6313   cmpptr(dst, low);
6314   jccb(Assembler::below, done);
6315   cmpptr(dst, high);
6316   jccb(Assembler::aboveEqual, done);
6317 }
6318 
6319 void MacroAssembler::shenandoah_cset_check(Register dst, Register tmp, Label& done) {
6320   // Destroys dst
6321 
6322   shenandoah_in_heap_check(dst, tmp, done);
6323 
6324   movptr(tmp, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
6325   movbool(tmp, Address(tmp, dst, Address::times_1));
6326   testbool(tmp);
6327   jccb(Assembler::zero, done);
6328 
6329   // Check for cancelled GC.
6330   movptr(tmp, (intptr_t) ShenandoahHeap::cancelled_concgc_addr());
6331   movbool(tmp, Address(tmp, 0));
6332   testbool(tmp);
6333   jccb(Assembler::notZero, done);
6334 }
6335 
6336 #ifndef _LP64
6337 void MacroAssembler::shenandoah_store_addr_check(Address addr) {
6338   // Not implemented on 32-bit, pass.
6339 }
6340 void MacroAssembler::shenandoah_store_addr_check(Register dst) {
6341   // Not implemented on 32-bit, pass.
6342 }
6343 void MacroAssembler::shenandoah_store_val_check(Register dst, Register value) {
6344   // Not implemented on 32-bit, pass.
6345 }
6346 void MacroAssembler::shenandoah_store_val_check(Address dst, Register value) {
6347   // Not implemented on 32-bit, pass.
6348 }
6349 void MacroAssembler::shenandoah_lock_check(Register dst) {
6350   // Not implemented on 32-bit, pass.
6351 }
6352 #else
6353 void MacroAssembler::shenandoah_store_addr_check(Address addr) {
6354   shenandoah_store_addr_check(addr.base());
6355 }
6356 
6357 void MacroAssembler::shenandoah_store_addr_check(Register dst) {
6358   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6359   if (dst == rsp) return; // Stack-based target
6360 
6361   // This method temporarily destroys dst, but always pushes
6362   // the original values on stack, and restores them on exit.
6363 
6364   Register tmp = NULL;
6365   if (dst != rscratch1) {
6366     tmp = rscratch1;
6367   } else if (dst != rscratch2) {
6368     tmp = rscratch2;
6369   } else {
6370     guarantee(false, "able to select the temp register");
6371   }
6372 
6373   Label done;
6374 
6375   pushf();
6376   push(dst);
6377   push(tmp);
6378 
6379   // Check null.
6380   testptr(dst, dst);
6381   jcc(Assembler::zero, done);
6382 
6383   shenandoah_cset_check(dst, tmp, done);
6384 
6385   // Fail.
6386   pop(tmp);
6387   pop(dst);
6388   popf();
6389 
6390   // Stop, provoke SEGV.
6391   // Shortest way to fail VM with RIP pointing to this check.
6392   // Store dst register to clearly see what had failed.
6393   lea(tmp, ExternalAddress(badAddress));
6394   movptr(Address(tmp, 0), dst);
6395   hlt();
6396 
6397   bind(done);
6398 
6399   pop(tmp);
6400   pop(dst);
6401   popf();
6402 }
6403 
6404 void MacroAssembler::shenandoah_store_val_check(Register dst, Register value) {
6405   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6406   if (dst == rsp)   return; // Stack-based target
6407   if (value == rsp) return; // Stack-based value // TODO: Handle this.
6408 
6409   // This method temporarily destroys dst and value, but always pushes
6410   // the original values on stack, and restores them on exit.
6411 
6412   Register tmp = NULL;
6413   if (value != rscratch1 && dst != rscratch1) {
6414     tmp = rscratch1;
6415   } else if (value != rscratch2 && dst != rscratch2) {
6416     tmp = rscratch2;
6417   } else if (value != r9 && dst != r9) {
6418     tmp = r9;
6419   } else {
6420     guarantee(false, "able to select the temp register");
6421   }
6422 
6423   // Push tmp regs and flags.
6424   pushf();
6425   push(dst);
6426   push(value);
6427   push(tmp);
6428 
6429   Label done;
6430 
6431   if (ShenandoahUpdateRefsEarly) {
6432     // Do value-check only when update refs is in progress.
6433     movptr(tmp, (intptr_t) ShenandoahHeap::update_refs_in_progress_addr());
6434   } else {
6435     // Do value-check only when concurrent mark is in progress.
6436     movptr(tmp, (intptr_t) ShenandoahHeap::concurrent_mark_in_progress_addr());
6437   }
6438   movbool(tmp, Address(tmp, 0));
6439   testbool(tmp);
6440   jcc(Assembler::zero, done);
6441 
6442   // Null-check dst.
6443   testptr(dst, dst);
6444   jcc(Assembler::zero, done);
6445 
6446   // Check that dst is in heap.
6447   // Rationale: we accept offheap writes to roots, because we will fix them up
6448   // as needed later. Non-root offheap writes are unsafe anyway, allow them.
6449   shenandoah_in_heap_check(dst, tmp, done);
6450 
6451   // Null-check value.
6452   testptr(value, value);
6453   jcc(Assembler::zero, done);
6454 
6455   // Test that value oop is not in to-space.
6456   shenandoah_cset_check(value, tmp, done);
6457 
6458   // Fail.
6459   pop(tmp);
6460   pop(value);
6461   pop(dst);
6462   popf();
6463 
6464   // Stop, provoke SEGV.
6465   // Shortest way to fail VM with RIP pointing to this check.
6466   // Store value register to clearly see what had failed.
6467   lea(tmp, ExternalAddress(badAddress));
6468   movptr(Address(tmp, 0), value);
6469   hlt();
6470 
6471   bind(done);
6472 
6473   // Pop tmp regs and flags.
6474   pop(tmp);
6475   pop(value);
6476   pop(dst);
6477   popf();
6478 }
6479 
6480 void MacroAssembler::shenandoah_store_val_check(Address addr, Register value) {
6481   shenandoah_store_val_check(addr.base(), value);
6482 }
6483 
6484 void MacroAssembler::shenandoah_lock_check(Register dst) {
6485 #ifdef ASSERT
6486   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6487 
6488   push(r8);
6489   movptr(r8, Address(dst, BasicObjectLock::obj_offset_in_bytes()));
6490   shenandoah_store_addr_check(r8);
6491   pop(r8);
6492 #endif
6493 }
6494 #endif // _LP64
6495 
6496 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6497                                                       Register tmp,
6498                                                       int offset) {
6499   intptr_t value = *delayed_value_addr;
6500   if (value != 0)
6501     return RegisterOrConstant(value + offset);
6502 
6503   // load indirectly to solve generation ordering problem
6504   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6505 
6506 #ifdef ASSERT
6507   { Label L;
6508     testptr(tmp, tmp);
6509     if (WizardMode) {
6510       const char* buf = NULL;
6511       {
6512         ResourceMark rm;
6513         stringStream ss;
6514         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6515         buf = code_string(ss.as_string());
6516       }
6517       jcc(Assembler::notZero, L);
6518       STOP(buf);
6519     } else {
6520       jccb(Assembler::notZero, L);
6521       hlt();
6522     }
6523     bind(L);
6524   }
6525 #endif
6526 
6527   if (offset != 0)
6528     addptr(tmp, offset);
6529 
6530   return RegisterOrConstant(tmp);
6531 }
6532 
6533 
6534 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6535                                          int extra_slot_offset) {
6536   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6537   int stackElementSize = Interpreter::stackElementSize;
6538   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6539 #ifdef ASSERT
6540   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6541   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6542 #endif
6543   Register             scale_reg    = noreg;
6544   Address::ScaleFactor scale_factor = Address::no_scale;
6545   if (arg_slot.is_constant()) {
6546     offset += arg_slot.as_constant() * stackElementSize;
6547   } else {
6548     scale_reg    = arg_slot.as_register();
6549     scale_factor = Address::times(stackElementSize);
6550   }
6551   offset += wordSize;           // return PC is on stack
6552   return Address(rsp, scale_reg, scale_factor, offset);
6553 }
6554 
6555 
6556 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6557   if (!VerifyOops) return;
6558 
6559   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6560   // Pass register number to verify_oop_subroutine
6561   const char* b = NULL;
6562   {
6563     ResourceMark rm;
6564     stringStream ss;
6565     ss.print("verify_oop_addr: %s", s);
6566     b = code_string(ss.as_string());
6567   }
6568 #ifdef _LP64
6569   push(rscratch1);                    // save r10, trashed by movptr()
6570 #endif
6571   push(rax);                          // save rax,
6572   // addr may contain rsp so we will have to adjust it based on the push
6573   // we just did (and on 64 bit we do two pushes)
6574   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6575   // stores rax into addr which is backwards of what was intended.
6576   if (addr.uses(rsp)) {
6577     lea(rax, addr);
6578     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6579   } else {
6580     pushptr(addr);
6581   }
6582 
6583   ExternalAddress buffer((address) b);
6584   // pass msg argument
6585   // avoid using pushptr, as it modifies scratch registers
6586   // and our contract is not to modify anything
6587   movptr(rax, buffer.addr());
6588   push(rax);
6589 
6590   // call indirectly to solve generation ordering problem
6591   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6592   call(rax);
6593   // Caller pops the arguments (addr, message) and restores rax, r10.
6594 }
6595 
6596 void MacroAssembler::verify_tlab() {
6597 #ifdef ASSERT
6598   if (UseTLAB && VerifyOops) {
6599     Label next, ok;
6600     Register t1 = rsi;
6601     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6602 
6603     push(t1);
6604     NOT_LP64(push(thread_reg));
6605     NOT_LP64(get_thread(thread_reg));
6606 
6607     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6608     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6609     jcc(Assembler::aboveEqual, next);
6610     STOP("assert(top >= start)");
6611     should_not_reach_here();
6612 
6613     bind(next);
6614     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6615     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6616     jcc(Assembler::aboveEqual, ok);
6617     STOP("assert(top <= end)");
6618     should_not_reach_here();
6619 
6620     bind(ok);
6621     NOT_LP64(pop(thread_reg));
6622     pop(t1);
6623   }
6624 #endif
6625 }
6626 
6627 class ControlWord {
6628  public:
6629   int32_t _value;
6630 
6631   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6632   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6633   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6634   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6635   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6636   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6637   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6638   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6639 
6640   void print() const {
6641     // rounding control
6642     const char* rc;
6643     switch (rounding_control()) {
6644       case 0: rc = "round near"; break;
6645       case 1: rc = "round down"; break;
6646       case 2: rc = "round up  "; break;
6647       case 3: rc = "chop      "; break;
6648     };
6649     // precision control
6650     const char* pc;
6651     switch (precision_control()) {
6652       case 0: pc = "24 bits "; break;
6653       case 1: pc = "reserved"; break;
6654       case 2: pc = "53 bits "; break;
6655       case 3: pc = "64 bits "; break;
6656     };
6657     // flags
6658     char f[9];
6659     f[0] = ' ';
6660     f[1] = ' ';
6661     f[2] = (precision   ()) ? 'P' : 'p';
6662     f[3] = (underflow   ()) ? 'U' : 'u';
6663     f[4] = (overflow    ()) ? 'O' : 'o';
6664     f[5] = (zero_divide ()) ? 'Z' : 'z';
6665     f[6] = (denormalized()) ? 'D' : 'd';
6666     f[7] = (invalid     ()) ? 'I' : 'i';
6667     f[8] = '\x0';
6668     // output
6669     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6670   }
6671 
6672 };
6673 
6674 class StatusWord {
6675  public:
6676   int32_t _value;
6677 
6678   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6679   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6680   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6681   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6682   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6683   int  top() const                     { return  (_value >> 11) & 7      ; }
6684   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6685   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6686   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6687   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6688   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6689   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6690   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6691   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6692 
6693   void print() const {
6694     // condition codes
6695     char c[5];
6696     c[0] = (C3()) ? '3' : '-';
6697     c[1] = (C2()) ? '2' : '-';
6698     c[2] = (C1()) ? '1' : '-';
6699     c[3] = (C0()) ? '0' : '-';
6700     c[4] = '\x0';
6701     // flags
6702     char f[9];
6703     f[0] = (error_status()) ? 'E' : '-';
6704     f[1] = (stack_fault ()) ? 'S' : '-';
6705     f[2] = (precision   ()) ? 'P' : '-';
6706     f[3] = (underflow   ()) ? 'U' : '-';
6707     f[4] = (overflow    ()) ? 'O' : '-';
6708     f[5] = (zero_divide ()) ? 'Z' : '-';
6709     f[6] = (denormalized()) ? 'D' : '-';
6710     f[7] = (invalid     ()) ? 'I' : '-';
6711     f[8] = '\x0';
6712     // output
6713     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6714   }
6715 
6716 };
6717 
6718 class TagWord {
6719  public:
6720   int32_t _value;
6721 
6722   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6723 
6724   void print() const {
6725     printf("%04x", _value & 0xFFFF);
6726   }
6727 
6728 };
6729 
6730 class FPU_Register {
6731  public:
6732   int32_t _m0;
6733   int32_t _m1;
6734   int16_t _ex;
6735 
6736   bool is_indefinite() const           {
6737     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6738   }
6739 
6740   void print() const {
6741     char  sign = (_ex < 0) ? '-' : '+';
6742     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6743     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6744   };
6745 
6746 };
6747 
6748 class FPU_State {
6749  public:
6750   enum {
6751     register_size       = 10,
6752     number_of_registers =  8,
6753     register_mask       =  7
6754   };
6755 
6756   ControlWord  _control_word;
6757   StatusWord   _status_word;
6758   TagWord      _tag_word;
6759   int32_t      _error_offset;
6760   int32_t      _error_selector;
6761   int32_t      _data_offset;
6762   int32_t      _data_selector;
6763   int8_t       _register[register_size * number_of_registers];
6764 
6765   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6766   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6767 
6768   const char* tag_as_string(int tag) const {
6769     switch (tag) {
6770       case 0: return "valid";
6771       case 1: return "zero";
6772       case 2: return "special";
6773       case 3: return "empty";
6774     }
6775     ShouldNotReachHere();
6776     return NULL;
6777   }
6778 
6779   void print() const {
6780     // print computation registers
6781     { int t = _status_word.top();
6782       for (int i = 0; i < number_of_registers; i++) {
6783         int j = (i - t) & register_mask;
6784         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6785         st(j)->print();
6786         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6787       }
6788     }
6789     printf("\n");
6790     // print control registers
6791     printf("ctrl = "); _control_word.print(); printf("\n");
6792     printf("stat = "); _status_word .print(); printf("\n");
6793     printf("tags = "); _tag_word    .print(); printf("\n");
6794   }
6795 
6796 };
6797 
6798 class Flag_Register {
6799  public:
6800   int32_t _value;
6801 
6802   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6803   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6804   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6805   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6806   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6807   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6808   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6809 
6810   void print() const {
6811     // flags
6812     char f[8];
6813     f[0] = (overflow       ()) ? 'O' : '-';
6814     f[1] = (direction      ()) ? 'D' : '-';
6815     f[2] = (sign           ()) ? 'S' : '-';
6816     f[3] = (zero           ()) ? 'Z' : '-';
6817     f[4] = (auxiliary_carry()) ? 'A' : '-';
6818     f[5] = (parity         ()) ? 'P' : '-';
6819     f[6] = (carry          ()) ? 'C' : '-';
6820     f[7] = '\x0';
6821     // output
6822     printf("%08x  flags = %s", _value, f);
6823   }
6824 
6825 };
6826 
6827 class IU_Register {
6828  public:
6829   int32_t _value;
6830 
6831   void print() const {
6832     printf("%08x  %11d", _value, _value);
6833   }
6834 
6835 };
6836 
6837 class IU_State {
6838  public:
6839   Flag_Register _eflags;
6840   IU_Register   _rdi;
6841   IU_Register   _rsi;
6842   IU_Register   _rbp;
6843   IU_Register   _rsp;
6844   IU_Register   _rbx;
6845   IU_Register   _rdx;
6846   IU_Register   _rcx;
6847   IU_Register   _rax;
6848 
6849   void print() const {
6850     // computation registers
6851     printf("rax,  = "); _rax.print(); printf("\n");
6852     printf("rbx,  = "); _rbx.print(); printf("\n");
6853     printf("rcx  = "); _rcx.print(); printf("\n");
6854     printf("rdx  = "); _rdx.print(); printf("\n");
6855     printf("rdi  = "); _rdi.print(); printf("\n");
6856     printf("rsi  = "); _rsi.print(); printf("\n");
6857     printf("rbp,  = "); _rbp.print(); printf("\n");
6858     printf("rsp  = "); _rsp.print(); printf("\n");
6859     printf("\n");
6860     // control registers
6861     printf("flgs = "); _eflags.print(); printf("\n");
6862   }
6863 };
6864 
6865 
6866 class CPU_State {
6867  public:
6868   FPU_State _fpu_state;
6869   IU_State  _iu_state;
6870 
6871   void print() const {
6872     printf("--------------------------------------------------\n");
6873     _iu_state .print();
6874     printf("\n");
6875     _fpu_state.print();
6876     printf("--------------------------------------------------\n");
6877   }
6878 
6879 };
6880 
6881 
6882 static void _print_CPU_state(CPU_State* state) {
6883   state->print();
6884 };
6885 
6886 
6887 void MacroAssembler::print_CPU_state() {
6888   push_CPU_state();
6889   push(rsp);                // pass CPU state
6890   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6891   addptr(rsp, wordSize);       // discard argument
6892   pop_CPU_state();
6893 }
6894 
6895 
6896 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6897   static int counter = 0;
6898   FPU_State* fs = &state->_fpu_state;
6899   counter++;
6900   // For leaf calls, only verify that the top few elements remain empty.
6901   // We only need 1 empty at the top for C2 code.
6902   if( stack_depth < 0 ) {
6903     if( fs->tag_for_st(7) != 3 ) {
6904       printf("FPR7 not empty\n");
6905       state->print();
6906       assert(false, "error");
6907       return false;
6908     }
6909     return true;                // All other stack states do not matter
6910   }
6911 
6912   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6913          "bad FPU control word");
6914 
6915   // compute stack depth
6916   int i = 0;
6917   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6918   int d = i;
6919   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6920   // verify findings
6921   if (i != FPU_State::number_of_registers) {
6922     // stack not contiguous
6923     printf("%s: stack not contiguous at ST%d\n", s, i);
6924     state->print();
6925     assert(false, "error");
6926     return false;
6927   }
6928   // check if computed stack depth corresponds to expected stack depth
6929   if (stack_depth < 0) {
6930     // expected stack depth is -stack_depth or less
6931     if (d > -stack_depth) {
6932       // too many elements on the stack
6933       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6934       state->print();
6935       assert(false, "error");
6936       return false;
6937     }
6938   } else {
6939     // expected stack depth is stack_depth
6940     if (d != stack_depth) {
6941       // wrong stack depth
6942       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6943       state->print();
6944       assert(false, "error");
6945       return false;
6946     }
6947   }
6948   // everything is cool
6949   return true;
6950 }
6951 
6952 
6953 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6954   if (!VerifyFPU) return;
6955   push_CPU_state();
6956   push(rsp);                // pass CPU state
6957   ExternalAddress msg((address) s);
6958   // pass message string s
6959   pushptr(msg.addr());
6960   push(stack_depth);        // pass stack depth
6961   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6962   addptr(rsp, 3 * wordSize);   // discard arguments
6963   // check for error
6964   { Label L;
6965     testl(rax, rax);
6966     jcc(Assembler::notZero, L);
6967     int3();                  // break if error condition
6968     bind(L);
6969   }
6970   pop_CPU_state();
6971 }
6972 
6973 void MacroAssembler::restore_cpu_control_state_after_jni() {
6974   // Either restore the MXCSR register after returning from the JNI Call
6975   // or verify that it wasn't changed (with -Xcheck:jni flag).
6976   if (VM_Version::supports_sse()) {
6977     if (RestoreMXCSROnJNICalls) {
6978       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6979     } else if (CheckJNICalls) {
6980       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6981     }
6982   }
6983   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6984   vzeroupper();
6985 
6986 #ifndef _LP64
6987   // Either restore the x87 floating pointer control word after returning
6988   // from the JNI call or verify that it wasn't changed.
6989   if (CheckJNICalls) {
6990     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6991   }
6992 #endif // _LP64
6993 }
6994 
6995 void MacroAssembler::load_mirror(Register mirror, Register method) {
6996   // get mirror
6997   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6998   movptr(mirror, Address(method, Method::const_offset()));
6999   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
7000   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
7001   movptr(mirror, Address(mirror, mirror_offset));
7002 }
7003 
7004 void MacroAssembler::load_klass(Register dst, Register src) {
7005 #ifdef _LP64
7006   if (UseCompressedClassPointers) {
7007     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
7008     decode_klass_not_null(dst);
7009   } else
7010 #endif
7011     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
7012 }
7013 
7014 void MacroAssembler::load_prototype_header(Register dst, Register src) {
7015   load_klass(dst, src);
7016   movptr(dst, Address(dst, Klass::prototype_header_offset()));
7017 }
7018 
7019 void MacroAssembler::store_klass(Register dst, Register src) {
7020 #ifdef _LP64
7021   if (UseCompressedClassPointers) {
7022     encode_klass_not_null(src);
7023     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
7024   } else
7025 #endif
7026     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
7027 }
7028 
7029 void MacroAssembler::load_heap_oop(Register dst, Address src) {
7030 #ifdef _LP64
7031   // FIXME: Must change all places where we try to load the klass.
7032   if (UseCompressedOops) {
7033     movl(dst, src);
7034     decode_heap_oop(dst);
7035   } else
7036 #endif
7037     movptr(dst, src);
7038 }
7039 
7040 // Doesn't do verfication, generates fixed size code
7041 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
7042 #ifdef _LP64
7043   if (UseCompressedOops) {
7044     movl(dst, src);
7045     decode_heap_oop_not_null(dst);
7046   } else
7047 #endif
7048     movptr(dst, src);
7049 }
7050 
7051 void MacroAssembler::store_heap_oop(Address dst, Register src) {
7052 #ifdef _LP64
7053   if (UseCompressedOops) {
7054     assert(!dst.uses(src), "not enough registers");
7055     encode_heap_oop(src);
7056     movl(dst, src);
7057   } else
7058 #endif
7059     movptr(dst, src);
7060 }
7061 
7062 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
7063   assert_different_registers(src1, tmp);
7064 #ifdef _LP64
7065   if (UseCompressedOops) {
7066     bool did_push = false;
7067     if (tmp == noreg) {
7068       tmp = rax;
7069       push(tmp);
7070       did_push = true;
7071       assert(!src2.uses(rsp), "can't push");
7072     }
7073     load_heap_oop(tmp, src2);
7074     cmpptr(src1, tmp);
7075     if (did_push)  pop(tmp);
7076   } else
7077 #endif
7078     cmpptr(src1, src2);
7079 }
7080 
7081 // Used for storing NULLs.
7082 void MacroAssembler::store_heap_oop_null(Address dst) {
7083 #ifdef _LP64
7084   if (UseCompressedOops) {
7085     movl(dst, (int32_t)NULL_WORD);
7086   } else {
7087     movslq(dst, (int32_t)NULL_WORD);
7088   }
7089 #else
7090   movl(dst, (int32_t)NULL_WORD);
7091 #endif
7092 }
7093 
7094 #ifdef _LP64
7095 void MacroAssembler::store_klass_gap(Register dst, Register src) {
7096   if (UseCompressedClassPointers) {
7097     // Store to klass gap in destination
7098     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
7099   }
7100 }
7101 
7102 #ifdef ASSERT
7103 void MacroAssembler::verify_heapbase(const char* msg) {
7104   assert (UseCompressedOops, "should be compressed");
7105   assert (Universe::heap() != NULL, "java heap should be initialized");
7106   if (CheckCompressedOops) {
7107     Label ok;
7108     push(rscratch1); // cmpptr trashes rscratch1
7109     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7110     jcc(Assembler::equal, ok);
7111     STOP(msg);
7112     bind(ok);
7113     pop(rscratch1);
7114   }
7115 }
7116 #endif
7117 
7118 // Algorithm must match oop.inline.hpp encode_heap_oop.
7119 void MacroAssembler::encode_heap_oop(Register r) {
7120 #ifdef ASSERT
7121   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
7122 #endif
7123   verify_oop(r, "broken oop in encode_heap_oop");
7124   if (Universe::narrow_oop_base() == NULL) {
7125     if (Universe::narrow_oop_shift() != 0) {
7126       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7127       shrq(r, LogMinObjAlignmentInBytes);
7128     }
7129     return;
7130   }
7131   testq(r, r);
7132   cmovq(Assembler::equal, r, r12_heapbase);
7133   subq(r, r12_heapbase);
7134   shrq(r, LogMinObjAlignmentInBytes);
7135 }
7136 
7137 void MacroAssembler::encode_heap_oop_not_null(Register r) {
7138 #ifdef ASSERT
7139   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
7140   if (CheckCompressedOops) {
7141     Label ok;
7142     testq(r, r);
7143     jcc(Assembler::notEqual, ok);
7144     STOP("null oop passed to encode_heap_oop_not_null");
7145     bind(ok);
7146   }
7147 #endif
7148   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7149   if (Universe::narrow_oop_base() != NULL) {
7150     subq(r, r12_heapbase);
7151   }
7152   if (Universe::narrow_oop_shift() != 0) {
7153     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7154     shrq(r, LogMinObjAlignmentInBytes);
7155   }
7156 }
7157 
7158 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7159 #ifdef ASSERT
7160   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7161   if (CheckCompressedOops) {
7162     Label ok;
7163     testq(src, src);
7164     jcc(Assembler::notEqual, ok);
7165     STOP("null oop passed to encode_heap_oop_not_null2");
7166     bind(ok);
7167   }
7168 #endif
7169   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7170   if (dst != src) {
7171     movq(dst, src);
7172   }
7173   if (Universe::narrow_oop_base() != NULL) {
7174     subq(dst, r12_heapbase);
7175   }
7176   if (Universe::narrow_oop_shift() != 0) {
7177     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7178     shrq(dst, LogMinObjAlignmentInBytes);
7179   }
7180 }
7181 
7182 void  MacroAssembler::decode_heap_oop(Register r) {
7183 #ifdef ASSERT
7184   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7185 #endif
7186   if (Universe::narrow_oop_base() == NULL) {
7187     if (Universe::narrow_oop_shift() != 0) {
7188       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7189       shlq(r, LogMinObjAlignmentInBytes);
7190     }
7191   } else {
7192     Label done;
7193     shlq(r, LogMinObjAlignmentInBytes);
7194     jccb(Assembler::equal, done);
7195     addq(r, r12_heapbase);
7196     bind(done);
7197   }
7198   verify_oop(r, "broken oop in decode_heap_oop");
7199 }
7200 
7201 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7202   // Note: it will change flags
7203   assert (UseCompressedOops, "should only be used for compressed headers");
7204   assert (Universe::heap() != NULL, "java heap should be initialized");
7205   // Cannot assert, unverified entry point counts instructions (see .ad file)
7206   // vtableStubs also counts instructions in pd_code_size_limit.
7207   // Also do not verify_oop as this is called by verify_oop.
7208   if (Universe::narrow_oop_shift() != 0) {
7209     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7210     shlq(r, LogMinObjAlignmentInBytes);
7211     if (Universe::narrow_oop_base() != NULL) {
7212       addq(r, r12_heapbase);
7213     }
7214   } else {
7215     assert (Universe::narrow_oop_base() == NULL, "sanity");
7216   }
7217 }
7218 
7219 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7220   // Note: it will change flags
7221   assert (UseCompressedOops, "should only be used for compressed headers");
7222   assert (Universe::heap() != NULL, "java heap should be initialized");
7223   // Cannot assert, unverified entry point counts instructions (see .ad file)
7224   // vtableStubs also counts instructions in pd_code_size_limit.
7225   // Also do not verify_oop as this is called by verify_oop.
7226   if (Universe::narrow_oop_shift() != 0) {
7227     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7228     if (LogMinObjAlignmentInBytes == Address::times_8) {
7229       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7230     } else {
7231       if (dst != src) {
7232         movq(dst, src);
7233       }
7234       shlq(dst, LogMinObjAlignmentInBytes);
7235       if (Universe::narrow_oop_base() != NULL) {
7236         addq(dst, r12_heapbase);
7237       }
7238     }
7239   } else {
7240     assert (Universe::narrow_oop_base() == NULL, "sanity");
7241     if (dst != src) {
7242       movq(dst, src);
7243     }
7244   }
7245 }
7246 
7247 void MacroAssembler::encode_klass_not_null(Register r) {
7248   if (Universe::narrow_klass_base() != NULL) {
7249     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7250     assert(r != r12_heapbase, "Encoding a klass in r12");
7251     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7252     subq(r, r12_heapbase);
7253   }
7254   if (Universe::narrow_klass_shift() != 0) {
7255     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7256     shrq(r, LogKlassAlignmentInBytes);
7257   }
7258   if (Universe::narrow_klass_base() != NULL) {
7259     reinit_heapbase();
7260   }
7261 }
7262 
7263 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7264   if (dst == src) {
7265     encode_klass_not_null(src);
7266   } else {
7267     if (Universe::narrow_klass_base() != NULL) {
7268       mov64(dst, (int64_t)Universe::narrow_klass_base());
7269       negq(dst);
7270       addq(dst, src);
7271     } else {
7272       movptr(dst, src);
7273     }
7274     if (Universe::narrow_klass_shift() != 0) {
7275       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7276       shrq(dst, LogKlassAlignmentInBytes);
7277     }
7278   }
7279 }
7280 
7281 // Function instr_size_for_decode_klass_not_null() counts the instructions
7282 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7283 // when (Universe::heap() != NULL).  Hence, if the instructions they
7284 // generate change, then this method needs to be updated.
7285 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7286   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7287   if (Universe::narrow_klass_base() != NULL) {
7288     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7289     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7290   } else {
7291     // longest load decode klass function, mov64, leaq
7292     return 16;
7293   }
7294 }
7295 
7296 // !!! If the instructions that get generated here change then function
7297 // instr_size_for_decode_klass_not_null() needs to get updated.
7298 void  MacroAssembler::decode_klass_not_null(Register r) {
7299   // Note: it will change flags
7300   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7301   assert(r != r12_heapbase, "Decoding a klass in r12");
7302   // Cannot assert, unverified entry point counts instructions (see .ad file)
7303   // vtableStubs also counts instructions in pd_code_size_limit.
7304   // Also do not verify_oop as this is called by verify_oop.
7305   if (Universe::narrow_klass_shift() != 0) {
7306     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7307     shlq(r, LogKlassAlignmentInBytes);
7308   }
7309   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7310   if (Universe::narrow_klass_base() != NULL) {
7311     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7312     addq(r, r12_heapbase);
7313     reinit_heapbase();
7314   }
7315 }
7316 
7317 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7318   // Note: it will change flags
7319   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7320   if (dst == src) {
7321     decode_klass_not_null(dst);
7322   } else {
7323     // Cannot assert, unverified entry point counts instructions (see .ad file)
7324     // vtableStubs also counts instructions in pd_code_size_limit.
7325     // Also do not verify_oop as this is called by verify_oop.
7326     mov64(dst, (int64_t)Universe::narrow_klass_base());
7327     if (Universe::narrow_klass_shift() != 0) {
7328       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7329       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7330       leaq(dst, Address(dst, src, Address::times_8, 0));
7331     } else {
7332       addq(dst, src);
7333     }
7334   }
7335 }
7336 
7337 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7338   assert (UseCompressedOops, "should only be used for compressed headers");
7339   assert (Universe::heap() != NULL, "java heap should be initialized");
7340   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7341   int oop_index = oop_recorder()->find_index(obj);
7342   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7343   mov_narrow_oop(dst, oop_index, rspec);
7344 }
7345 
7346 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7347   assert (UseCompressedOops, "should only be used for compressed headers");
7348   assert (Universe::heap() != NULL, "java heap should be initialized");
7349   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7350   int oop_index = oop_recorder()->find_index(obj);
7351   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7352   mov_narrow_oop(dst, oop_index, rspec);
7353 }
7354 
7355 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7356   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7357   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7358   int klass_index = oop_recorder()->find_index(k);
7359   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7360   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7361 }
7362 
7363 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7364   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7365   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7366   int klass_index = oop_recorder()->find_index(k);
7367   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7368   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7369 }
7370 
7371 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7372   assert (UseCompressedOops, "should only be used for compressed headers");
7373   assert (Universe::heap() != NULL, "java heap should be initialized");
7374   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7375   int oop_index = oop_recorder()->find_index(obj);
7376   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7377   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7378 }
7379 
7380 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7381   assert (UseCompressedOops, "should only be used for compressed headers");
7382   assert (Universe::heap() != NULL, "java heap should be initialized");
7383   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7384   int oop_index = oop_recorder()->find_index(obj);
7385   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7386   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7387 }
7388 
7389 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7390   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7391   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7392   int klass_index = oop_recorder()->find_index(k);
7393   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7394   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7395 }
7396 
7397 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7398   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7399   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7400   int klass_index = oop_recorder()->find_index(k);
7401   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7402   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7403 }
7404 
7405 void MacroAssembler::reinit_heapbase() {
7406   if (UseCompressedOops || UseCompressedClassPointers) {
7407     if (Universe::heap() != NULL) {
7408       if (Universe::narrow_oop_base() == NULL) {
7409         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7410       } else {
7411         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7412       }
7413     } else {
7414       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7415     }
7416   }
7417 }
7418 
7419 #endif // _LP64
7420 
7421 
7422 // C2 compiled method's prolog code.
7423 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7424 
7425   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7426   // NativeJump::patch_verified_entry will be able to patch out the entry
7427   // code safely. The push to verify stack depth is ok at 5 bytes,
7428   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7429   // stack bang then we must use the 6 byte frame allocation even if
7430   // we have no frame. :-(
7431   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7432 
7433   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7434   // Remove word for return addr
7435   framesize -= wordSize;
7436   stack_bang_size -= wordSize;
7437 
7438   // Calls to C2R adapters often do not accept exceptional returns.
7439   // We require that their callers must bang for them.  But be careful, because
7440   // some VM calls (such as call site linkage) can use several kilobytes of
7441   // stack.  But the stack safety zone should account for that.
7442   // See bugs 4446381, 4468289, 4497237.
7443   if (stack_bang_size > 0) {
7444     generate_stack_overflow_check(stack_bang_size);
7445 
7446     // We always push rbp, so that on return to interpreter rbp, will be
7447     // restored correctly and we can correct the stack.
7448     push(rbp);
7449     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7450     if (PreserveFramePointer) {
7451       mov(rbp, rsp);
7452     }
7453     // Remove word for ebp
7454     framesize -= wordSize;
7455 
7456     // Create frame
7457     if (framesize) {
7458       subptr(rsp, framesize);
7459     }
7460   } else {
7461     // Create frame (force generation of a 4 byte immediate value)
7462     subptr_imm32(rsp, framesize);
7463 
7464     // Save RBP register now.
7465     framesize -= wordSize;
7466     movptr(Address(rsp, framesize), rbp);
7467     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7468     if (PreserveFramePointer) {
7469       movptr(rbp, rsp);
7470       if (framesize > 0) {
7471         addptr(rbp, framesize);
7472       }
7473     }
7474   }
7475 
7476   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7477     framesize -= wordSize;
7478     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7479   }
7480 
7481 #ifndef _LP64
7482   // If method sets FPU control word do it now
7483   if (fp_mode_24b) {
7484     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7485   }
7486   if (UseSSE >= 2 && VerifyFPU) {
7487     verify_FPU(0, "FPU stack must be clean on entry");
7488   }
7489 #endif
7490 
7491 #ifdef ASSERT
7492   if (VerifyStackAtCalls) {
7493     Label L;
7494     push(rax);
7495     mov(rax, rsp);
7496     andptr(rax, StackAlignmentInBytes-1);
7497     cmpptr(rax, StackAlignmentInBytes-wordSize);
7498     pop(rax);
7499     jcc(Assembler::equal, L);
7500     STOP("Stack is not properly aligned!");
7501     bind(L);
7502   }
7503 #endif
7504 
7505 }
7506 
7507 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7508   // cnt - number of qwords (8-byte words).
7509   // base - start address, qword aligned.
7510   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7511   assert(base==rdi, "base register must be edi for rep stos");
7512   assert(tmp==rax,   "tmp register must be eax for rep stos");
7513   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7514   assert(InitArrayShortSize % BytesPerLong == 0,
7515     "InitArrayShortSize should be the multiple of BytesPerLong");
7516 
7517   Label DONE;
7518 
7519   xorptr(tmp, tmp);
7520 
7521   if (!is_large) {
7522     Label LOOP, LONG;
7523     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7524     jccb(Assembler::greater, LONG);
7525 
7526     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7527 
7528     decrement(cnt);
7529     jccb(Assembler::negative, DONE); // Zero length
7530 
7531     // Use individual pointer-sized stores for small counts:
7532     BIND(LOOP);
7533     movptr(Address(base, cnt, Address::times_ptr), tmp);
7534     decrement(cnt);
7535     jccb(Assembler::greaterEqual, LOOP);
7536     jmpb(DONE);
7537 
7538     BIND(LONG);
7539   }
7540 
7541   // Use longer rep-prefixed ops for non-small counts:
7542   if (UseFastStosb) {
7543     shlptr(cnt, 3); // convert to number of bytes
7544     rep_stosb();
7545   } else {
7546     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7547     rep_stos();
7548   }
7549 
7550   BIND(DONE);
7551 }
7552 
7553 #ifdef COMPILER2
7554 
7555 // IndexOf for constant substrings with size >= 8 chars
7556 // which don't need to be loaded through stack.
7557 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7558                                       Register cnt1, Register cnt2,
7559                                       int int_cnt2,  Register result,
7560                                       XMMRegister vec, Register tmp,
7561                                       int ae) {
7562   ShortBranchVerifier sbv(this);
7563   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7564   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7565 
7566   // This method uses the pcmpestri instruction with bound registers
7567   //   inputs:
7568   //     xmm - substring
7569   //     rax - substring length (elements count)
7570   //     mem - scanned string
7571   //     rdx - string length (elements count)
7572   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7573   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7574   //   outputs:
7575   //     rcx - matched index in string
7576   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7577   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7578   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7579   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7580   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7581 
7582   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7583         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7584         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7585 
7586   // Note, inline_string_indexOf() generates checks:
7587   // if (substr.count > string.count) return -1;
7588   // if (substr.count == 0) return 0;
7589   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7590 
7591   // Load substring.
7592   if (ae == StrIntrinsicNode::UL) {
7593     pmovzxbw(vec, Address(str2, 0));
7594   } else {
7595     movdqu(vec, Address(str2, 0));
7596   }
7597   movl(cnt2, int_cnt2);
7598   movptr(result, str1); // string addr
7599 
7600   if (int_cnt2 > stride) {
7601     jmpb(SCAN_TO_SUBSTR);
7602 
7603     // Reload substr for rescan, this code
7604     // is executed only for large substrings (> 8 chars)
7605     bind(RELOAD_SUBSTR);
7606     if (ae == StrIntrinsicNode::UL) {
7607       pmovzxbw(vec, Address(str2, 0));
7608     } else {
7609       movdqu(vec, Address(str2, 0));
7610     }
7611     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7612 
7613     bind(RELOAD_STR);
7614     // We came here after the beginning of the substring was
7615     // matched but the rest of it was not so we need to search
7616     // again. Start from the next element after the previous match.
7617 
7618     // cnt2 is number of substring reminding elements and
7619     // cnt1 is number of string reminding elements when cmp failed.
7620     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7621     subl(cnt1, cnt2);
7622     addl(cnt1, int_cnt2);
7623     movl(cnt2, int_cnt2); // Now restore cnt2
7624 
7625     decrementl(cnt1);     // Shift to next element
7626     cmpl(cnt1, cnt2);
7627     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7628 
7629     addptr(result, (1<<scale1));
7630 
7631   } // (int_cnt2 > 8)
7632 
7633   // Scan string for start of substr in 16-byte vectors
7634   bind(SCAN_TO_SUBSTR);
7635   pcmpestri(vec, Address(result, 0), mode);
7636   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7637   subl(cnt1, stride);
7638   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7639   cmpl(cnt1, cnt2);
7640   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7641   addptr(result, 16);
7642   jmpb(SCAN_TO_SUBSTR);
7643 
7644   // Found a potential substr
7645   bind(FOUND_CANDIDATE);
7646   // Matched whole vector if first element matched (tmp(rcx) == 0).
7647   if (int_cnt2 == stride) {
7648     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7649   } else { // int_cnt2 > 8
7650     jccb(Assembler::overflow, FOUND_SUBSTR);
7651   }
7652   // After pcmpestri tmp(rcx) contains matched element index
7653   // Compute start addr of substr
7654   lea(result, Address(result, tmp, scale1));
7655 
7656   // Make sure string is still long enough
7657   subl(cnt1, tmp);
7658   cmpl(cnt1, cnt2);
7659   if (int_cnt2 == stride) {
7660     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7661   } else { // int_cnt2 > 8
7662     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7663   }
7664   // Left less then substring.
7665 
7666   bind(RET_NOT_FOUND);
7667   movl(result, -1);
7668   jmp(EXIT);
7669 
7670   if (int_cnt2 > stride) {
7671     // This code is optimized for the case when whole substring
7672     // is matched if its head is matched.
7673     bind(MATCH_SUBSTR_HEAD);
7674     pcmpestri(vec, Address(result, 0), mode);
7675     // Reload only string if does not match
7676     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7677 
7678     Label CONT_SCAN_SUBSTR;
7679     // Compare the rest of substring (> 8 chars).
7680     bind(FOUND_SUBSTR);
7681     // First 8 chars are already matched.
7682     negptr(cnt2);
7683     addptr(cnt2, stride);
7684 
7685     bind(SCAN_SUBSTR);
7686     subl(cnt1, stride);
7687     cmpl(cnt2, -stride); // Do not read beyond substring
7688     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7689     // Back-up strings to avoid reading beyond substring:
7690     // cnt1 = cnt1 - cnt2 + 8
7691     addl(cnt1, cnt2); // cnt2 is negative
7692     addl(cnt1, stride);
7693     movl(cnt2, stride); negptr(cnt2);
7694     bind(CONT_SCAN_SUBSTR);
7695     if (int_cnt2 < (int)G) {
7696       int tail_off1 = int_cnt2<<scale1;
7697       int tail_off2 = int_cnt2<<scale2;
7698       if (ae == StrIntrinsicNode::UL) {
7699         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7700       } else {
7701         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7702       }
7703       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7704     } else {
7705       // calculate index in register to avoid integer overflow (int_cnt2*2)
7706       movl(tmp, int_cnt2);
7707       addptr(tmp, cnt2);
7708       if (ae == StrIntrinsicNode::UL) {
7709         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7710       } else {
7711         movdqu(vec, Address(str2, tmp, scale2, 0));
7712       }
7713       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7714     }
7715     // Need to reload strings pointers if not matched whole vector
7716     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7717     addptr(cnt2, stride);
7718     jcc(Assembler::negative, SCAN_SUBSTR);
7719     // Fall through if found full substring
7720 
7721   } // (int_cnt2 > 8)
7722 
7723   bind(RET_FOUND);
7724   // Found result if we matched full small substring.
7725   // Compute substr offset
7726   subptr(result, str1);
7727   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7728     shrl(result, 1); // index
7729   }
7730   bind(EXIT);
7731 
7732 } // string_indexofC8
7733 
7734 // Small strings are loaded through stack if they cross page boundary.
7735 void MacroAssembler::string_indexof(Register str1, Register str2,
7736                                     Register cnt1, Register cnt2,
7737                                     int int_cnt2,  Register result,
7738                                     XMMRegister vec, Register tmp,
7739                                     int ae) {
7740   ShortBranchVerifier sbv(this);
7741   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7742   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7743 
7744   //
7745   // int_cnt2 is length of small (< 8 chars) constant substring
7746   // or (-1) for non constant substring in which case its length
7747   // is in cnt2 register.
7748   //
7749   // Note, inline_string_indexOf() generates checks:
7750   // if (substr.count > string.count) return -1;
7751   // if (substr.count == 0) return 0;
7752   //
7753   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7754   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7755   // This method uses the pcmpestri instruction with bound registers
7756   //   inputs:
7757   //     xmm - substring
7758   //     rax - substring length (elements count)
7759   //     mem - scanned string
7760   //     rdx - string length (elements count)
7761   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7762   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7763   //   outputs:
7764   //     rcx - matched index in string
7765   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7766   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7767   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7768   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7769 
7770   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7771         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7772         FOUND_CANDIDATE;
7773 
7774   { //========================================================
7775     // We don't know where these strings are located
7776     // and we can't read beyond them. Load them through stack.
7777     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7778 
7779     movptr(tmp, rsp); // save old SP
7780 
7781     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7782       if (int_cnt2 == (1>>scale2)) { // One byte
7783         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7784         load_unsigned_byte(result, Address(str2, 0));
7785         movdl(vec, result); // move 32 bits
7786       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7787         // Not enough header space in 32-bit VM: 12+3 = 15.
7788         movl(result, Address(str2, -1));
7789         shrl(result, 8);
7790         movdl(vec, result); // move 32 bits
7791       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7792         load_unsigned_short(result, Address(str2, 0));
7793         movdl(vec, result); // move 32 bits
7794       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7795         movdl(vec, Address(str2, 0)); // move 32 bits
7796       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7797         movq(vec, Address(str2, 0));  // move 64 bits
7798       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7799         // Array header size is 12 bytes in 32-bit VM
7800         // + 6 bytes for 3 chars == 18 bytes,
7801         // enough space to load vec and shift.
7802         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7803         if (ae == StrIntrinsicNode::UL) {
7804           int tail_off = int_cnt2-8;
7805           pmovzxbw(vec, Address(str2, tail_off));
7806           psrldq(vec, -2*tail_off);
7807         }
7808         else {
7809           int tail_off = int_cnt2*(1<<scale2);
7810           movdqu(vec, Address(str2, tail_off-16));
7811           psrldq(vec, 16-tail_off);
7812         }
7813       }
7814     } else { // not constant substring
7815       cmpl(cnt2, stride);
7816       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7817 
7818       // We can read beyond string if srt+16 does not cross page boundary
7819       // since heaps are aligned and mapped by pages.
7820       assert(os::vm_page_size() < (int)G, "default page should be small");
7821       movl(result, str2); // We need only low 32 bits
7822       andl(result, (os::vm_page_size()-1));
7823       cmpl(result, (os::vm_page_size()-16));
7824       jccb(Assembler::belowEqual, CHECK_STR);
7825 
7826       // Move small strings to stack to allow load 16 bytes into vec.
7827       subptr(rsp, 16);
7828       int stk_offset = wordSize-(1<<scale2);
7829       push(cnt2);
7830 
7831       bind(COPY_SUBSTR);
7832       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7833         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7834         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7835       } else if (ae == StrIntrinsicNode::UU) {
7836         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7837         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7838       }
7839       decrement(cnt2);
7840       jccb(Assembler::notZero, COPY_SUBSTR);
7841 
7842       pop(cnt2);
7843       movptr(str2, rsp);  // New substring address
7844     } // non constant
7845 
7846     bind(CHECK_STR);
7847     cmpl(cnt1, stride);
7848     jccb(Assembler::aboveEqual, BIG_STRINGS);
7849 
7850     // Check cross page boundary.
7851     movl(result, str1); // We need only low 32 bits
7852     andl(result, (os::vm_page_size()-1));
7853     cmpl(result, (os::vm_page_size()-16));
7854     jccb(Assembler::belowEqual, BIG_STRINGS);
7855 
7856     subptr(rsp, 16);
7857     int stk_offset = -(1<<scale1);
7858     if (int_cnt2 < 0) { // not constant
7859       push(cnt2);
7860       stk_offset += wordSize;
7861     }
7862     movl(cnt2, cnt1);
7863 
7864     bind(COPY_STR);
7865     if (ae == StrIntrinsicNode::LL) {
7866       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7867       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7868     } else {
7869       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7870       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7871     }
7872     decrement(cnt2);
7873     jccb(Assembler::notZero, COPY_STR);
7874 
7875     if (int_cnt2 < 0) { // not constant
7876       pop(cnt2);
7877     }
7878     movptr(str1, rsp);  // New string address
7879 
7880     bind(BIG_STRINGS);
7881     // Load substring.
7882     if (int_cnt2 < 0) { // -1
7883       if (ae == StrIntrinsicNode::UL) {
7884         pmovzxbw(vec, Address(str2, 0));
7885       } else {
7886         movdqu(vec, Address(str2, 0));
7887       }
7888       push(cnt2);       // substr count
7889       push(str2);       // substr addr
7890       push(str1);       // string addr
7891     } else {
7892       // Small (< 8 chars) constant substrings are loaded already.
7893       movl(cnt2, int_cnt2);
7894     }
7895     push(tmp);  // original SP
7896 
7897   } // Finished loading
7898 
7899   //========================================================
7900   // Start search
7901   //
7902 
7903   movptr(result, str1); // string addr
7904 
7905   if (int_cnt2  < 0) {  // Only for non constant substring
7906     jmpb(SCAN_TO_SUBSTR);
7907 
7908     // SP saved at sp+0
7909     // String saved at sp+1*wordSize
7910     // Substr saved at sp+2*wordSize
7911     // Substr count saved at sp+3*wordSize
7912 
7913     // Reload substr for rescan, this code
7914     // is executed only for large substrings (> 8 chars)
7915     bind(RELOAD_SUBSTR);
7916     movptr(str2, Address(rsp, 2*wordSize));
7917     movl(cnt2, Address(rsp, 3*wordSize));
7918     if (ae == StrIntrinsicNode::UL) {
7919       pmovzxbw(vec, Address(str2, 0));
7920     } else {
7921       movdqu(vec, Address(str2, 0));
7922     }
7923     // We came here after the beginning of the substring was
7924     // matched but the rest of it was not so we need to search
7925     // again. Start from the next element after the previous match.
7926     subptr(str1, result); // Restore counter
7927     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7928       shrl(str1, 1);
7929     }
7930     addl(cnt1, str1);
7931     decrementl(cnt1);   // Shift to next element
7932     cmpl(cnt1, cnt2);
7933     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7934 
7935     addptr(result, (1<<scale1));
7936   } // non constant
7937 
7938   // Scan string for start of substr in 16-byte vectors
7939   bind(SCAN_TO_SUBSTR);
7940   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7941   pcmpestri(vec, Address(result, 0), mode);
7942   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7943   subl(cnt1, stride);
7944   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7945   cmpl(cnt1, cnt2);
7946   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7947   addptr(result, 16);
7948 
7949   bind(ADJUST_STR);
7950   cmpl(cnt1, stride); // Do not read beyond string
7951   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7952   // Back-up string to avoid reading beyond string.
7953   lea(result, Address(result, cnt1, scale1, -16));
7954   movl(cnt1, stride);
7955   jmpb(SCAN_TO_SUBSTR);
7956 
7957   // Found a potential substr
7958   bind(FOUND_CANDIDATE);
7959   // After pcmpestri tmp(rcx) contains matched element index
7960 
7961   // Make sure string is still long enough
7962   subl(cnt1, tmp);
7963   cmpl(cnt1, cnt2);
7964   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7965   // Left less then substring.
7966 
7967   bind(RET_NOT_FOUND);
7968   movl(result, -1);
7969   jmpb(CLEANUP);
7970 
7971   bind(FOUND_SUBSTR);
7972   // Compute start addr of substr
7973   lea(result, Address(result, tmp, scale1));
7974   if (int_cnt2 > 0) { // Constant substring
7975     // Repeat search for small substring (< 8 chars)
7976     // from new point without reloading substring.
7977     // Have to check that we don't read beyond string.
7978     cmpl(tmp, stride-int_cnt2);
7979     jccb(Assembler::greater, ADJUST_STR);
7980     // Fall through if matched whole substring.
7981   } else { // non constant
7982     assert(int_cnt2 == -1, "should be != 0");
7983 
7984     addl(tmp, cnt2);
7985     // Found result if we matched whole substring.
7986     cmpl(tmp, stride);
7987     jccb(Assembler::lessEqual, RET_FOUND);
7988 
7989     // Repeat search for small substring (<= 8 chars)
7990     // from new point 'str1' without reloading substring.
7991     cmpl(cnt2, stride);
7992     // Have to check that we don't read beyond string.
7993     jccb(Assembler::lessEqual, ADJUST_STR);
7994 
7995     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7996     // Compare the rest of substring (> 8 chars).
7997     movptr(str1, result);
7998 
7999     cmpl(tmp, cnt2);
8000     // First 8 chars are already matched.
8001     jccb(Assembler::equal, CHECK_NEXT);
8002 
8003     bind(SCAN_SUBSTR);
8004     pcmpestri(vec, Address(str1, 0), mode);
8005     // Need to reload strings pointers if not matched whole vector
8006     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
8007 
8008     bind(CHECK_NEXT);
8009     subl(cnt2, stride);
8010     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
8011     addptr(str1, 16);
8012     if (ae == StrIntrinsicNode::UL) {
8013       addptr(str2, 8);
8014     } else {
8015       addptr(str2, 16);
8016     }
8017     subl(cnt1, stride);
8018     cmpl(cnt2, stride); // Do not read beyond substring
8019     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
8020     // Back-up strings to avoid reading beyond substring.
8021 
8022     if (ae == StrIntrinsicNode::UL) {
8023       lea(str2, Address(str2, cnt2, scale2, -8));
8024       lea(str1, Address(str1, cnt2, scale1, -16));
8025     } else {
8026       lea(str2, Address(str2, cnt2, scale2, -16));
8027       lea(str1, Address(str1, cnt2, scale1, -16));
8028     }
8029     subl(cnt1, cnt2);
8030     movl(cnt2, stride);
8031     addl(cnt1, stride);
8032     bind(CONT_SCAN_SUBSTR);
8033     if (ae == StrIntrinsicNode::UL) {
8034       pmovzxbw(vec, Address(str2, 0));
8035     } else {
8036       movdqu(vec, Address(str2, 0));
8037     }
8038     jmp(SCAN_SUBSTR);
8039 
8040     bind(RET_FOUND_LONG);
8041     movptr(str1, Address(rsp, wordSize));
8042   } // non constant
8043 
8044   bind(RET_FOUND);
8045   // Compute substr offset
8046   subptr(result, str1);
8047   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
8048     shrl(result, 1); // index
8049   }
8050   bind(CLEANUP);
8051   pop(rsp); // restore SP
8052 
8053 } // string_indexof
8054 
8055 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
8056                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
8057   ShortBranchVerifier sbv(this);
8058   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
8059 
8060   int stride = 8;
8061 
8062   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
8063         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
8064         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
8065         FOUND_SEQ_CHAR, DONE_LABEL;
8066 
8067   movptr(result, str1);
8068   if (UseAVX >= 2) {
8069     cmpl(cnt1, stride);
8070     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8071     cmpl(cnt1, 2*stride);
8072     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
8073     movdl(vec1, ch);
8074     vpbroadcastw(vec1, vec1);
8075     vpxor(vec2, vec2);
8076     movl(tmp, cnt1);
8077     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
8078     andl(cnt1,0x0000000F);  //tail count (in chars)
8079 
8080     bind(SCAN_TO_16_CHAR_LOOP);
8081     vmovdqu(vec3, Address(result, 0));
8082     vpcmpeqw(vec3, vec3, vec1, 1);
8083     vptest(vec2, vec3);
8084     jcc(Assembler::carryClear, FOUND_CHAR);
8085     addptr(result, 32);
8086     subl(tmp, 2*stride);
8087     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
8088     jmp(SCAN_TO_8_CHAR);
8089     bind(SCAN_TO_8_CHAR_INIT);
8090     movdl(vec1, ch);
8091     pshuflw(vec1, vec1, 0x00);
8092     pshufd(vec1, vec1, 0);
8093     pxor(vec2, vec2);
8094   }
8095   bind(SCAN_TO_8_CHAR);
8096   cmpl(cnt1, stride);
8097   if (UseAVX >= 2) {
8098     jcc(Assembler::less, SCAN_TO_CHAR);
8099   } else {
8100     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8101     movdl(vec1, ch);
8102     pshuflw(vec1, vec1, 0x00);
8103     pshufd(vec1, vec1, 0);
8104     pxor(vec2, vec2);
8105   }
8106   movl(tmp, cnt1);
8107   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
8108   andl(cnt1,0x00000007);  //tail count (in chars)
8109 
8110   bind(SCAN_TO_8_CHAR_LOOP);
8111   movdqu(vec3, Address(result, 0));
8112   pcmpeqw(vec3, vec1);
8113   ptest(vec2, vec3);
8114   jcc(Assembler::carryClear, FOUND_CHAR);
8115   addptr(result, 16);
8116   subl(tmp, stride);
8117   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
8118   bind(SCAN_TO_CHAR);
8119   testl(cnt1, cnt1);
8120   jcc(Assembler::zero, RET_NOT_FOUND);
8121   bind(SCAN_TO_CHAR_LOOP);
8122   load_unsigned_short(tmp, Address(result, 0));
8123   cmpl(ch, tmp);
8124   jccb(Assembler::equal, FOUND_SEQ_CHAR);
8125   addptr(result, 2);
8126   subl(cnt1, 1);
8127   jccb(Assembler::zero, RET_NOT_FOUND);
8128   jmp(SCAN_TO_CHAR_LOOP);
8129 
8130   bind(RET_NOT_FOUND);
8131   movl(result, -1);
8132   jmpb(DONE_LABEL);
8133 
8134   bind(FOUND_CHAR);
8135   if (UseAVX >= 2) {
8136     vpmovmskb(tmp, vec3);
8137   } else {
8138     pmovmskb(tmp, vec3);
8139   }
8140   bsfl(ch, tmp);
8141   addl(result, ch);
8142 
8143   bind(FOUND_SEQ_CHAR);
8144   subptr(result, str1);
8145   shrl(result, 1);
8146 
8147   bind(DONE_LABEL);
8148 } // string_indexof_char
8149 
8150 // helper function for string_compare
8151 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
8152                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
8153                                         Address::ScaleFactor scale2, Register index, int ae) {
8154   if (ae == StrIntrinsicNode::LL) {
8155     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
8156     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
8157   } else if (ae == StrIntrinsicNode::UU) {
8158     load_unsigned_short(elem1, Address(str1, index, scale, 0));
8159     load_unsigned_short(elem2, Address(str2, index, scale, 0));
8160   } else {
8161     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
8162     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
8163   }
8164 }
8165 
8166 // Compare strings, used for char[] and byte[].
8167 void MacroAssembler::string_compare(Register str1, Register str2,
8168                                     Register cnt1, Register cnt2, Register result,
8169                                     XMMRegister vec1, int ae) {
8170   ShortBranchVerifier sbv(this);
8171   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
8172   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
8173   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8174   int stride2x2 = 0x40;
8175   Address::ScaleFactor scale = Address::no_scale;
8176   Address::ScaleFactor scale1 = Address::no_scale;
8177   Address::ScaleFactor scale2 = Address::no_scale;
8178 
8179   if (ae != StrIntrinsicNode::LL) {
8180     stride2x2 = 0x20;
8181   }
8182 
8183   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8184     shrl(cnt2, 1);
8185   }
8186   // Compute the minimum of the string lengths and the
8187   // difference of the string lengths (stack).
8188   // Do the conditional move stuff
8189   movl(result, cnt1);
8190   subl(cnt1, cnt2);
8191   push(cnt1);
8192   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
8193 
8194   // Is the minimum length zero?
8195   testl(cnt2, cnt2);
8196   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8197   if (ae == StrIntrinsicNode::LL) {
8198     // Load first bytes
8199     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
8200     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
8201   } else if (ae == StrIntrinsicNode::UU) {
8202     // Load first characters
8203     load_unsigned_short(result, Address(str1, 0));
8204     load_unsigned_short(cnt1, Address(str2, 0));
8205   } else {
8206     load_unsigned_byte(result, Address(str1, 0));
8207     load_unsigned_short(cnt1, Address(str2, 0));
8208   }
8209   subl(result, cnt1);
8210   jcc(Assembler::notZero,  POP_LABEL);
8211 
8212   if (ae == StrIntrinsicNode::UU) {
8213     // Divide length by 2 to get number of chars
8214     shrl(cnt2, 1);
8215   }
8216   cmpl(cnt2, 1);
8217   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8218 
8219   // Check if the strings start at the same location and setup scale and stride
8220   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8221     cmpptr(str1, str2);
8222     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8223     if (ae == StrIntrinsicNode::LL) {
8224       scale = Address::times_1;
8225       stride = 16;
8226     } else {
8227       scale = Address::times_2;
8228       stride = 8;
8229     }
8230   } else {
8231     scale1 = Address::times_1;
8232     scale2 = Address::times_2;
8233     // scale not used
8234     stride = 8;
8235   }
8236 
8237   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8238     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8239     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8240     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
8241     Label COMPARE_TAIL_LONG;
8242     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
8243 
8244     int pcmpmask = 0x19;
8245     if (ae == StrIntrinsicNode::LL) {
8246       pcmpmask &= ~0x01;
8247     }
8248 
8249     // Setup to compare 16-chars (32-bytes) vectors,
8250     // start from first character again because it has aligned address.
8251     if (ae == StrIntrinsicNode::LL) {
8252       stride2 = 32;
8253     } else {
8254       stride2 = 16;
8255     }
8256     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8257       adr_stride = stride << scale;
8258     } else {
8259       adr_stride1 = 8;  //stride << scale1;
8260       adr_stride2 = 16; //stride << scale2;
8261     }
8262 
8263     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8264     // rax and rdx are used by pcmpestri as elements counters
8265     movl(result, cnt2);
8266     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8267     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8268 
8269     // fast path : compare first 2 8-char vectors.
8270     bind(COMPARE_16_CHARS);
8271     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8272       movdqu(vec1, Address(str1, 0));
8273     } else {
8274       pmovzxbw(vec1, Address(str1, 0));
8275     }
8276     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8277     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8278 
8279     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8280       movdqu(vec1, Address(str1, adr_stride));
8281       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8282     } else {
8283       pmovzxbw(vec1, Address(str1, adr_stride1));
8284       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8285     }
8286     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8287     addl(cnt1, stride);
8288 
8289     // Compare the characters at index in cnt1
8290     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8291     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8292     subl(result, cnt2);
8293     jmp(POP_LABEL);
8294 
8295     // Setup the registers to start vector comparison loop
8296     bind(COMPARE_WIDE_VECTORS);
8297     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8298       lea(str1, Address(str1, result, scale));
8299       lea(str2, Address(str2, result, scale));
8300     } else {
8301       lea(str1, Address(str1, result, scale1));
8302       lea(str2, Address(str2, result, scale2));
8303     }
8304     subl(result, stride2);
8305     subl(cnt2, stride2);
8306     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8307     negptr(result);
8308 
8309     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8310     bind(COMPARE_WIDE_VECTORS_LOOP);
8311 
8312 #ifdef _LP64
8313     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8314       cmpl(cnt2, stride2x2);
8315       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8316       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8317       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8318 
8319       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8320       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8321         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8322         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8323       } else {
8324         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8325         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8326       }
8327       kortestql(k7, k7);
8328       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8329       addptr(result, stride2x2);  // update since we already compared at this addr
8330       subl(cnt2, stride2x2);      // and sub the size too
8331       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8332 
8333       vpxor(vec1, vec1);
8334       jmpb(COMPARE_WIDE_TAIL);
8335     }//if (VM_Version::supports_avx512vlbw())
8336 #endif // _LP64
8337 
8338 
8339     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8340     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8341       vmovdqu(vec1, Address(str1, result, scale));
8342       vpxor(vec1, Address(str2, result, scale));
8343     } else {
8344       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8345       vpxor(vec1, Address(str2, result, scale2));
8346     }
8347     vptest(vec1, vec1);
8348     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8349     addptr(result, stride2);
8350     subl(cnt2, stride2);
8351     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8352     // clean upper bits of YMM registers
8353     vpxor(vec1, vec1);
8354 
8355     // compare wide vectors tail
8356     bind(COMPARE_WIDE_TAIL);
8357     testptr(result, result);
8358     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8359 
8360     movl(result, stride2);
8361     movl(cnt2, result);
8362     negptr(result);
8363     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8364 
8365     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8366     bind(VECTOR_NOT_EQUAL);
8367     // clean upper bits of YMM registers
8368     vpxor(vec1, vec1);
8369     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8370       lea(str1, Address(str1, result, scale));
8371       lea(str2, Address(str2, result, scale));
8372     } else {
8373       lea(str1, Address(str1, result, scale1));
8374       lea(str2, Address(str2, result, scale2));
8375     }
8376     jmp(COMPARE_16_CHARS);
8377 
8378     // Compare tail chars, length between 1 to 15 chars
8379     bind(COMPARE_TAIL_LONG);
8380     movl(cnt2, result);
8381     cmpl(cnt2, stride);
8382     jcc(Assembler::less, COMPARE_SMALL_STR);
8383 
8384     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8385       movdqu(vec1, Address(str1, 0));
8386     } else {
8387       pmovzxbw(vec1, Address(str1, 0));
8388     }
8389     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8390     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8391     subptr(cnt2, stride);
8392     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8393     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8394       lea(str1, Address(str1, result, scale));
8395       lea(str2, Address(str2, result, scale));
8396     } else {
8397       lea(str1, Address(str1, result, scale1));
8398       lea(str2, Address(str2, result, scale2));
8399     }
8400     negptr(cnt2);
8401     jmpb(WHILE_HEAD_LABEL);
8402 
8403     bind(COMPARE_SMALL_STR);
8404   } else if (UseSSE42Intrinsics) {
8405     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8406     int pcmpmask = 0x19;
8407     // Setup to compare 8-char (16-byte) vectors,
8408     // start from first character again because it has aligned address.
8409     movl(result, cnt2);
8410     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8411     if (ae == StrIntrinsicNode::LL) {
8412       pcmpmask &= ~0x01;
8413     }
8414     jcc(Assembler::zero, COMPARE_TAIL);
8415     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8416       lea(str1, Address(str1, result, scale));
8417       lea(str2, Address(str2, result, scale));
8418     } else {
8419       lea(str1, Address(str1, result, scale1));
8420       lea(str2, Address(str2, result, scale2));
8421     }
8422     negptr(result);
8423 
8424     // pcmpestri
8425     //   inputs:
8426     //     vec1- substring
8427     //     rax - negative string length (elements count)
8428     //     mem - scanned string
8429     //     rdx - string length (elements count)
8430     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8431     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8432     //   outputs:
8433     //     rcx - first mismatched element index
8434     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8435 
8436     bind(COMPARE_WIDE_VECTORS);
8437     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8438       movdqu(vec1, Address(str1, result, scale));
8439       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8440     } else {
8441       pmovzxbw(vec1, Address(str1, result, scale1));
8442       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8443     }
8444     // After pcmpestri cnt1(rcx) contains mismatched element index
8445 
8446     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8447     addptr(result, stride);
8448     subptr(cnt2, stride);
8449     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8450 
8451     // compare wide vectors tail
8452     testptr(result, result);
8453     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8454 
8455     movl(cnt2, stride);
8456     movl(result, stride);
8457     negptr(result);
8458     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8459       movdqu(vec1, Address(str1, result, scale));
8460       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8461     } else {
8462       pmovzxbw(vec1, Address(str1, result, scale1));
8463       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8464     }
8465     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8466 
8467     // Mismatched characters in the vectors
8468     bind(VECTOR_NOT_EQUAL);
8469     addptr(cnt1, result);
8470     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8471     subl(result, cnt2);
8472     jmpb(POP_LABEL);
8473 
8474     bind(COMPARE_TAIL); // limit is zero
8475     movl(cnt2, result);
8476     // Fallthru to tail compare
8477   }
8478   // Shift str2 and str1 to the end of the arrays, negate min
8479   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8480     lea(str1, Address(str1, cnt2, scale));
8481     lea(str2, Address(str2, cnt2, scale));
8482   } else {
8483     lea(str1, Address(str1, cnt2, scale1));
8484     lea(str2, Address(str2, cnt2, scale2));
8485   }
8486   decrementl(cnt2);  // first character was compared already
8487   negptr(cnt2);
8488 
8489   // Compare the rest of the elements
8490   bind(WHILE_HEAD_LABEL);
8491   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8492   subl(result, cnt1);
8493   jccb(Assembler::notZero, POP_LABEL);
8494   increment(cnt2);
8495   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8496 
8497   // Strings are equal up to min length.  Return the length difference.
8498   bind(LENGTH_DIFF_LABEL);
8499   pop(result);
8500   if (ae == StrIntrinsicNode::UU) {
8501     // Divide diff by 2 to get number of chars
8502     sarl(result, 1);
8503   }
8504   jmpb(DONE_LABEL);
8505 
8506 #ifdef _LP64
8507   if (VM_Version::supports_avx512vlbw()) {
8508 
8509     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8510 
8511     kmovql(cnt1, k7);
8512     notq(cnt1);
8513     bsfq(cnt2, cnt1);
8514     if (ae != StrIntrinsicNode::LL) {
8515       // Divide diff by 2 to get number of chars
8516       sarl(cnt2, 1);
8517     }
8518     addq(result, cnt2);
8519     if (ae == StrIntrinsicNode::LL) {
8520       load_unsigned_byte(cnt1, Address(str2, result));
8521       load_unsigned_byte(result, Address(str1, result));
8522     } else if (ae == StrIntrinsicNode::UU) {
8523       load_unsigned_short(cnt1, Address(str2, result, scale));
8524       load_unsigned_short(result, Address(str1, result, scale));
8525     } else {
8526       load_unsigned_short(cnt1, Address(str2, result, scale2));
8527       load_unsigned_byte(result, Address(str1, result, scale1));
8528     }
8529     subl(result, cnt1);
8530     jmpb(POP_LABEL);
8531   }//if (VM_Version::supports_avx512vlbw())
8532 #endif // _LP64
8533 
8534   // Discard the stored length difference
8535   bind(POP_LABEL);
8536   pop(cnt1);
8537 
8538   // That's it
8539   bind(DONE_LABEL);
8540   if(ae == StrIntrinsicNode::UL) {
8541     negl(result);
8542   }
8543 
8544 }
8545 
8546 // Search for Non-ASCII character (Negative byte value) in a byte array,
8547 // return true if it has any and false otherwise.
8548 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8549 //   @HotSpotIntrinsicCandidate
8550 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8551 //     for (int i = off; i < off + len; i++) {
8552 //       if (ba[i] < 0) {
8553 //         return true;
8554 //       }
8555 //     }
8556 //     return false;
8557 //   }
8558 void MacroAssembler::has_negatives(Register ary1, Register len,
8559   Register result, Register tmp1,
8560   XMMRegister vec1, XMMRegister vec2) {
8561   // rsi: byte array
8562   // rcx: len
8563   // rax: result
8564   ShortBranchVerifier sbv(this);
8565   assert_different_registers(ary1, len, result, tmp1);
8566   assert_different_registers(vec1, vec2);
8567   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8568 
8569   // len == 0
8570   testl(len, len);
8571   jcc(Assembler::zero, FALSE_LABEL);
8572 
8573   if ((UseAVX > 2) && // AVX512
8574     VM_Version::supports_avx512vlbw() &&
8575     VM_Version::supports_bmi2()) {
8576 
8577     set_vector_masking();  // opening of the stub context for programming mask registers
8578 
8579     Label test_64_loop, test_tail;
8580     Register tmp3_aliased = len;
8581 
8582     movl(tmp1, len);
8583     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8584 
8585     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8586     andl(len, ~(64 - 1));    // vector count (in chars)
8587     jccb(Assembler::zero, test_tail);
8588 
8589     lea(ary1, Address(ary1, len, Address::times_1));
8590     negptr(len);
8591 
8592     bind(test_64_loop);
8593     // Check whether our 64 elements of size byte contain negatives
8594     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8595     kortestql(k2, k2);
8596     jcc(Assembler::notZero, TRUE_LABEL);
8597 
8598     addptr(len, 64);
8599     jccb(Assembler::notZero, test_64_loop);
8600 
8601 
8602     bind(test_tail);
8603     // bail out when there is nothing to be done
8604     testl(tmp1, -1);
8605     jcc(Assembler::zero, FALSE_LABEL);
8606 
8607     // Save k1
8608     kmovql(k3, k1);
8609 
8610     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8611 #ifdef _LP64
8612     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8613     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8614     notq(tmp3_aliased);
8615     kmovql(k1, tmp3_aliased);
8616 #else
8617     Label k_init;
8618     jmp(k_init);
8619 
8620     // We could not read 64-bits from a general purpose register thus we move
8621     // data required to compose 64 1's to the instruction stream
8622     // We emit 64 byte wide series of elements from 0..63 which later on would
8623     // be used as a compare targets with tail count contained in tmp1 register.
8624     // Result would be a k1 register having tmp1 consecutive number or 1
8625     // counting from least significant bit.
8626     address tmp = pc();
8627     emit_int64(0x0706050403020100);
8628     emit_int64(0x0F0E0D0C0B0A0908);
8629     emit_int64(0x1716151413121110);
8630     emit_int64(0x1F1E1D1C1B1A1918);
8631     emit_int64(0x2726252423222120);
8632     emit_int64(0x2F2E2D2C2B2A2928);
8633     emit_int64(0x3736353433323130);
8634     emit_int64(0x3F3E3D3C3B3A3938);
8635 
8636     bind(k_init);
8637     lea(len, InternalAddress(tmp));
8638     // create mask to test for negative byte inside a vector
8639     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8640     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8641 
8642 #endif
8643     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8644     ktestq(k2, k1);
8645     // Restore k1
8646     kmovql(k1, k3);
8647     jcc(Assembler::notZero, TRUE_LABEL);
8648 
8649     jmp(FALSE_LABEL);
8650 
8651     clear_vector_masking();   // closing of the stub context for programming mask registers
8652   } else {
8653     movl(result, len); // copy
8654 
8655     if (UseAVX == 2 && UseSSE >= 2) {
8656       // With AVX2, use 32-byte vector compare
8657       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8658 
8659       // Compare 32-byte vectors
8660       andl(result, 0x0000001f);  //   tail count (in bytes)
8661       andl(len, 0xffffffe0);   // vector count (in bytes)
8662       jccb(Assembler::zero, COMPARE_TAIL);
8663 
8664       lea(ary1, Address(ary1, len, Address::times_1));
8665       negptr(len);
8666 
8667       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8668       movdl(vec2, tmp1);
8669       vpbroadcastd(vec2, vec2);
8670 
8671       bind(COMPARE_WIDE_VECTORS);
8672       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8673       vptest(vec1, vec2);
8674       jccb(Assembler::notZero, TRUE_LABEL);
8675       addptr(len, 32);
8676       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8677 
8678       testl(result, result);
8679       jccb(Assembler::zero, FALSE_LABEL);
8680 
8681       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8682       vptest(vec1, vec2);
8683       jccb(Assembler::notZero, TRUE_LABEL);
8684       jmpb(FALSE_LABEL);
8685 
8686       bind(COMPARE_TAIL); // len is zero
8687       movl(len, result);
8688       // Fallthru to tail compare
8689     } else if (UseSSE42Intrinsics) {
8690       // With SSE4.2, use double quad vector compare
8691       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8692 
8693       // Compare 16-byte vectors
8694       andl(result, 0x0000000f);  //   tail count (in bytes)
8695       andl(len, 0xfffffff0);   // vector count (in bytes)
8696       jccb(Assembler::zero, COMPARE_TAIL);
8697 
8698       lea(ary1, Address(ary1, len, Address::times_1));
8699       negptr(len);
8700 
8701       movl(tmp1, 0x80808080);
8702       movdl(vec2, tmp1);
8703       pshufd(vec2, vec2, 0);
8704 
8705       bind(COMPARE_WIDE_VECTORS);
8706       movdqu(vec1, Address(ary1, len, Address::times_1));
8707       ptest(vec1, vec2);
8708       jccb(Assembler::notZero, TRUE_LABEL);
8709       addptr(len, 16);
8710       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8711 
8712       testl(result, result);
8713       jccb(Assembler::zero, FALSE_LABEL);
8714 
8715       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8716       ptest(vec1, vec2);
8717       jccb(Assembler::notZero, TRUE_LABEL);
8718       jmpb(FALSE_LABEL);
8719 
8720       bind(COMPARE_TAIL); // len is zero
8721       movl(len, result);
8722       // Fallthru to tail compare
8723     }
8724   }
8725   // Compare 4-byte vectors
8726   andl(len, 0xfffffffc); // vector count (in bytes)
8727   jccb(Assembler::zero, COMPARE_CHAR);
8728 
8729   lea(ary1, Address(ary1, len, Address::times_1));
8730   negptr(len);
8731 
8732   bind(COMPARE_VECTORS);
8733   movl(tmp1, Address(ary1, len, Address::times_1));
8734   andl(tmp1, 0x80808080);
8735   jccb(Assembler::notZero, TRUE_LABEL);
8736   addptr(len, 4);
8737   jcc(Assembler::notZero, COMPARE_VECTORS);
8738 
8739   // Compare trailing char (final 2 bytes), if any
8740   bind(COMPARE_CHAR);
8741   testl(result, 0x2);   // tail  char
8742   jccb(Assembler::zero, COMPARE_BYTE);
8743   load_unsigned_short(tmp1, Address(ary1, 0));
8744   andl(tmp1, 0x00008080);
8745   jccb(Assembler::notZero, TRUE_LABEL);
8746   subptr(result, 2);
8747   lea(ary1, Address(ary1, 2));
8748 
8749   bind(COMPARE_BYTE);
8750   testl(result, 0x1);   // tail  byte
8751   jccb(Assembler::zero, FALSE_LABEL);
8752   load_unsigned_byte(tmp1, Address(ary1, 0));
8753   andl(tmp1, 0x00000080);
8754   jccb(Assembler::notEqual, TRUE_LABEL);
8755   jmpb(FALSE_LABEL);
8756 
8757   bind(TRUE_LABEL);
8758   movl(result, 1);   // return true
8759   jmpb(DONE);
8760 
8761   bind(FALSE_LABEL);
8762   xorl(result, result); // return false
8763 
8764   // That's it
8765   bind(DONE);
8766   if (UseAVX >= 2 && UseSSE >= 2) {
8767     // clean upper bits of YMM registers
8768     vpxor(vec1, vec1);
8769     vpxor(vec2, vec2);
8770   }
8771 }
8772 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8773 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8774                                    Register limit, Register result, Register chr,
8775                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8776   ShortBranchVerifier sbv(this);
8777   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8778 
8779   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8780   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8781 
8782   if (is_array_equ) {
8783     // Check the input args
8784     cmpoops(ary1, ary2);
8785     jcc(Assembler::equal, TRUE_LABEL);
8786 
8787     // Need additional checks for arrays_equals.
8788     testptr(ary1, ary1);
8789     jcc(Assembler::zero, FALSE_LABEL);
8790     testptr(ary2, ary2);
8791     jcc(Assembler::zero, FALSE_LABEL);
8792 
8793     // Check the lengths
8794     movl(limit, Address(ary1, length_offset));
8795     cmpl(limit, Address(ary2, length_offset));
8796     jcc(Assembler::notEqual, FALSE_LABEL);
8797   }
8798 
8799   // count == 0
8800   testl(limit, limit);
8801   jcc(Assembler::zero, TRUE_LABEL);
8802 
8803   if (is_array_equ) {
8804     // Load array address
8805     lea(ary1, Address(ary1, base_offset));
8806     lea(ary2, Address(ary2, base_offset));
8807   }
8808 
8809   if (is_array_equ && is_char) {
8810     // arrays_equals when used for char[].
8811     shll(limit, 1);      // byte count != 0
8812   }
8813   movl(result, limit); // copy
8814 
8815   if (UseAVX >= 2) {
8816     // With AVX2, use 32-byte vector compare
8817     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8818 
8819     // Compare 32-byte vectors
8820     andl(result, 0x0000001f);  //   tail count (in bytes)
8821     andl(limit, 0xffffffe0);   // vector count (in bytes)
8822     jcc(Assembler::zero, COMPARE_TAIL);
8823 
8824     lea(ary1, Address(ary1, limit, Address::times_1));
8825     lea(ary2, Address(ary2, limit, Address::times_1));
8826     negptr(limit);
8827 
8828     bind(COMPARE_WIDE_VECTORS);
8829 
8830 #ifdef _LP64
8831     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8832       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8833 
8834       cmpl(limit, -64);
8835       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8836 
8837       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8838 
8839       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8840       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8841       kortestql(k7, k7);
8842       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8843       addptr(limit, 64);  // update since we already compared at this addr
8844       cmpl(limit, -64);
8845       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8846 
8847       // At this point we may still need to compare -limit+result bytes.
8848       // We could execute the next two instruction and just continue via non-wide path:
8849       //  cmpl(limit, 0);
8850       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8851       // But since we stopped at the points ary{1,2}+limit which are
8852       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8853       // (|limit| <= 32 and result < 32),
8854       // we may just compare the last 64 bytes.
8855       //
8856       addptr(result, -64);   // it is safe, bc we just came from this area
8857       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8858       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8859       kortestql(k7, k7);
8860       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8861 
8862       jmp(TRUE_LABEL);
8863 
8864       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8865 
8866     }//if (VM_Version::supports_avx512vlbw())
8867 #endif //_LP64
8868 
8869     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8870     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8871     vpxor(vec1, vec2);
8872 
8873     vptest(vec1, vec1);
8874     jcc(Assembler::notZero, FALSE_LABEL);
8875     addptr(limit, 32);
8876     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8877 
8878     testl(result, result);
8879     jcc(Assembler::zero, TRUE_LABEL);
8880 
8881     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8882     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8883     vpxor(vec1, vec2);
8884 
8885     vptest(vec1, vec1);
8886     jccb(Assembler::notZero, FALSE_LABEL);
8887     jmpb(TRUE_LABEL);
8888 
8889     bind(COMPARE_TAIL); // limit is zero
8890     movl(limit, result);
8891     // Fallthru to tail compare
8892   } else if (UseSSE42Intrinsics) {
8893     // With SSE4.2, use double quad vector compare
8894     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8895 
8896     // Compare 16-byte vectors
8897     andl(result, 0x0000000f);  //   tail count (in bytes)
8898     andl(limit, 0xfffffff0);   // vector count (in bytes)
8899     jcc(Assembler::zero, COMPARE_TAIL);
8900 
8901     lea(ary1, Address(ary1, limit, Address::times_1));
8902     lea(ary2, Address(ary2, limit, Address::times_1));
8903     negptr(limit);
8904 
8905     bind(COMPARE_WIDE_VECTORS);
8906     movdqu(vec1, Address(ary1, limit, Address::times_1));
8907     movdqu(vec2, Address(ary2, limit, Address::times_1));
8908     pxor(vec1, vec2);
8909 
8910     ptest(vec1, vec1);
8911     jcc(Assembler::notZero, FALSE_LABEL);
8912     addptr(limit, 16);
8913     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8914 
8915     testl(result, result);
8916     jcc(Assembler::zero, TRUE_LABEL);
8917 
8918     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8919     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8920     pxor(vec1, vec2);
8921 
8922     ptest(vec1, vec1);
8923     jccb(Assembler::notZero, FALSE_LABEL);
8924     jmpb(TRUE_LABEL);
8925 
8926     bind(COMPARE_TAIL); // limit is zero
8927     movl(limit, result);
8928     // Fallthru to tail compare
8929   }
8930 
8931   // Compare 4-byte vectors
8932   andl(limit, 0xfffffffc); // vector count (in bytes)
8933   jccb(Assembler::zero, COMPARE_CHAR);
8934 
8935   lea(ary1, Address(ary1, limit, Address::times_1));
8936   lea(ary2, Address(ary2, limit, Address::times_1));
8937   negptr(limit);
8938 
8939   bind(COMPARE_VECTORS);
8940   movl(chr, Address(ary1, limit, Address::times_1));
8941   cmpl(chr, Address(ary2, limit, Address::times_1));
8942   jccb(Assembler::notEqual, FALSE_LABEL);
8943   addptr(limit, 4);
8944   jcc(Assembler::notZero, COMPARE_VECTORS);
8945 
8946   // Compare trailing char (final 2 bytes), if any
8947   bind(COMPARE_CHAR);
8948   testl(result, 0x2);   // tail  char
8949   jccb(Assembler::zero, COMPARE_BYTE);
8950   load_unsigned_short(chr, Address(ary1, 0));
8951   load_unsigned_short(limit, Address(ary2, 0));
8952   cmpl(chr, limit);
8953   jccb(Assembler::notEqual, FALSE_LABEL);
8954 
8955   if (is_array_equ && is_char) {
8956     bind(COMPARE_BYTE);
8957   } else {
8958     lea(ary1, Address(ary1, 2));
8959     lea(ary2, Address(ary2, 2));
8960 
8961     bind(COMPARE_BYTE);
8962     testl(result, 0x1);   // tail  byte
8963     jccb(Assembler::zero, TRUE_LABEL);
8964     load_unsigned_byte(chr, Address(ary1, 0));
8965     load_unsigned_byte(limit, Address(ary2, 0));
8966     cmpl(chr, limit);
8967     jccb(Assembler::notEqual, FALSE_LABEL);
8968   }
8969   bind(TRUE_LABEL);
8970   movl(result, 1);   // return true
8971   jmpb(DONE);
8972 
8973   bind(FALSE_LABEL);
8974   xorl(result, result); // return false
8975 
8976   // That's it
8977   bind(DONE);
8978   if (UseAVX >= 2) {
8979     // clean upper bits of YMM registers
8980     vpxor(vec1, vec1);
8981     vpxor(vec2, vec2);
8982   }
8983 }
8984 
8985 #endif
8986 
8987 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8988                                    Register to, Register value, Register count,
8989                                    Register rtmp, XMMRegister xtmp) {
8990   ShortBranchVerifier sbv(this);
8991   assert_different_registers(to, value, count, rtmp);
8992   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8993   Label L_fill_2_bytes, L_fill_4_bytes;
8994 
8995   int shift = -1;
8996   switch (t) {
8997     case T_BYTE:
8998       shift = 2;
8999       break;
9000     case T_SHORT:
9001       shift = 1;
9002       break;
9003     case T_INT:
9004       shift = 0;
9005       break;
9006     default: ShouldNotReachHere();
9007   }
9008 
9009   if (t == T_BYTE) {
9010     andl(value, 0xff);
9011     movl(rtmp, value);
9012     shll(rtmp, 8);
9013     orl(value, rtmp);
9014   }
9015   if (t == T_SHORT) {
9016     andl(value, 0xffff);
9017   }
9018   if (t == T_BYTE || t == T_SHORT) {
9019     movl(rtmp, value);
9020     shll(rtmp, 16);
9021     orl(value, rtmp);
9022   }
9023 
9024   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
9025   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
9026   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
9027     // align source address at 4 bytes address boundary
9028     if (t == T_BYTE) {
9029       // One byte misalignment happens only for byte arrays
9030       testptr(to, 1);
9031       jccb(Assembler::zero, L_skip_align1);
9032       movb(Address(to, 0), value);
9033       increment(to);
9034       decrement(count);
9035       BIND(L_skip_align1);
9036     }
9037     // Two bytes misalignment happens only for byte and short (char) arrays
9038     testptr(to, 2);
9039     jccb(Assembler::zero, L_skip_align2);
9040     movw(Address(to, 0), value);
9041     addptr(to, 2);
9042     subl(count, 1<<(shift-1));
9043     BIND(L_skip_align2);
9044   }
9045   if (UseSSE < 2) {
9046     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9047     // Fill 32-byte chunks
9048     subl(count, 8 << shift);
9049     jcc(Assembler::less, L_check_fill_8_bytes);
9050     align(16);
9051 
9052     BIND(L_fill_32_bytes_loop);
9053 
9054     for (int i = 0; i < 32; i += 4) {
9055       movl(Address(to, i), value);
9056     }
9057 
9058     addptr(to, 32);
9059     subl(count, 8 << shift);
9060     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9061     BIND(L_check_fill_8_bytes);
9062     addl(count, 8 << shift);
9063     jccb(Assembler::zero, L_exit);
9064     jmpb(L_fill_8_bytes);
9065 
9066     //
9067     // length is too short, just fill qwords
9068     //
9069     BIND(L_fill_8_bytes_loop);
9070     movl(Address(to, 0), value);
9071     movl(Address(to, 4), value);
9072     addptr(to, 8);
9073     BIND(L_fill_8_bytes);
9074     subl(count, 1 << (shift + 1));
9075     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9076     // fall through to fill 4 bytes
9077   } else {
9078     Label L_fill_32_bytes;
9079     if (!UseUnalignedLoadStores) {
9080       // align to 8 bytes, we know we are 4 byte aligned to start
9081       testptr(to, 4);
9082       jccb(Assembler::zero, L_fill_32_bytes);
9083       movl(Address(to, 0), value);
9084       addptr(to, 4);
9085       subl(count, 1<<shift);
9086     }
9087     BIND(L_fill_32_bytes);
9088     {
9089       assert( UseSSE >= 2, "supported cpu only" );
9090       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9091       if (UseAVX > 2) {
9092         movl(rtmp, 0xffff);
9093         kmovwl(k1, rtmp);
9094       }
9095       movdl(xtmp, value);
9096       if (UseAVX > 2 && UseUnalignedLoadStores) {
9097         // Fill 64-byte chunks
9098         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9099         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
9100 
9101         subl(count, 16 << shift);
9102         jcc(Assembler::less, L_check_fill_32_bytes);
9103         align(16);
9104 
9105         BIND(L_fill_64_bytes_loop);
9106         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
9107         addptr(to, 64);
9108         subl(count, 16 << shift);
9109         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9110 
9111         BIND(L_check_fill_32_bytes);
9112         addl(count, 8 << shift);
9113         jccb(Assembler::less, L_check_fill_8_bytes);
9114         vmovdqu(Address(to, 0), xtmp);
9115         addptr(to, 32);
9116         subl(count, 8 << shift);
9117 
9118         BIND(L_check_fill_8_bytes);
9119       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
9120         // Fill 64-byte chunks
9121         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9122         vpbroadcastd(xtmp, xtmp);
9123 
9124         subl(count, 16 << shift);
9125         jcc(Assembler::less, L_check_fill_32_bytes);
9126         align(16);
9127 
9128         BIND(L_fill_64_bytes_loop);
9129         vmovdqu(Address(to, 0), xtmp);
9130         vmovdqu(Address(to, 32), xtmp);
9131         addptr(to, 64);
9132         subl(count, 16 << shift);
9133         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9134 
9135         BIND(L_check_fill_32_bytes);
9136         addl(count, 8 << shift);
9137         jccb(Assembler::less, L_check_fill_8_bytes);
9138         vmovdqu(Address(to, 0), xtmp);
9139         addptr(to, 32);
9140         subl(count, 8 << shift);
9141 
9142         BIND(L_check_fill_8_bytes);
9143         // clean upper bits of YMM registers
9144         movdl(xtmp, value);
9145         pshufd(xtmp, xtmp, 0);
9146       } else {
9147         // Fill 32-byte chunks
9148         pshufd(xtmp, xtmp, 0);
9149 
9150         subl(count, 8 << shift);
9151         jcc(Assembler::less, L_check_fill_8_bytes);
9152         align(16);
9153 
9154         BIND(L_fill_32_bytes_loop);
9155 
9156         if (UseUnalignedLoadStores) {
9157           movdqu(Address(to, 0), xtmp);
9158           movdqu(Address(to, 16), xtmp);
9159         } else {
9160           movq(Address(to, 0), xtmp);
9161           movq(Address(to, 8), xtmp);
9162           movq(Address(to, 16), xtmp);
9163           movq(Address(to, 24), xtmp);
9164         }
9165 
9166         addptr(to, 32);
9167         subl(count, 8 << shift);
9168         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9169 
9170         BIND(L_check_fill_8_bytes);
9171       }
9172       addl(count, 8 << shift);
9173       jccb(Assembler::zero, L_exit);
9174       jmpb(L_fill_8_bytes);
9175 
9176       //
9177       // length is too short, just fill qwords
9178       //
9179       BIND(L_fill_8_bytes_loop);
9180       movq(Address(to, 0), xtmp);
9181       addptr(to, 8);
9182       BIND(L_fill_8_bytes);
9183       subl(count, 1 << (shift + 1));
9184       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9185     }
9186   }
9187   // fill trailing 4 bytes
9188   BIND(L_fill_4_bytes);
9189   testl(count, 1<<shift);
9190   jccb(Assembler::zero, L_fill_2_bytes);
9191   movl(Address(to, 0), value);
9192   if (t == T_BYTE || t == T_SHORT) {
9193     addptr(to, 4);
9194     BIND(L_fill_2_bytes);
9195     // fill trailing 2 bytes
9196     testl(count, 1<<(shift-1));
9197     jccb(Assembler::zero, L_fill_byte);
9198     movw(Address(to, 0), value);
9199     if (t == T_BYTE) {
9200       addptr(to, 2);
9201       BIND(L_fill_byte);
9202       // fill trailing byte
9203       testl(count, 1);
9204       jccb(Assembler::zero, L_exit);
9205       movb(Address(to, 0), value);
9206     } else {
9207       BIND(L_fill_byte);
9208     }
9209   } else {
9210     BIND(L_fill_2_bytes);
9211   }
9212   BIND(L_exit);
9213 }
9214 
9215 // encode char[] to byte[] in ISO_8859_1
9216    //@HotSpotIntrinsicCandidate
9217    //private static int implEncodeISOArray(byte[] sa, int sp,
9218    //byte[] da, int dp, int len) {
9219    //  int i = 0;
9220    //  for (; i < len; i++) {
9221    //    char c = StringUTF16.getChar(sa, sp++);
9222    //    if (c > '\u00FF')
9223    //      break;
9224    //    da[dp++] = (byte)c;
9225    //  }
9226    //  return i;
9227    //}
9228 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
9229   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9230   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9231   Register tmp5, Register result) {
9232 
9233   // rsi: src
9234   // rdi: dst
9235   // rdx: len
9236   // rcx: tmp5
9237   // rax: result
9238   ShortBranchVerifier sbv(this);
9239   assert_different_registers(src, dst, len, tmp5, result);
9240   Label L_done, L_copy_1_char, L_copy_1_char_exit;
9241 
9242   // set result
9243   xorl(result, result);
9244   // check for zero length
9245   testl(len, len);
9246   jcc(Assembler::zero, L_done);
9247 
9248   movl(result, len);
9249 
9250   // Setup pointers
9251   lea(src, Address(src, len, Address::times_2)); // char[]
9252   lea(dst, Address(dst, len, Address::times_1)); // byte[]
9253   negptr(len);
9254 
9255   if (UseSSE42Intrinsics || UseAVX >= 2) {
9256     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
9257     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
9258 
9259     if (UseAVX >= 2) {
9260       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
9261       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9262       movdl(tmp1Reg, tmp5);
9263       vpbroadcastd(tmp1Reg, tmp1Reg);
9264       jmp(L_chars_32_check);
9265 
9266       bind(L_copy_32_chars);
9267       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
9268       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
9269       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9270       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9271       jccb(Assembler::notZero, L_copy_32_chars_exit);
9272       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9273       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
9274       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
9275 
9276       bind(L_chars_32_check);
9277       addptr(len, 32);
9278       jcc(Assembler::lessEqual, L_copy_32_chars);
9279 
9280       bind(L_copy_32_chars_exit);
9281       subptr(len, 16);
9282       jccb(Assembler::greater, L_copy_16_chars_exit);
9283 
9284     } else if (UseSSE42Intrinsics) {
9285       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9286       movdl(tmp1Reg, tmp5);
9287       pshufd(tmp1Reg, tmp1Reg, 0);
9288       jmpb(L_chars_16_check);
9289     }
9290 
9291     bind(L_copy_16_chars);
9292     if (UseAVX >= 2) {
9293       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9294       vptest(tmp2Reg, tmp1Reg);
9295       jcc(Assembler::notZero, L_copy_16_chars_exit);
9296       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9297       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9298     } else {
9299       if (UseAVX > 0) {
9300         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9301         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9302         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9303       } else {
9304         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9305         por(tmp2Reg, tmp3Reg);
9306         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9307         por(tmp2Reg, tmp4Reg);
9308       }
9309       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9310       jccb(Assembler::notZero, L_copy_16_chars_exit);
9311       packuswb(tmp3Reg, tmp4Reg);
9312     }
9313     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9314 
9315     bind(L_chars_16_check);
9316     addptr(len, 16);
9317     jcc(Assembler::lessEqual, L_copy_16_chars);
9318 
9319     bind(L_copy_16_chars_exit);
9320     if (UseAVX >= 2) {
9321       // clean upper bits of YMM registers
9322       vpxor(tmp2Reg, tmp2Reg);
9323       vpxor(tmp3Reg, tmp3Reg);
9324       vpxor(tmp4Reg, tmp4Reg);
9325       movdl(tmp1Reg, tmp5);
9326       pshufd(tmp1Reg, tmp1Reg, 0);
9327     }
9328     subptr(len, 8);
9329     jccb(Assembler::greater, L_copy_8_chars_exit);
9330 
9331     bind(L_copy_8_chars);
9332     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9333     ptest(tmp3Reg, tmp1Reg);
9334     jccb(Assembler::notZero, L_copy_8_chars_exit);
9335     packuswb(tmp3Reg, tmp1Reg);
9336     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9337     addptr(len, 8);
9338     jccb(Assembler::lessEqual, L_copy_8_chars);
9339 
9340     bind(L_copy_8_chars_exit);
9341     subptr(len, 8);
9342     jccb(Assembler::zero, L_done);
9343   }
9344 
9345   bind(L_copy_1_char);
9346   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9347   testl(tmp5, 0xff00);      // check if Unicode char
9348   jccb(Assembler::notZero, L_copy_1_char_exit);
9349   movb(Address(dst, len, Address::times_1, 0), tmp5);
9350   addptr(len, 1);
9351   jccb(Assembler::less, L_copy_1_char);
9352 
9353   bind(L_copy_1_char_exit);
9354   addptr(result, len); // len is negative count of not processed elements
9355 
9356   bind(L_done);
9357 }
9358 
9359 #ifdef _LP64
9360 /**
9361  * Helper for multiply_to_len().
9362  */
9363 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9364   addq(dest_lo, src1);
9365   adcq(dest_hi, 0);
9366   addq(dest_lo, src2);
9367   adcq(dest_hi, 0);
9368 }
9369 
9370 /**
9371  * Multiply 64 bit by 64 bit first loop.
9372  */
9373 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9374                                            Register y, Register y_idx, Register z,
9375                                            Register carry, Register product,
9376                                            Register idx, Register kdx) {
9377   //
9378   //  jlong carry, x[], y[], z[];
9379   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9380   //    huge_128 product = y[idx] * x[xstart] + carry;
9381   //    z[kdx] = (jlong)product;
9382   //    carry  = (jlong)(product >>> 64);
9383   //  }
9384   //  z[xstart] = carry;
9385   //
9386 
9387   Label L_first_loop, L_first_loop_exit;
9388   Label L_one_x, L_one_y, L_multiply;
9389 
9390   decrementl(xstart);
9391   jcc(Assembler::negative, L_one_x);
9392 
9393   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9394   rorq(x_xstart, 32); // convert big-endian to little-endian
9395 
9396   bind(L_first_loop);
9397   decrementl(idx);
9398   jcc(Assembler::negative, L_first_loop_exit);
9399   decrementl(idx);
9400   jcc(Assembler::negative, L_one_y);
9401   movq(y_idx, Address(y, idx, Address::times_4,  0));
9402   rorq(y_idx, 32); // convert big-endian to little-endian
9403   bind(L_multiply);
9404   movq(product, x_xstart);
9405   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9406   addq(product, carry);
9407   adcq(rdx, 0);
9408   subl(kdx, 2);
9409   movl(Address(z, kdx, Address::times_4,  4), product);
9410   shrq(product, 32);
9411   movl(Address(z, kdx, Address::times_4,  0), product);
9412   movq(carry, rdx);
9413   jmp(L_first_loop);
9414 
9415   bind(L_one_y);
9416   movl(y_idx, Address(y,  0));
9417   jmp(L_multiply);
9418 
9419   bind(L_one_x);
9420   movl(x_xstart, Address(x,  0));
9421   jmp(L_first_loop);
9422 
9423   bind(L_first_loop_exit);
9424 }
9425 
9426 /**
9427  * Multiply 64 bit by 64 bit and add 128 bit.
9428  */
9429 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9430                                             Register yz_idx, Register idx,
9431                                             Register carry, Register product, int offset) {
9432   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9433   //     z[kdx] = (jlong)product;
9434 
9435   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9436   rorq(yz_idx, 32); // convert big-endian to little-endian
9437   movq(product, x_xstart);
9438   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9439   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9440   rorq(yz_idx, 32); // convert big-endian to little-endian
9441 
9442   add2_with_carry(rdx, product, carry, yz_idx);
9443 
9444   movl(Address(z, idx, Address::times_4,  offset+4), product);
9445   shrq(product, 32);
9446   movl(Address(z, idx, Address::times_4,  offset), product);
9447 
9448 }
9449 
9450 /**
9451  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9452  */
9453 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9454                                              Register yz_idx, Register idx, Register jdx,
9455                                              Register carry, Register product,
9456                                              Register carry2) {
9457   //   jlong carry, x[], y[], z[];
9458   //   int kdx = ystart+1;
9459   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9460   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9461   //     z[kdx+idx+1] = (jlong)product;
9462   //     jlong carry2  = (jlong)(product >>> 64);
9463   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9464   //     z[kdx+idx] = (jlong)product;
9465   //     carry  = (jlong)(product >>> 64);
9466   //   }
9467   //   idx += 2;
9468   //   if (idx > 0) {
9469   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9470   //     z[kdx+idx] = (jlong)product;
9471   //     carry  = (jlong)(product >>> 64);
9472   //   }
9473   //
9474 
9475   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9476 
9477   movl(jdx, idx);
9478   andl(jdx, 0xFFFFFFFC);
9479   shrl(jdx, 2);
9480 
9481   bind(L_third_loop);
9482   subl(jdx, 1);
9483   jcc(Assembler::negative, L_third_loop_exit);
9484   subl(idx, 4);
9485 
9486   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9487   movq(carry2, rdx);
9488 
9489   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9490   movq(carry, rdx);
9491   jmp(L_third_loop);
9492 
9493   bind (L_third_loop_exit);
9494 
9495   andl (idx, 0x3);
9496   jcc(Assembler::zero, L_post_third_loop_done);
9497 
9498   Label L_check_1;
9499   subl(idx, 2);
9500   jcc(Assembler::negative, L_check_1);
9501 
9502   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9503   movq(carry, rdx);
9504 
9505   bind (L_check_1);
9506   addl (idx, 0x2);
9507   andl (idx, 0x1);
9508   subl(idx, 1);
9509   jcc(Assembler::negative, L_post_third_loop_done);
9510 
9511   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9512   movq(product, x_xstart);
9513   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9514   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9515 
9516   add2_with_carry(rdx, product, yz_idx, carry);
9517 
9518   movl(Address(z, idx, Address::times_4,  0), product);
9519   shrq(product, 32);
9520 
9521   shlq(rdx, 32);
9522   orq(product, rdx);
9523   movq(carry, product);
9524 
9525   bind(L_post_third_loop_done);
9526 }
9527 
9528 /**
9529  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9530  *
9531  */
9532 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9533                                                   Register carry, Register carry2,
9534                                                   Register idx, Register jdx,
9535                                                   Register yz_idx1, Register yz_idx2,
9536                                                   Register tmp, Register tmp3, Register tmp4) {
9537   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9538 
9539   //   jlong carry, x[], y[], z[];
9540   //   int kdx = ystart+1;
9541   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9542   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9543   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9544   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9545   //     carry  = (jlong)(tmp4 >>> 64);
9546   //     z[kdx+idx+1] = (jlong)tmp3;
9547   //     z[kdx+idx] = (jlong)tmp4;
9548   //   }
9549   //   idx += 2;
9550   //   if (idx > 0) {
9551   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9552   //     z[kdx+idx] = (jlong)yz_idx1;
9553   //     carry  = (jlong)(yz_idx1 >>> 64);
9554   //   }
9555   //
9556 
9557   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9558 
9559   movl(jdx, idx);
9560   andl(jdx, 0xFFFFFFFC);
9561   shrl(jdx, 2);
9562 
9563   bind(L_third_loop);
9564   subl(jdx, 1);
9565   jcc(Assembler::negative, L_third_loop_exit);
9566   subl(idx, 4);
9567 
9568   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9569   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9570   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9571   rorxq(yz_idx2, yz_idx2, 32);
9572 
9573   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9574   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9575 
9576   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9577   rorxq(yz_idx1, yz_idx1, 32);
9578   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9579   rorxq(yz_idx2, yz_idx2, 32);
9580 
9581   if (VM_Version::supports_adx()) {
9582     adcxq(tmp3, carry);
9583     adoxq(tmp3, yz_idx1);
9584 
9585     adcxq(tmp4, tmp);
9586     adoxq(tmp4, yz_idx2);
9587 
9588     movl(carry, 0); // does not affect flags
9589     adcxq(carry2, carry);
9590     adoxq(carry2, carry);
9591   } else {
9592     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9593     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9594   }
9595   movq(carry, carry2);
9596 
9597   movl(Address(z, idx, Address::times_4, 12), tmp3);
9598   shrq(tmp3, 32);
9599   movl(Address(z, idx, Address::times_4,  8), tmp3);
9600 
9601   movl(Address(z, idx, Address::times_4,  4), tmp4);
9602   shrq(tmp4, 32);
9603   movl(Address(z, idx, Address::times_4,  0), tmp4);
9604 
9605   jmp(L_third_loop);
9606 
9607   bind (L_third_loop_exit);
9608 
9609   andl (idx, 0x3);
9610   jcc(Assembler::zero, L_post_third_loop_done);
9611 
9612   Label L_check_1;
9613   subl(idx, 2);
9614   jcc(Assembler::negative, L_check_1);
9615 
9616   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9617   rorxq(yz_idx1, yz_idx1, 32);
9618   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9619   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9620   rorxq(yz_idx2, yz_idx2, 32);
9621 
9622   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9623 
9624   movl(Address(z, idx, Address::times_4,  4), tmp3);
9625   shrq(tmp3, 32);
9626   movl(Address(z, idx, Address::times_4,  0), tmp3);
9627   movq(carry, tmp4);
9628 
9629   bind (L_check_1);
9630   addl (idx, 0x2);
9631   andl (idx, 0x1);
9632   subl(idx, 1);
9633   jcc(Assembler::negative, L_post_third_loop_done);
9634   movl(tmp4, Address(y, idx, Address::times_4,  0));
9635   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9636   movl(tmp4, Address(z, idx, Address::times_4,  0));
9637 
9638   add2_with_carry(carry2, tmp3, tmp4, carry);
9639 
9640   movl(Address(z, idx, Address::times_4,  0), tmp3);
9641   shrq(tmp3, 32);
9642 
9643   shlq(carry2, 32);
9644   orq(tmp3, carry2);
9645   movq(carry, tmp3);
9646 
9647   bind(L_post_third_loop_done);
9648 }
9649 
9650 /**
9651  * Code for BigInteger::multiplyToLen() instrinsic.
9652  *
9653  * rdi: x
9654  * rax: xlen
9655  * rsi: y
9656  * rcx: ylen
9657  * r8:  z
9658  * r11: zlen
9659  * r12: tmp1
9660  * r13: tmp2
9661  * r14: tmp3
9662  * r15: tmp4
9663  * rbx: tmp5
9664  *
9665  */
9666 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9667                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9668   ShortBranchVerifier sbv(this);
9669   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9670 
9671   push(tmp1);
9672   push(tmp2);
9673   push(tmp3);
9674   push(tmp4);
9675   push(tmp5);
9676 
9677   push(xlen);
9678   push(zlen);
9679 
9680   const Register idx = tmp1;
9681   const Register kdx = tmp2;
9682   const Register xstart = tmp3;
9683 
9684   const Register y_idx = tmp4;
9685   const Register carry = tmp5;
9686   const Register product  = xlen;
9687   const Register x_xstart = zlen;  // reuse register
9688 
9689   // First Loop.
9690   //
9691   //  final static long LONG_MASK = 0xffffffffL;
9692   //  int xstart = xlen - 1;
9693   //  int ystart = ylen - 1;
9694   //  long carry = 0;
9695   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9696   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9697   //    z[kdx] = (int)product;
9698   //    carry = product >>> 32;
9699   //  }
9700   //  z[xstart] = (int)carry;
9701   //
9702 
9703   movl(idx, ylen);      // idx = ylen;
9704   movl(kdx, zlen);      // kdx = xlen+ylen;
9705   xorq(carry, carry);   // carry = 0;
9706 
9707   Label L_done;
9708 
9709   movl(xstart, xlen);
9710   decrementl(xstart);
9711   jcc(Assembler::negative, L_done);
9712 
9713   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9714 
9715   Label L_second_loop;
9716   testl(kdx, kdx);
9717   jcc(Assembler::zero, L_second_loop);
9718 
9719   Label L_carry;
9720   subl(kdx, 1);
9721   jcc(Assembler::zero, L_carry);
9722 
9723   movl(Address(z, kdx, Address::times_4,  0), carry);
9724   shrq(carry, 32);
9725   subl(kdx, 1);
9726 
9727   bind(L_carry);
9728   movl(Address(z, kdx, Address::times_4,  0), carry);
9729 
9730   // Second and third (nested) loops.
9731   //
9732   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9733   //   carry = 0;
9734   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9735   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9736   //                    (z[k] & LONG_MASK) + carry;
9737   //     z[k] = (int)product;
9738   //     carry = product >>> 32;
9739   //   }
9740   //   z[i] = (int)carry;
9741   // }
9742   //
9743   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9744 
9745   const Register jdx = tmp1;
9746 
9747   bind(L_second_loop);
9748   xorl(carry, carry);    // carry = 0;
9749   movl(jdx, ylen);       // j = ystart+1
9750 
9751   subl(xstart, 1);       // i = xstart-1;
9752   jcc(Assembler::negative, L_done);
9753 
9754   push (z);
9755 
9756   Label L_last_x;
9757   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9758   subl(xstart, 1);       // i = xstart-1;
9759   jcc(Assembler::negative, L_last_x);
9760 
9761   if (UseBMI2Instructions) {
9762     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9763     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9764   } else {
9765     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9766     rorq(x_xstart, 32);  // convert big-endian to little-endian
9767   }
9768 
9769   Label L_third_loop_prologue;
9770   bind(L_third_loop_prologue);
9771 
9772   push (x);
9773   push (xstart);
9774   push (ylen);
9775 
9776 
9777   if (UseBMI2Instructions) {
9778     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9779   } else { // !UseBMI2Instructions
9780     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9781   }
9782 
9783   pop(ylen);
9784   pop(xlen);
9785   pop(x);
9786   pop(z);
9787 
9788   movl(tmp3, xlen);
9789   addl(tmp3, 1);
9790   movl(Address(z, tmp3, Address::times_4,  0), carry);
9791   subl(tmp3, 1);
9792   jccb(Assembler::negative, L_done);
9793 
9794   shrq(carry, 32);
9795   movl(Address(z, tmp3, Address::times_4,  0), carry);
9796   jmp(L_second_loop);
9797 
9798   // Next infrequent code is moved outside loops.
9799   bind(L_last_x);
9800   if (UseBMI2Instructions) {
9801     movl(rdx, Address(x,  0));
9802   } else {
9803     movl(x_xstart, Address(x,  0));
9804   }
9805   jmp(L_third_loop_prologue);
9806 
9807   bind(L_done);
9808 
9809   pop(zlen);
9810   pop(xlen);
9811 
9812   pop(tmp5);
9813   pop(tmp4);
9814   pop(tmp3);
9815   pop(tmp2);
9816   pop(tmp1);
9817 }
9818 
9819 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9820   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9821   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9822   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9823   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9824   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9825   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9826   Label SAME_TILL_END, DONE;
9827   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9828 
9829   //scale is in rcx in both Win64 and Unix
9830   ShortBranchVerifier sbv(this);
9831 
9832   shlq(length);
9833   xorq(result, result);
9834 
9835   if ((UseAVX > 2) &&
9836       VM_Version::supports_avx512vlbw()) {
9837     set_vector_masking();  // opening of the stub context for programming mask registers
9838     cmpq(length, 64);
9839     jcc(Assembler::less, VECTOR32_TAIL);
9840     movq(tmp1, length);
9841     andq(tmp1, 0x3F);      // tail count
9842     andq(length, ~(0x3F)); //vector count
9843 
9844     bind(VECTOR64_LOOP);
9845     // AVX512 code to compare 64 byte vectors.
9846     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9847     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9848     kortestql(k7, k7);
9849     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9850     addq(result, 64);
9851     subq(length, 64);
9852     jccb(Assembler::notZero, VECTOR64_LOOP);
9853 
9854     //bind(VECTOR64_TAIL);
9855     testq(tmp1, tmp1);
9856     jcc(Assembler::zero, SAME_TILL_END);
9857 
9858     bind(VECTOR64_TAIL);
9859     // AVX512 code to compare upto 63 byte vectors.
9860     // Save k1
9861     kmovql(k3, k1);
9862     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9863     shlxq(tmp2, tmp2, tmp1);
9864     notq(tmp2);
9865     kmovql(k1, tmp2);
9866 
9867     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9868     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9869 
9870     ktestql(k7, k1);
9871     // Restore k1
9872     kmovql(k1, k3);
9873     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9874 
9875     bind(VECTOR64_NOT_EQUAL);
9876     kmovql(tmp1, k7);
9877     notq(tmp1);
9878     tzcntq(tmp1, tmp1);
9879     addq(result, tmp1);
9880     shrq(result);
9881     jmp(DONE);
9882     bind(VECTOR32_TAIL);
9883     clear_vector_masking();   // closing of the stub context for programming mask registers
9884   }
9885 
9886   cmpq(length, 8);
9887   jcc(Assembler::equal, VECTOR8_LOOP);
9888   jcc(Assembler::less, VECTOR4_TAIL);
9889 
9890   if (UseAVX >= 2) {
9891 
9892     cmpq(length, 16);
9893     jcc(Assembler::equal, VECTOR16_LOOP);
9894     jcc(Assembler::less, VECTOR8_LOOP);
9895 
9896     cmpq(length, 32);
9897     jccb(Assembler::less, VECTOR16_TAIL);
9898 
9899     subq(length, 32);
9900     bind(VECTOR32_LOOP);
9901     vmovdqu(rymm0, Address(obja, result));
9902     vmovdqu(rymm1, Address(objb, result));
9903     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9904     vptest(rymm2, rymm2);
9905     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9906     addq(result, 32);
9907     subq(length, 32);
9908     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9909     addq(length, 32);
9910     jcc(Assembler::equal, SAME_TILL_END);
9911     //falling through if less than 32 bytes left //close the branch here.
9912 
9913     bind(VECTOR16_TAIL);
9914     cmpq(length, 16);
9915     jccb(Assembler::less, VECTOR8_TAIL);
9916     bind(VECTOR16_LOOP);
9917     movdqu(rymm0, Address(obja, result));
9918     movdqu(rymm1, Address(objb, result));
9919     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9920     ptest(rymm2, rymm2);
9921     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9922     addq(result, 16);
9923     subq(length, 16);
9924     jcc(Assembler::equal, SAME_TILL_END);
9925     //falling through if less than 16 bytes left
9926   } else {//regular intrinsics
9927 
9928     cmpq(length, 16);
9929     jccb(Assembler::less, VECTOR8_TAIL);
9930 
9931     subq(length, 16);
9932     bind(VECTOR16_LOOP);
9933     movdqu(rymm0, Address(obja, result));
9934     movdqu(rymm1, Address(objb, result));
9935     pxor(rymm0, rymm1);
9936     ptest(rymm0, rymm0);
9937     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9938     addq(result, 16);
9939     subq(length, 16);
9940     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9941     addq(length, 16);
9942     jcc(Assembler::equal, SAME_TILL_END);
9943     //falling through if less than 16 bytes left
9944   }
9945 
9946   bind(VECTOR8_TAIL);
9947   cmpq(length, 8);
9948   jccb(Assembler::less, VECTOR4_TAIL);
9949   bind(VECTOR8_LOOP);
9950   movq(tmp1, Address(obja, result));
9951   movq(tmp2, Address(objb, result));
9952   xorq(tmp1, tmp2);
9953   testq(tmp1, tmp1);
9954   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9955   addq(result, 8);
9956   subq(length, 8);
9957   jcc(Assembler::equal, SAME_TILL_END);
9958   //falling through if less than 8 bytes left
9959 
9960   bind(VECTOR4_TAIL);
9961   cmpq(length, 4);
9962   jccb(Assembler::less, BYTES_TAIL);
9963   bind(VECTOR4_LOOP);
9964   movl(tmp1, Address(obja, result));
9965   xorl(tmp1, Address(objb, result));
9966   testl(tmp1, tmp1);
9967   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9968   addq(result, 4);
9969   subq(length, 4);
9970   jcc(Assembler::equal, SAME_TILL_END);
9971   //falling through if less than 4 bytes left
9972 
9973   bind(BYTES_TAIL);
9974   bind(BYTES_LOOP);
9975   load_unsigned_byte(tmp1, Address(obja, result));
9976   load_unsigned_byte(tmp2, Address(objb, result));
9977   xorl(tmp1, tmp2);
9978   testl(tmp1, tmp1);
9979   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9980   decq(length);
9981   jccb(Assembler::zero, SAME_TILL_END);
9982   incq(result);
9983   load_unsigned_byte(tmp1, Address(obja, result));
9984   load_unsigned_byte(tmp2, Address(objb, result));
9985   xorl(tmp1, tmp2);
9986   testl(tmp1, tmp1);
9987   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9988   decq(length);
9989   jccb(Assembler::zero, SAME_TILL_END);
9990   incq(result);
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   jmpb(SAME_TILL_END);
9997 
9998   if (UseAVX >= 2) {
9999     bind(VECTOR32_NOT_EQUAL);
10000     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
10001     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
10002     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
10003     vpmovmskb(tmp1, rymm0);
10004     bsfq(tmp1, tmp1);
10005     addq(result, tmp1);
10006     shrq(result);
10007     jmpb(DONE);
10008   }
10009 
10010   bind(VECTOR16_NOT_EQUAL);
10011   if (UseAVX >= 2) {
10012     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
10013     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
10014     pxor(rymm0, rymm2);
10015   } else {
10016     pcmpeqb(rymm2, rymm2);
10017     pxor(rymm0, rymm1);
10018     pcmpeqb(rymm0, rymm1);
10019     pxor(rymm0, rymm2);
10020   }
10021   pmovmskb(tmp1, rymm0);
10022   bsfq(tmp1, tmp1);
10023   addq(result, tmp1);
10024   shrq(result);
10025   jmpb(DONE);
10026 
10027   bind(VECTOR8_NOT_EQUAL);
10028   bind(VECTOR4_NOT_EQUAL);
10029   bsfq(tmp1, tmp1);
10030   shrq(tmp1, 3);
10031   addq(result, tmp1);
10032   bind(BYTES_NOT_EQUAL);
10033   shrq(result);
10034   jmpb(DONE);
10035 
10036   bind(SAME_TILL_END);
10037   mov64(result, -1);
10038 
10039   bind(DONE);
10040 }
10041 
10042 //Helper functions for square_to_len()
10043 
10044 /**
10045  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
10046  * Preserves x and z and modifies rest of the registers.
10047  */
10048 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10049   // Perform square and right shift by 1
10050   // Handle odd xlen case first, then for even xlen do the following
10051   // jlong carry = 0;
10052   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
10053   //     huge_128 product = x[j:j+1] * x[j:j+1];
10054   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
10055   //     z[i+2:i+3] = (jlong)(product >>> 1);
10056   //     carry = (jlong)product;
10057   // }
10058 
10059   xorq(tmp5, tmp5);     // carry
10060   xorq(rdxReg, rdxReg);
10061   xorl(tmp1, tmp1);     // index for x
10062   xorl(tmp4, tmp4);     // index for z
10063 
10064   Label L_first_loop, L_first_loop_exit;
10065 
10066   testl(xlen, 1);
10067   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
10068 
10069   // Square and right shift by 1 the odd element using 32 bit multiply
10070   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
10071   imulq(raxReg, raxReg);
10072   shrq(raxReg, 1);
10073   adcq(tmp5, 0);
10074   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
10075   incrementl(tmp1);
10076   addl(tmp4, 2);
10077 
10078   // Square and  right shift by 1 the rest using 64 bit multiply
10079   bind(L_first_loop);
10080   cmpptr(tmp1, xlen);
10081   jccb(Assembler::equal, L_first_loop_exit);
10082 
10083   // Square
10084   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
10085   rorq(raxReg, 32);    // convert big-endian to little-endian
10086   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
10087 
10088   // Right shift by 1 and save carry
10089   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
10090   rcrq(rdxReg, 1);
10091   rcrq(raxReg, 1);
10092   adcq(tmp5, 0);
10093 
10094   // Store result in z
10095   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
10096   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
10097 
10098   // Update indices for x and z
10099   addl(tmp1, 2);
10100   addl(tmp4, 4);
10101   jmp(L_first_loop);
10102 
10103   bind(L_first_loop_exit);
10104 }
10105 
10106 
10107 /**
10108  * Perform the following multiply add operation using BMI2 instructions
10109  * carry:sum = sum + op1*op2 + carry
10110  * op2 should be in rdx
10111  * op2 is preserved, all other registers are modified
10112  */
10113 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
10114   // assert op2 is rdx
10115   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
10116   addq(sum, carry);
10117   adcq(tmp2, 0);
10118   addq(sum, op1);
10119   adcq(tmp2, 0);
10120   movq(carry, tmp2);
10121 }
10122 
10123 /**
10124  * Perform the following multiply add operation:
10125  * carry:sum = sum + op1*op2 + carry
10126  * Preserves op1, op2 and modifies rest of registers
10127  */
10128 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
10129   // rdx:rax = op1 * op2
10130   movq(raxReg, op2);
10131   mulq(op1);
10132 
10133   //  rdx:rax = sum + carry + rdx:rax
10134   addq(sum, carry);
10135   adcq(rdxReg, 0);
10136   addq(sum, raxReg);
10137   adcq(rdxReg, 0);
10138 
10139   // carry:sum = rdx:sum
10140   movq(carry, rdxReg);
10141 }
10142 
10143 /**
10144  * Add 64 bit long carry into z[] with carry propogation.
10145  * Preserves z and carry register values and modifies rest of registers.
10146  *
10147  */
10148 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
10149   Label L_fourth_loop, L_fourth_loop_exit;
10150 
10151   movl(tmp1, 1);
10152   subl(zlen, 2);
10153   addq(Address(z, zlen, Address::times_4, 0), carry);
10154 
10155   bind(L_fourth_loop);
10156   jccb(Assembler::carryClear, L_fourth_loop_exit);
10157   subl(zlen, 2);
10158   jccb(Assembler::negative, L_fourth_loop_exit);
10159   addq(Address(z, zlen, Address::times_4, 0), tmp1);
10160   jmp(L_fourth_loop);
10161   bind(L_fourth_loop_exit);
10162 }
10163 
10164 /**
10165  * Shift z[] left by 1 bit.
10166  * Preserves x, len, z and zlen registers and modifies rest of the registers.
10167  *
10168  */
10169 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
10170 
10171   Label L_fifth_loop, L_fifth_loop_exit;
10172 
10173   // Fifth loop
10174   // Perform primitiveLeftShift(z, zlen, 1)
10175 
10176   const Register prev_carry = tmp1;
10177   const Register new_carry = tmp4;
10178   const Register value = tmp2;
10179   const Register zidx = tmp3;
10180 
10181   // int zidx, carry;
10182   // long value;
10183   // carry = 0;
10184   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
10185   //    (carry:value)  = (z[i] << 1) | carry ;
10186   //    z[i] = value;
10187   // }
10188 
10189   movl(zidx, zlen);
10190   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
10191 
10192   bind(L_fifth_loop);
10193   decl(zidx);  // Use decl to preserve carry flag
10194   decl(zidx);
10195   jccb(Assembler::negative, L_fifth_loop_exit);
10196 
10197   if (UseBMI2Instructions) {
10198      movq(value, Address(z, zidx, Address::times_4, 0));
10199      rclq(value, 1);
10200      rorxq(value, value, 32);
10201      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10202   }
10203   else {
10204     // clear new_carry
10205     xorl(new_carry, new_carry);
10206 
10207     // Shift z[i] by 1, or in previous carry and save new carry
10208     movq(value, Address(z, zidx, Address::times_4, 0));
10209     shlq(value, 1);
10210     adcl(new_carry, 0);
10211 
10212     orq(value, prev_carry);
10213     rorq(value, 0x20);
10214     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10215 
10216     // Set previous carry = new carry
10217     movl(prev_carry, new_carry);
10218   }
10219   jmp(L_fifth_loop);
10220 
10221   bind(L_fifth_loop_exit);
10222 }
10223 
10224 
10225 /**
10226  * Code for BigInteger::squareToLen() intrinsic
10227  *
10228  * rdi: x
10229  * rsi: len
10230  * r8:  z
10231  * rcx: zlen
10232  * r12: tmp1
10233  * r13: tmp2
10234  * r14: tmp3
10235  * r15: tmp4
10236  * rbx: tmp5
10237  *
10238  */
10239 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) {
10240 
10241   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;
10242   push(tmp1);
10243   push(tmp2);
10244   push(tmp3);
10245   push(tmp4);
10246   push(tmp5);
10247 
10248   // First loop
10249   // Store the squares, right shifted one bit (i.e., divided by 2).
10250   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
10251 
10252   // Add in off-diagonal sums.
10253   //
10254   // Second, third (nested) and fourth loops.
10255   // zlen +=2;
10256   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
10257   //    carry = 0;
10258   //    long op2 = x[xidx:xidx+1];
10259   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
10260   //       k -= 2;
10261   //       long op1 = x[j:j+1];
10262   //       long sum = z[k:k+1];
10263   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
10264   //       z[k:k+1] = sum;
10265   //    }
10266   //    add_one_64(z, k, carry, tmp_regs);
10267   // }
10268 
10269   const Register carry = tmp5;
10270   const Register sum = tmp3;
10271   const Register op1 = tmp4;
10272   Register op2 = tmp2;
10273 
10274   push(zlen);
10275   push(len);
10276   addl(zlen,2);
10277   bind(L_second_loop);
10278   xorq(carry, carry);
10279   subl(zlen, 4);
10280   subl(len, 2);
10281   push(zlen);
10282   push(len);
10283   cmpl(len, 0);
10284   jccb(Assembler::lessEqual, L_second_loop_exit);
10285 
10286   // Multiply an array by one 64 bit long.
10287   if (UseBMI2Instructions) {
10288     op2 = rdxReg;
10289     movq(op2, Address(x, len, Address::times_4,  0));
10290     rorxq(op2, op2, 32);
10291   }
10292   else {
10293     movq(op2, Address(x, len, Address::times_4,  0));
10294     rorq(op2, 32);
10295   }
10296 
10297   bind(L_third_loop);
10298   decrementl(len);
10299   jccb(Assembler::negative, L_third_loop_exit);
10300   decrementl(len);
10301   jccb(Assembler::negative, L_last_x);
10302 
10303   movq(op1, Address(x, len, Address::times_4,  0));
10304   rorq(op1, 32);
10305 
10306   bind(L_multiply);
10307   subl(zlen, 2);
10308   movq(sum, Address(z, zlen, Address::times_4,  0));
10309 
10310   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10311   if (UseBMI2Instructions) {
10312     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10313   }
10314   else {
10315     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10316   }
10317 
10318   movq(Address(z, zlen, Address::times_4, 0), sum);
10319 
10320   jmp(L_third_loop);
10321   bind(L_third_loop_exit);
10322 
10323   // Fourth loop
10324   // Add 64 bit long carry into z with carry propogation.
10325   // Uses offsetted zlen.
10326   add_one_64(z, zlen, carry, tmp1);
10327 
10328   pop(len);
10329   pop(zlen);
10330   jmp(L_second_loop);
10331 
10332   // Next infrequent code is moved outside loops.
10333   bind(L_last_x);
10334   movl(op1, Address(x, 0));
10335   jmp(L_multiply);
10336 
10337   bind(L_second_loop_exit);
10338   pop(len);
10339   pop(zlen);
10340   pop(len);
10341   pop(zlen);
10342 
10343   // Fifth loop
10344   // Shift z left 1 bit.
10345   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10346 
10347   // z[zlen-1] |= x[len-1] & 1;
10348   movl(tmp3, Address(x, len, Address::times_4, -4));
10349   andl(tmp3, 1);
10350   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10351 
10352   pop(tmp5);
10353   pop(tmp4);
10354   pop(tmp3);
10355   pop(tmp2);
10356   pop(tmp1);
10357 }
10358 
10359 /**
10360  * Helper function for mul_add()
10361  * Multiply the in[] by int k and add to out[] starting at offset offs using
10362  * 128 bit by 32 bit multiply and return the carry in tmp5.
10363  * Only quad int aligned length of in[] is operated on in this function.
10364  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10365  * This function preserves out, in and k registers.
10366  * len and offset point to the appropriate index in "in" & "out" correspondingly
10367  * tmp5 has the carry.
10368  * other registers are temporary and are modified.
10369  *
10370  */
10371 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10372   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10373   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10374 
10375   Label L_first_loop, L_first_loop_exit;
10376 
10377   movl(tmp1, len);
10378   shrl(tmp1, 2);
10379 
10380   bind(L_first_loop);
10381   subl(tmp1, 1);
10382   jccb(Assembler::negative, L_first_loop_exit);
10383 
10384   subl(len, 4);
10385   subl(offset, 4);
10386 
10387   Register op2 = tmp2;
10388   const Register sum = tmp3;
10389   const Register op1 = tmp4;
10390   const Register carry = tmp5;
10391 
10392   if (UseBMI2Instructions) {
10393     op2 = rdxReg;
10394   }
10395 
10396   movq(op1, Address(in, len, Address::times_4,  8));
10397   rorq(op1, 32);
10398   movq(sum, Address(out, offset, Address::times_4,  8));
10399   rorq(sum, 32);
10400   if (UseBMI2Instructions) {
10401     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10402   }
10403   else {
10404     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10405   }
10406   // Store back in big endian from little endian
10407   rorq(sum, 0x20);
10408   movq(Address(out, offset, Address::times_4,  8), sum);
10409 
10410   movq(op1, Address(in, len, Address::times_4,  0));
10411   rorq(op1, 32);
10412   movq(sum, Address(out, offset, Address::times_4,  0));
10413   rorq(sum, 32);
10414   if (UseBMI2Instructions) {
10415     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10416   }
10417   else {
10418     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10419   }
10420   // Store back in big endian from little endian
10421   rorq(sum, 0x20);
10422   movq(Address(out, offset, Address::times_4,  0), sum);
10423 
10424   jmp(L_first_loop);
10425   bind(L_first_loop_exit);
10426 }
10427 
10428 /**
10429  * Code for BigInteger::mulAdd() intrinsic
10430  *
10431  * rdi: out
10432  * rsi: in
10433  * r11: offs (out.length - offset)
10434  * rcx: len
10435  * r8:  k
10436  * r12: tmp1
10437  * r13: tmp2
10438  * r14: tmp3
10439  * r15: tmp4
10440  * rbx: tmp5
10441  * Multiply the in[] by word k and add to out[], return the carry in rax
10442  */
10443 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10444    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10445    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10446 
10447   Label L_carry, L_last_in, L_done;
10448 
10449 // carry = 0;
10450 // for (int j=len-1; j >= 0; j--) {
10451 //    long product = (in[j] & LONG_MASK) * kLong +
10452 //                   (out[offs] & LONG_MASK) + carry;
10453 //    out[offs--] = (int)product;
10454 //    carry = product >>> 32;
10455 // }
10456 //
10457   push(tmp1);
10458   push(tmp2);
10459   push(tmp3);
10460   push(tmp4);
10461   push(tmp5);
10462 
10463   Register op2 = tmp2;
10464   const Register sum = tmp3;
10465   const Register op1 = tmp4;
10466   const Register carry =  tmp5;
10467 
10468   if (UseBMI2Instructions) {
10469     op2 = rdxReg;
10470     movl(op2, k);
10471   }
10472   else {
10473     movl(op2, k);
10474   }
10475 
10476   xorq(carry, carry);
10477 
10478   //First loop
10479 
10480   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10481   //The carry is in tmp5
10482   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10483 
10484   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10485   decrementl(len);
10486   jccb(Assembler::negative, L_carry);
10487   decrementl(len);
10488   jccb(Assembler::negative, L_last_in);
10489 
10490   movq(op1, Address(in, len, Address::times_4,  0));
10491   rorq(op1, 32);
10492 
10493   subl(offs, 2);
10494   movq(sum, Address(out, offs, Address::times_4,  0));
10495   rorq(sum, 32);
10496 
10497   if (UseBMI2Instructions) {
10498     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10499   }
10500   else {
10501     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10502   }
10503 
10504   // Store back in big endian from little endian
10505   rorq(sum, 0x20);
10506   movq(Address(out, offs, Address::times_4,  0), sum);
10507 
10508   testl(len, len);
10509   jccb(Assembler::zero, L_carry);
10510 
10511   //Multiply the last in[] entry, if any
10512   bind(L_last_in);
10513   movl(op1, Address(in, 0));
10514   movl(sum, Address(out, offs, Address::times_4,  -4));
10515 
10516   movl(raxReg, k);
10517   mull(op1); //tmp4 * eax -> edx:eax
10518   addl(sum, carry);
10519   adcl(rdxReg, 0);
10520   addl(sum, raxReg);
10521   adcl(rdxReg, 0);
10522   movl(carry, rdxReg);
10523 
10524   movl(Address(out, offs, Address::times_4,  -4), sum);
10525 
10526   bind(L_carry);
10527   //return tmp5/carry as carry in rax
10528   movl(rax, carry);
10529 
10530   bind(L_done);
10531   pop(tmp5);
10532   pop(tmp4);
10533   pop(tmp3);
10534   pop(tmp2);
10535   pop(tmp1);
10536 }
10537 #endif
10538 
10539 /**
10540  * Emits code to update CRC-32 with a byte value according to constants in table
10541  *
10542  * @param [in,out]crc   Register containing the crc.
10543  * @param [in]val       Register containing the byte to fold into the CRC.
10544  * @param [in]table     Register containing the table of crc constants.
10545  *
10546  * uint32_t crc;
10547  * val = crc_table[(val ^ crc) & 0xFF];
10548  * crc = val ^ (crc >> 8);
10549  *
10550  */
10551 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10552   xorl(val, crc);
10553   andl(val, 0xFF);
10554   shrl(crc, 8); // unsigned shift
10555   xorl(crc, Address(table, val, Address::times_4, 0));
10556 }
10557 
10558 /**
10559  * Fold 128-bit data chunk
10560  */
10561 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10562   if (UseAVX > 0) {
10563     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10564     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10565     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10566     pxor(xcrc, xtmp);
10567   } else {
10568     movdqa(xtmp, xcrc);
10569     pclmulhdq(xtmp, xK);   // [123:64]
10570     pclmulldq(xcrc, xK);   // [63:0]
10571     pxor(xcrc, xtmp);
10572     movdqu(xtmp, Address(buf, offset));
10573     pxor(xcrc, xtmp);
10574   }
10575 }
10576 
10577 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10578   if (UseAVX > 0) {
10579     vpclmulhdq(xtmp, xK, xcrc);
10580     vpclmulldq(xcrc, xK, xcrc);
10581     pxor(xcrc, xbuf);
10582     pxor(xcrc, xtmp);
10583   } else {
10584     movdqa(xtmp, xcrc);
10585     pclmulhdq(xtmp, xK);
10586     pclmulldq(xcrc, xK);
10587     pxor(xcrc, xbuf);
10588     pxor(xcrc, xtmp);
10589   }
10590 }
10591 
10592 /**
10593  * 8-bit folds to compute 32-bit CRC
10594  *
10595  * uint64_t xcrc;
10596  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10597  */
10598 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10599   movdl(tmp, xcrc);
10600   andl(tmp, 0xFF);
10601   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10602   psrldq(xcrc, 1); // unsigned shift one byte
10603   pxor(xcrc, xtmp);
10604 }
10605 
10606 /**
10607  * uint32_t crc;
10608  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10609  */
10610 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10611   movl(tmp, crc);
10612   andl(tmp, 0xFF);
10613   shrl(crc, 8);
10614   xorl(crc, Address(table, tmp, Address::times_4, 0));
10615 }
10616 
10617 /**
10618  * @param crc   register containing existing CRC (32-bit)
10619  * @param buf   register pointing to input byte buffer (byte*)
10620  * @param len   register containing number of bytes
10621  * @param table register that will contain address of CRC table
10622  * @param tmp   scratch register
10623  */
10624 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10625   assert_different_registers(crc, buf, len, table, tmp, rax);
10626 
10627   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10628   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10629 
10630   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10631   // context for the registers used, where all instructions below are using 128-bit mode
10632   // On EVEX without VL and BW, these instructions will all be AVX.
10633   if (VM_Version::supports_avx512vlbw()) {
10634     movl(tmp, 0xffff);
10635     kmovwl(k1, tmp);
10636   }
10637 
10638   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10639   notl(crc); // ~crc
10640   cmpl(len, 16);
10641   jcc(Assembler::less, L_tail);
10642 
10643   // Align buffer to 16 bytes
10644   movl(tmp, buf);
10645   andl(tmp, 0xF);
10646   jccb(Assembler::zero, L_aligned);
10647   subl(tmp,  16);
10648   addl(len, tmp);
10649 
10650   align(4);
10651   BIND(L_align_loop);
10652   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10653   update_byte_crc32(crc, rax, table);
10654   increment(buf);
10655   incrementl(tmp);
10656   jccb(Assembler::less, L_align_loop);
10657 
10658   BIND(L_aligned);
10659   movl(tmp, len); // save
10660   shrl(len, 4);
10661   jcc(Assembler::zero, L_tail_restore);
10662 
10663   // Fold crc into first bytes of vector
10664   movdqa(xmm1, Address(buf, 0));
10665   movdl(rax, xmm1);
10666   xorl(crc, rax);
10667   if (VM_Version::supports_sse4_1()) {
10668     pinsrd(xmm1, crc, 0);
10669   } else {
10670     pinsrw(xmm1, crc, 0);
10671     shrl(crc, 16);
10672     pinsrw(xmm1, crc, 1);
10673   }
10674   addptr(buf, 16);
10675   subl(len, 4); // len > 0
10676   jcc(Assembler::less, L_fold_tail);
10677 
10678   movdqa(xmm2, Address(buf,  0));
10679   movdqa(xmm3, Address(buf, 16));
10680   movdqa(xmm4, Address(buf, 32));
10681   addptr(buf, 48);
10682   subl(len, 3);
10683   jcc(Assembler::lessEqual, L_fold_512b);
10684 
10685   // Fold total 512 bits of polynomial on each iteration,
10686   // 128 bits per each of 4 parallel streams.
10687   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10688 
10689   align(32);
10690   BIND(L_fold_512b_loop);
10691   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10692   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10693   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10694   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10695   addptr(buf, 64);
10696   subl(len, 4);
10697   jcc(Assembler::greater, L_fold_512b_loop);
10698 
10699   // Fold 512 bits to 128 bits.
10700   BIND(L_fold_512b);
10701   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10702   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10703   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10704   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10705 
10706   // Fold the rest of 128 bits data chunks
10707   BIND(L_fold_tail);
10708   addl(len, 3);
10709   jccb(Assembler::lessEqual, L_fold_128b);
10710   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10711 
10712   BIND(L_fold_tail_loop);
10713   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10714   addptr(buf, 16);
10715   decrementl(len);
10716   jccb(Assembler::greater, L_fold_tail_loop);
10717 
10718   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10719   BIND(L_fold_128b);
10720   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10721   if (UseAVX > 0) {
10722     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10723     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10724     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10725   } else {
10726     movdqa(xmm2, xmm0);
10727     pclmulqdq(xmm2, xmm1, 0x1);
10728     movdqa(xmm3, xmm0);
10729     pand(xmm3, xmm2);
10730     pclmulqdq(xmm0, xmm3, 0x1);
10731   }
10732   psrldq(xmm1, 8);
10733   psrldq(xmm2, 4);
10734   pxor(xmm0, xmm1);
10735   pxor(xmm0, xmm2);
10736 
10737   // 8 8-bit folds to compute 32-bit CRC.
10738   for (int j = 0; j < 4; j++) {
10739     fold_8bit_crc32(xmm0, table, xmm1, rax);
10740   }
10741   movdl(crc, xmm0); // mov 32 bits to general register
10742   for (int j = 0; j < 4; j++) {
10743     fold_8bit_crc32(crc, table, rax);
10744   }
10745 
10746   BIND(L_tail_restore);
10747   movl(len, tmp); // restore
10748   BIND(L_tail);
10749   andl(len, 0xf);
10750   jccb(Assembler::zero, L_exit);
10751 
10752   // Fold the rest of bytes
10753   align(4);
10754   BIND(L_tail_loop);
10755   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10756   update_byte_crc32(crc, rax, table);
10757   increment(buf);
10758   decrementl(len);
10759   jccb(Assembler::greater, L_tail_loop);
10760 
10761   BIND(L_exit);
10762   notl(crc); // ~c
10763 }
10764 
10765 #ifdef _LP64
10766 // S. Gueron / Information Processing Letters 112 (2012) 184
10767 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10768 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10769 // Output: the 64-bit carry-less product of B * CONST
10770 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10771                                      Register tmp1, Register tmp2, Register tmp3) {
10772   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10773   if (n > 0) {
10774     addq(tmp3, n * 256 * 8);
10775   }
10776   //    Q1 = TABLEExt[n][B & 0xFF];
10777   movl(tmp1, in);
10778   andl(tmp1, 0x000000FF);
10779   shll(tmp1, 3);
10780   addq(tmp1, tmp3);
10781   movq(tmp1, Address(tmp1, 0));
10782 
10783   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10784   movl(tmp2, in);
10785   shrl(tmp2, 8);
10786   andl(tmp2, 0x000000FF);
10787   shll(tmp2, 3);
10788   addq(tmp2, tmp3);
10789   movq(tmp2, Address(tmp2, 0));
10790 
10791   shlq(tmp2, 8);
10792   xorq(tmp1, tmp2);
10793 
10794   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10795   movl(tmp2, in);
10796   shrl(tmp2, 16);
10797   andl(tmp2, 0x000000FF);
10798   shll(tmp2, 3);
10799   addq(tmp2, tmp3);
10800   movq(tmp2, Address(tmp2, 0));
10801 
10802   shlq(tmp2, 16);
10803   xorq(tmp1, tmp2);
10804 
10805   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10806   shrl(in, 24);
10807   andl(in, 0x000000FF);
10808   shll(in, 3);
10809   addq(in, tmp3);
10810   movq(in, Address(in, 0));
10811 
10812   shlq(in, 24);
10813   xorq(in, tmp1);
10814   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10815 }
10816 
10817 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10818                                       Register in_out,
10819                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10820                                       XMMRegister w_xtmp2,
10821                                       Register tmp1,
10822                                       Register n_tmp2, Register n_tmp3) {
10823   if (is_pclmulqdq_supported) {
10824     movdl(w_xtmp1, in_out); // modified blindly
10825 
10826     movl(tmp1, const_or_pre_comp_const_index);
10827     movdl(w_xtmp2, tmp1);
10828     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10829 
10830     movdq(in_out, w_xtmp1);
10831   } else {
10832     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10833   }
10834 }
10835 
10836 // Recombination Alternative 2: No bit-reflections
10837 // T1 = (CRC_A * U1) << 1
10838 // T2 = (CRC_B * U2) << 1
10839 // C1 = T1 >> 32
10840 // C2 = T2 >> 32
10841 // T1 = T1 & 0xFFFFFFFF
10842 // T2 = T2 & 0xFFFFFFFF
10843 // T1 = CRC32(0, T1)
10844 // T2 = CRC32(0, T2)
10845 // C1 = C1 ^ T1
10846 // C2 = C2 ^ T2
10847 // CRC = C1 ^ C2 ^ CRC_C
10848 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,
10849                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10850                                      Register tmp1, Register tmp2,
10851                                      Register n_tmp3) {
10852   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10853   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10854   shlq(in_out, 1);
10855   movl(tmp1, in_out);
10856   shrq(in_out, 32);
10857   xorl(tmp2, tmp2);
10858   crc32(tmp2, tmp1, 4);
10859   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10860   shlq(in1, 1);
10861   movl(tmp1, in1);
10862   shrq(in1, 32);
10863   xorl(tmp2, tmp2);
10864   crc32(tmp2, tmp1, 4);
10865   xorl(in1, tmp2);
10866   xorl(in_out, in1);
10867   xorl(in_out, in2);
10868 }
10869 
10870 // Set N to predefined value
10871 // Subtract from a lenght of a buffer
10872 // execute in a loop:
10873 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10874 // for i = 1 to N do
10875 //  CRC_A = CRC32(CRC_A, A[i])
10876 //  CRC_B = CRC32(CRC_B, B[i])
10877 //  CRC_C = CRC32(CRC_C, C[i])
10878 // end for
10879 // Recombine
10880 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,
10881                                        Register in_out1, Register in_out2, Register in_out3,
10882                                        Register tmp1, Register tmp2, Register tmp3,
10883                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10884                                        Register tmp4, Register tmp5,
10885                                        Register n_tmp6) {
10886   Label L_processPartitions;
10887   Label L_processPartition;
10888   Label L_exit;
10889 
10890   bind(L_processPartitions);
10891   cmpl(in_out1, 3 * size);
10892   jcc(Assembler::less, L_exit);
10893     xorl(tmp1, tmp1);
10894     xorl(tmp2, tmp2);
10895     movq(tmp3, in_out2);
10896     addq(tmp3, size);
10897 
10898     bind(L_processPartition);
10899       crc32(in_out3, Address(in_out2, 0), 8);
10900       crc32(tmp1, Address(in_out2, size), 8);
10901       crc32(tmp2, Address(in_out2, size * 2), 8);
10902       addq(in_out2, 8);
10903       cmpq(in_out2, tmp3);
10904       jcc(Assembler::less, L_processPartition);
10905     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10906             w_xtmp1, w_xtmp2, w_xtmp3,
10907             tmp4, tmp5,
10908             n_tmp6);
10909     addq(in_out2, 2 * size);
10910     subl(in_out1, 3 * size);
10911     jmp(L_processPartitions);
10912 
10913   bind(L_exit);
10914 }
10915 #else
10916 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10917                                      Register tmp1, Register tmp2, Register tmp3,
10918                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10919   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10920   if (n > 0) {
10921     addl(tmp3, n * 256 * 8);
10922   }
10923   //    Q1 = TABLEExt[n][B & 0xFF];
10924   movl(tmp1, in_out);
10925   andl(tmp1, 0x000000FF);
10926   shll(tmp1, 3);
10927   addl(tmp1, tmp3);
10928   movq(xtmp1, Address(tmp1, 0));
10929 
10930   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10931   movl(tmp2, in_out);
10932   shrl(tmp2, 8);
10933   andl(tmp2, 0x000000FF);
10934   shll(tmp2, 3);
10935   addl(tmp2, tmp3);
10936   movq(xtmp2, Address(tmp2, 0));
10937 
10938   psllq(xtmp2, 8);
10939   pxor(xtmp1, xtmp2);
10940 
10941   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10942   movl(tmp2, in_out);
10943   shrl(tmp2, 16);
10944   andl(tmp2, 0x000000FF);
10945   shll(tmp2, 3);
10946   addl(tmp2, tmp3);
10947   movq(xtmp2, Address(tmp2, 0));
10948 
10949   psllq(xtmp2, 16);
10950   pxor(xtmp1, xtmp2);
10951 
10952   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10953   shrl(in_out, 24);
10954   andl(in_out, 0x000000FF);
10955   shll(in_out, 3);
10956   addl(in_out, tmp3);
10957   movq(xtmp2, Address(in_out, 0));
10958 
10959   psllq(xtmp2, 24);
10960   pxor(xtmp1, xtmp2); // Result in CXMM
10961   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10962 }
10963 
10964 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10965                                       Register in_out,
10966                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10967                                       XMMRegister w_xtmp2,
10968                                       Register tmp1,
10969                                       Register n_tmp2, Register n_tmp3) {
10970   if (is_pclmulqdq_supported) {
10971     movdl(w_xtmp1, in_out);
10972 
10973     movl(tmp1, const_or_pre_comp_const_index);
10974     movdl(w_xtmp2, tmp1);
10975     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10976     // Keep result in XMM since GPR is 32 bit in length
10977   } else {
10978     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10979   }
10980 }
10981 
10982 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,
10983                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10984                                      Register tmp1, Register tmp2,
10985                                      Register n_tmp3) {
10986   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10987   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10988 
10989   psllq(w_xtmp1, 1);
10990   movdl(tmp1, w_xtmp1);
10991   psrlq(w_xtmp1, 32);
10992   movdl(in_out, w_xtmp1);
10993 
10994   xorl(tmp2, tmp2);
10995   crc32(tmp2, tmp1, 4);
10996   xorl(in_out, tmp2);
10997 
10998   psllq(w_xtmp2, 1);
10999   movdl(tmp1, w_xtmp2);
11000   psrlq(w_xtmp2, 32);
11001   movdl(in1, w_xtmp2);
11002 
11003   xorl(tmp2, tmp2);
11004   crc32(tmp2, tmp1, 4);
11005   xorl(in1, tmp2);
11006   xorl(in_out, in1);
11007   xorl(in_out, in2);
11008 }
11009 
11010 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,
11011                                        Register in_out1, Register in_out2, Register in_out3,
11012                                        Register tmp1, Register tmp2, Register tmp3,
11013                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11014                                        Register tmp4, Register tmp5,
11015                                        Register n_tmp6) {
11016   Label L_processPartitions;
11017   Label L_processPartition;
11018   Label L_exit;
11019 
11020   bind(L_processPartitions);
11021   cmpl(in_out1, 3 * size);
11022   jcc(Assembler::less, L_exit);
11023     xorl(tmp1, tmp1);
11024     xorl(tmp2, tmp2);
11025     movl(tmp3, in_out2);
11026     addl(tmp3, size);
11027 
11028     bind(L_processPartition);
11029       crc32(in_out3, Address(in_out2, 0), 4);
11030       crc32(tmp1, Address(in_out2, size), 4);
11031       crc32(tmp2, Address(in_out2, size*2), 4);
11032       crc32(in_out3, Address(in_out2, 0+4), 4);
11033       crc32(tmp1, Address(in_out2, size+4), 4);
11034       crc32(tmp2, Address(in_out2, size*2+4), 4);
11035       addl(in_out2, 8);
11036       cmpl(in_out2, tmp3);
11037       jcc(Assembler::less, L_processPartition);
11038 
11039         push(tmp3);
11040         push(in_out1);
11041         push(in_out2);
11042         tmp4 = tmp3;
11043         tmp5 = in_out1;
11044         n_tmp6 = in_out2;
11045 
11046       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
11047             w_xtmp1, w_xtmp2, w_xtmp3,
11048             tmp4, tmp5,
11049             n_tmp6);
11050 
11051         pop(in_out2);
11052         pop(in_out1);
11053         pop(tmp3);
11054 
11055     addl(in_out2, 2 * size);
11056     subl(in_out1, 3 * size);
11057     jmp(L_processPartitions);
11058 
11059   bind(L_exit);
11060 }
11061 #endif //LP64
11062 
11063 #ifdef _LP64
11064 // Algorithm 2: Pipelined usage of the CRC32 instruction.
11065 // Input: A buffer I of L bytes.
11066 // Output: the CRC32C value of the buffer.
11067 // Notations:
11068 // Write L = 24N + r, with N = floor (L/24).
11069 // r = L mod 24 (0 <= r < 24).
11070 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
11071 // N quadwords, and R consists of r bytes.
11072 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
11073 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
11074 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
11075 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
11076 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11077                                           Register tmp1, Register tmp2, Register tmp3,
11078                                           Register tmp4, Register tmp5, Register tmp6,
11079                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11080                                           bool is_pclmulqdq_supported) {
11081   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11082   Label L_wordByWord;
11083   Label L_byteByByteProlog;
11084   Label L_byteByByte;
11085   Label L_exit;
11086 
11087   if (is_pclmulqdq_supported ) {
11088     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11089     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
11090 
11091     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11092     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11093 
11094     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11095     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11096     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
11097   } else {
11098     const_or_pre_comp_const_index[0] = 1;
11099     const_or_pre_comp_const_index[1] = 0;
11100 
11101     const_or_pre_comp_const_index[2] = 3;
11102     const_or_pre_comp_const_index[3] = 2;
11103 
11104     const_or_pre_comp_const_index[4] = 5;
11105     const_or_pre_comp_const_index[5] = 4;
11106    }
11107   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11108                     in2, in1, in_out,
11109                     tmp1, tmp2, tmp3,
11110                     w_xtmp1, w_xtmp2, w_xtmp3,
11111                     tmp4, tmp5,
11112                     tmp6);
11113   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11114                     in2, in1, in_out,
11115                     tmp1, tmp2, tmp3,
11116                     w_xtmp1, w_xtmp2, w_xtmp3,
11117                     tmp4, tmp5,
11118                     tmp6);
11119   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11120                     in2, in1, in_out,
11121                     tmp1, tmp2, tmp3,
11122                     w_xtmp1, w_xtmp2, w_xtmp3,
11123                     tmp4, tmp5,
11124                     tmp6);
11125   movl(tmp1, in2);
11126   andl(tmp1, 0x00000007);
11127   negl(tmp1);
11128   addl(tmp1, in2);
11129   addq(tmp1, in1);
11130 
11131   BIND(L_wordByWord);
11132   cmpq(in1, tmp1);
11133   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11134     crc32(in_out, Address(in1, 0), 4);
11135     addq(in1, 4);
11136     jmp(L_wordByWord);
11137 
11138   BIND(L_byteByByteProlog);
11139   andl(in2, 0x00000007);
11140   movl(tmp2, 1);
11141 
11142   BIND(L_byteByByte);
11143   cmpl(tmp2, in2);
11144   jccb(Assembler::greater, L_exit);
11145     crc32(in_out, Address(in1, 0), 1);
11146     incq(in1);
11147     incl(tmp2);
11148     jmp(L_byteByByte);
11149 
11150   BIND(L_exit);
11151 }
11152 #else
11153 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11154                                           Register tmp1, Register  tmp2, Register tmp3,
11155                                           Register tmp4, Register  tmp5, Register tmp6,
11156                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11157                                           bool is_pclmulqdq_supported) {
11158   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11159   Label L_wordByWord;
11160   Label L_byteByByteProlog;
11161   Label L_byteByByte;
11162   Label L_exit;
11163 
11164   if (is_pclmulqdq_supported) {
11165     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11166     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
11167 
11168     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11169     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11170 
11171     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11172     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11173   } else {
11174     const_or_pre_comp_const_index[0] = 1;
11175     const_or_pre_comp_const_index[1] = 0;
11176 
11177     const_or_pre_comp_const_index[2] = 3;
11178     const_or_pre_comp_const_index[3] = 2;
11179 
11180     const_or_pre_comp_const_index[4] = 5;
11181     const_or_pre_comp_const_index[5] = 4;
11182   }
11183   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11184                     in2, in1, in_out,
11185                     tmp1, tmp2, tmp3,
11186                     w_xtmp1, w_xtmp2, w_xtmp3,
11187                     tmp4, tmp5,
11188                     tmp6);
11189   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11190                     in2, in1, in_out,
11191                     tmp1, tmp2, tmp3,
11192                     w_xtmp1, w_xtmp2, w_xtmp3,
11193                     tmp4, tmp5,
11194                     tmp6);
11195   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11196                     in2, in1, in_out,
11197                     tmp1, tmp2, tmp3,
11198                     w_xtmp1, w_xtmp2, w_xtmp3,
11199                     tmp4, tmp5,
11200                     tmp6);
11201   movl(tmp1, in2);
11202   andl(tmp1, 0x00000007);
11203   negl(tmp1);
11204   addl(tmp1, in2);
11205   addl(tmp1, in1);
11206 
11207   BIND(L_wordByWord);
11208   cmpl(in1, tmp1);
11209   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11210     crc32(in_out, Address(in1,0), 4);
11211     addl(in1, 4);
11212     jmp(L_wordByWord);
11213 
11214   BIND(L_byteByByteProlog);
11215   andl(in2, 0x00000007);
11216   movl(tmp2, 1);
11217 
11218   BIND(L_byteByByte);
11219   cmpl(tmp2, in2);
11220   jccb(Assembler::greater, L_exit);
11221     movb(tmp1, Address(in1, 0));
11222     crc32(in_out, tmp1, 1);
11223     incl(in1);
11224     incl(tmp2);
11225     jmp(L_byteByByte);
11226 
11227   BIND(L_exit);
11228 }
11229 #endif // LP64
11230 #undef BIND
11231 #undef BLOCK_COMMENT
11232 
11233 // Compress char[] array to byte[].
11234 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
11235 //   @HotSpotIntrinsicCandidate
11236 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
11237 //     for (int i = 0; i < len; i++) {
11238 //       int c = src[srcOff++];
11239 //       if (c >>> 8 != 0) {
11240 //         return 0;
11241 //       }
11242 //       dst[dstOff++] = (byte)c;
11243 //     }
11244 //     return len;
11245 //   }
11246 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
11247   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
11248   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
11249   Register tmp5, Register result) {
11250   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
11251 
11252   // rsi: src
11253   // rdi: dst
11254   // rdx: len
11255   // rcx: tmp5
11256   // rax: result
11257 
11258   // rsi holds start addr of source char[] to be compressed
11259   // rdi holds start addr of destination byte[]
11260   // rdx holds length
11261 
11262   assert(len != result, "");
11263 
11264   // save length for return
11265   push(len);
11266 
11267   if ((UseAVX > 2) && // AVX512
11268     VM_Version::supports_avx512vlbw() &&
11269     VM_Version::supports_bmi2()) {
11270 
11271     set_vector_masking();  // opening of the stub context for programming mask registers
11272 
11273     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
11274 
11275     // alignement
11276     Label post_alignement;
11277 
11278     // if length of the string is less than 16, handle it in an old fashioned
11279     // way
11280     testl(len, -32);
11281     jcc(Assembler::zero, below_threshold);
11282 
11283     // First check whether a character is compressable ( <= 0xFF).
11284     // Create mask to test for Unicode chars inside zmm vector
11285     movl(result, 0x00FF);
11286     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
11287 
11288     // Save k1
11289     kmovql(k3, k1);
11290 
11291     testl(len, -64);
11292     jcc(Assembler::zero, post_alignement);
11293 
11294     movl(tmp5, dst);
11295     andl(tmp5, (32 - 1));
11296     negl(tmp5);
11297     andl(tmp5, (32 - 1));
11298 
11299     // bail out when there is nothing to be done
11300     testl(tmp5, 0xFFFFFFFF);
11301     jcc(Assembler::zero, post_alignement);
11302 
11303     // ~(~0 << len), where len is the # of remaining elements to process
11304     movl(result, 0xFFFFFFFF);
11305     shlxl(result, result, tmp5);
11306     notl(result);
11307     kmovdl(k1, result);
11308 
11309     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11310     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11311     ktestd(k2, k1);
11312     jcc(Assembler::carryClear, restore_k1_return_zero);
11313 
11314     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11315 
11316     addptr(src, tmp5);
11317     addptr(src, tmp5);
11318     addptr(dst, tmp5);
11319     subl(len, tmp5);
11320 
11321     bind(post_alignement);
11322     // end of alignement
11323 
11324     movl(tmp5, len);
11325     andl(tmp5, (32 - 1));    // tail count (in chars)
11326     andl(len, ~(32 - 1));    // vector count (in chars)
11327     jcc(Assembler::zero, copy_loop_tail);
11328 
11329     lea(src, Address(src, len, Address::times_2));
11330     lea(dst, Address(dst, len, Address::times_1));
11331     negptr(len);
11332 
11333     bind(copy_32_loop);
11334     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11335     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11336     kortestdl(k2, k2);
11337     jcc(Assembler::carryClear, restore_k1_return_zero);
11338 
11339     // All elements in current processed chunk are valid candidates for
11340     // compression. Write a truncated byte elements to the memory.
11341     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11342     addptr(len, 32);
11343     jcc(Assembler::notZero, copy_32_loop);
11344 
11345     bind(copy_loop_tail);
11346     // bail out when there is nothing to be done
11347     testl(tmp5, 0xFFFFFFFF);
11348     // Restore k1
11349     kmovql(k1, k3);
11350     jcc(Assembler::zero, return_length);
11351 
11352     movl(len, tmp5);
11353 
11354     // ~(~0 << len), where len is the # of remaining elements to process
11355     movl(result, 0xFFFFFFFF);
11356     shlxl(result, result, len);
11357     notl(result);
11358 
11359     kmovdl(k1, result);
11360 
11361     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11362     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11363     ktestd(k2, k1);
11364     jcc(Assembler::carryClear, restore_k1_return_zero);
11365 
11366     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11367     // Restore k1
11368     kmovql(k1, k3);
11369     jmp(return_length);
11370 
11371     bind(restore_k1_return_zero);
11372     // Restore k1
11373     kmovql(k1, k3);
11374     jmp(return_zero);
11375 
11376     clear_vector_masking();   // closing of the stub context for programming mask registers
11377   }
11378   if (UseSSE42Intrinsics) {
11379     Label copy_32_loop, copy_16, copy_tail;
11380 
11381     bind(below_threshold);
11382 
11383     movl(result, len);
11384 
11385     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11386 
11387     // vectored compression
11388     andl(len, 0xfffffff0);    // vector count (in chars)
11389     andl(result, 0x0000000f);    // tail count (in chars)
11390     testl(len, len);
11391     jccb(Assembler::zero, copy_16);
11392 
11393     // compress 16 chars per iter
11394     movdl(tmp1Reg, tmp5);
11395     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11396     pxor(tmp4Reg, tmp4Reg);
11397 
11398     lea(src, Address(src, len, Address::times_2));
11399     lea(dst, Address(dst, len, Address::times_1));
11400     negptr(len);
11401 
11402     bind(copy_32_loop);
11403     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11404     por(tmp4Reg, tmp2Reg);
11405     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11406     por(tmp4Reg, tmp3Reg);
11407     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11408     jcc(Assembler::notZero, return_zero);
11409     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11410     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11411     addptr(len, 16);
11412     jcc(Assembler::notZero, copy_32_loop);
11413 
11414     // compress next vector of 8 chars (if any)
11415     bind(copy_16);
11416     movl(len, result);
11417     andl(len, 0xfffffff8);    // vector count (in chars)
11418     andl(result, 0x00000007);    // tail count (in chars)
11419     testl(len, len);
11420     jccb(Assembler::zero, copy_tail);
11421 
11422     movdl(tmp1Reg, tmp5);
11423     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11424     pxor(tmp3Reg, tmp3Reg);
11425 
11426     movdqu(tmp2Reg, Address(src, 0));
11427     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11428     jccb(Assembler::notZero, return_zero);
11429     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11430     movq(Address(dst, 0), tmp2Reg);
11431     addptr(src, 16);
11432     addptr(dst, 8);
11433 
11434     bind(copy_tail);
11435     movl(len, result);
11436   }
11437   // compress 1 char per iter
11438   testl(len, len);
11439   jccb(Assembler::zero, return_length);
11440   lea(src, Address(src, len, Address::times_2));
11441   lea(dst, Address(dst, len, Address::times_1));
11442   negptr(len);
11443 
11444   bind(copy_chars_loop);
11445   load_unsigned_short(result, Address(src, len, Address::times_2));
11446   testl(result, 0xff00);      // check if Unicode char
11447   jccb(Assembler::notZero, return_zero);
11448   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11449   increment(len);
11450   jcc(Assembler::notZero, copy_chars_loop);
11451 
11452   // if compression succeeded, return length
11453   bind(return_length);
11454   pop(result);
11455   jmpb(done);
11456 
11457   // if compression failed, return 0
11458   bind(return_zero);
11459   xorl(result, result);
11460   addptr(rsp, wordSize);
11461 
11462   bind(done);
11463 }
11464 
11465 // Inflate byte[] array to char[].
11466 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11467 //   @HotSpotIntrinsicCandidate
11468 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11469 //     for (int i = 0; i < len; i++) {
11470 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11471 //     }
11472 //   }
11473 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11474   XMMRegister tmp1, Register tmp2) {
11475   Label copy_chars_loop, done, below_threshold;
11476   // rsi: src
11477   // rdi: dst
11478   // rdx: len
11479   // rcx: tmp2
11480 
11481   // rsi holds start addr of source byte[] to be inflated
11482   // rdi holds start addr of destination char[]
11483   // rdx holds length
11484   assert_different_registers(src, dst, len, tmp2);
11485 
11486   if ((UseAVX > 2) && // AVX512
11487     VM_Version::supports_avx512vlbw() &&
11488     VM_Version::supports_bmi2()) {
11489 
11490     set_vector_masking();  // opening of the stub context for programming mask registers
11491 
11492     Label copy_32_loop, copy_tail;
11493     Register tmp3_aliased = len;
11494 
11495     // if length of the string is less than 16, handle it in an old fashioned
11496     // way
11497     testl(len, -16);
11498     jcc(Assembler::zero, below_threshold);
11499 
11500     // In order to use only one arithmetic operation for the main loop we use
11501     // this pre-calculation
11502     movl(tmp2, len);
11503     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11504     andl(len, -32);     // vector count
11505     jccb(Assembler::zero, copy_tail);
11506 
11507     lea(src, Address(src, len, Address::times_1));
11508     lea(dst, Address(dst, len, Address::times_2));
11509     negptr(len);
11510 
11511 
11512     // inflate 32 chars per iter
11513     bind(copy_32_loop);
11514     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11515     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11516     addptr(len, 32);
11517     jcc(Assembler::notZero, copy_32_loop);
11518 
11519     bind(copy_tail);
11520     // bail out when there is nothing to be done
11521     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11522     jcc(Assembler::zero, done);
11523 
11524     // Save k1
11525     kmovql(k2, k1);
11526 
11527     // ~(~0 << length), where length is the # of remaining elements to process
11528     movl(tmp3_aliased, -1);
11529     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11530     notl(tmp3_aliased);
11531     kmovdl(k1, tmp3_aliased);
11532     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11533     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11534 
11535     // Restore k1
11536     kmovql(k1, k2);
11537     jmp(done);
11538 
11539     clear_vector_masking();   // closing of the stub context for programming mask registers
11540   }
11541   if (UseSSE42Intrinsics) {
11542     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11543 
11544     movl(tmp2, len);
11545 
11546     if (UseAVX > 1) {
11547       andl(tmp2, (16 - 1));
11548       andl(len, -16);
11549       jccb(Assembler::zero, copy_new_tail);
11550     } else {
11551       andl(tmp2, 0x00000007);   // tail count (in chars)
11552       andl(len, 0xfffffff8);    // vector count (in chars)
11553       jccb(Assembler::zero, copy_tail);
11554     }
11555 
11556     // vectored inflation
11557     lea(src, Address(src, len, Address::times_1));
11558     lea(dst, Address(dst, len, Address::times_2));
11559     negptr(len);
11560 
11561     if (UseAVX > 1) {
11562       bind(copy_16_loop);
11563       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11564       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11565       addptr(len, 16);
11566       jcc(Assembler::notZero, copy_16_loop);
11567 
11568       bind(below_threshold);
11569       bind(copy_new_tail);
11570       if ((UseAVX > 2) &&
11571         VM_Version::supports_avx512vlbw() &&
11572         VM_Version::supports_bmi2()) {
11573         movl(tmp2, len);
11574       } else {
11575         movl(len, tmp2);
11576       }
11577       andl(tmp2, 0x00000007);
11578       andl(len, 0xFFFFFFF8);
11579       jccb(Assembler::zero, copy_tail);
11580 
11581       pmovzxbw(tmp1, Address(src, 0));
11582       movdqu(Address(dst, 0), tmp1);
11583       addptr(src, 8);
11584       addptr(dst, 2 * 8);
11585 
11586       jmp(copy_tail, true);
11587     }
11588 
11589     // inflate 8 chars per iter
11590     bind(copy_8_loop);
11591     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11592     movdqu(Address(dst, len, Address::times_2), tmp1);
11593     addptr(len, 8);
11594     jcc(Assembler::notZero, copy_8_loop);
11595 
11596     bind(copy_tail);
11597     movl(len, tmp2);
11598 
11599     cmpl(len, 4);
11600     jccb(Assembler::less, copy_bytes);
11601 
11602     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11603     pmovzxbw(tmp1, tmp1);
11604     movq(Address(dst, 0), tmp1);
11605     subptr(len, 4);
11606     addptr(src, 4);
11607     addptr(dst, 8);
11608 
11609     bind(copy_bytes);
11610   }
11611   testl(len, len);
11612   jccb(Assembler::zero, done);
11613   lea(src, Address(src, len, Address::times_1));
11614   lea(dst, Address(dst, len, Address::times_2));
11615   negptr(len);
11616 
11617   // inflate 1 char per iter
11618   bind(copy_chars_loop);
11619   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11620   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11621   increment(len);
11622   jcc(Assembler::notZero, copy_chars_loop);
11623 
11624   bind(done);
11625 }
11626 
11627 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11628   switch (cond) {
11629     // Note some conditions are synonyms for others
11630     case Assembler::zero:         return Assembler::notZero;
11631     case Assembler::notZero:      return Assembler::zero;
11632     case Assembler::less:         return Assembler::greaterEqual;
11633     case Assembler::lessEqual:    return Assembler::greater;
11634     case Assembler::greater:      return Assembler::lessEqual;
11635     case Assembler::greaterEqual: return Assembler::less;
11636     case Assembler::below:        return Assembler::aboveEqual;
11637     case Assembler::belowEqual:   return Assembler::above;
11638     case Assembler::above:        return Assembler::belowEqual;
11639     case Assembler::aboveEqual:   return Assembler::below;
11640     case Assembler::overflow:     return Assembler::noOverflow;
11641     case Assembler::noOverflow:   return Assembler::overflow;
11642     case Assembler::negative:     return Assembler::positive;
11643     case Assembler::positive:     return Assembler::negative;
11644     case Assembler::parity:       return Assembler::noParity;
11645     case Assembler::noParity:     return Assembler::parity;
11646   }
11647   ShouldNotReachHere(); return Assembler::overflow;
11648 }
11649 
11650 SkipIfEqual::SkipIfEqual(
11651     MacroAssembler* masm, const bool* flag_addr, bool value) {
11652   _masm = masm;
11653   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11654   _masm->jcc(Assembler::equal, _label);
11655 }
11656 
11657 SkipIfEqual::~SkipIfEqual() {
11658   _masm->bind(_label);
11659 }
11660 
11661 // 32-bit Windows has its own fast-path implementation
11662 // of get_thread
11663 #if !defined(WIN32) || defined(_LP64)
11664 
11665 // This is simply a call to Thread::current()
11666 void MacroAssembler::get_thread(Register thread) {
11667   if (thread != rax) {
11668     push(rax);
11669   }
11670   LP64_ONLY(push(rdi);)
11671   LP64_ONLY(push(rsi);)
11672   push(rdx);
11673   push(rcx);
11674 #ifdef _LP64
11675   push(r8);
11676   push(r9);
11677   push(r10);
11678   push(r11);
11679 #endif
11680 
11681   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11682 
11683 #ifdef _LP64
11684   pop(r11);
11685   pop(r10);
11686   pop(r9);
11687   pop(r8);
11688 #endif
11689   pop(rcx);
11690   pop(rdx);
11691   LP64_ONLY(pop(rsi);)
11692   LP64_ONLY(pop(rdi);)
11693   if (thread != rax) {
11694     mov(thread, rax);
11695     pop(rax);
11696   }
11697 }
11698 
11699 #endif
11700 
11701 void MacroAssembler::save_vector_registers() {
11702   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11703   if (UseAVX > 2) {
11704     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11705   }
11706 
11707   if (UseSSE == 1)  {
11708     subptr(rsp, sizeof(jdouble)*8);
11709     for (int n = 0; n < 8; n++) {
11710       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11711     }
11712   } else if (UseSSE >= 2)  {
11713     if (UseAVX > 2) {
11714       push(rbx);
11715       movl(rbx, 0xffff);
11716       kmovwl(k1, rbx);
11717       pop(rbx);
11718     }
11719 #ifdef COMPILER2
11720     if (MaxVectorSize > 16) {
11721       if(UseAVX > 2) {
11722         // Save upper half of ZMM registers
11723         subptr(rsp, 32*num_xmm_regs);
11724         for (int n = 0; n < num_xmm_regs; n++) {
11725           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11726         }
11727       }
11728       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11729       // Save upper half of YMM registers
11730       subptr(rsp, 16*num_xmm_regs);
11731       for (int n = 0; n < num_xmm_regs; n++) {
11732         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11733       }
11734     }
11735 #endif
11736     // Save whole 128bit (16 bytes) XMM registers
11737     subptr(rsp, 16*num_xmm_regs);
11738 #ifdef _LP64
11739     if (VM_Version::supports_evex()) {
11740       for (int n = 0; n < num_xmm_regs; n++) {
11741         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11742       }
11743     } else {
11744       for (int n = 0; n < num_xmm_regs; n++) {
11745         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11746       }
11747     }
11748 #else
11749     for (int n = 0; n < num_xmm_regs; n++) {
11750       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11751     }
11752 #endif
11753   }
11754 }
11755 
11756 void MacroAssembler::restore_vector_registers() {
11757   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11758   if (UseAVX > 2) {
11759     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11760   }
11761   if (UseSSE == 1)  {
11762     for (int n = 0; n < 8; n++) {
11763       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11764     }
11765     addptr(rsp, sizeof(jdouble)*8);
11766   } else if (UseSSE >= 2)  {
11767     // Restore whole 128bit (16 bytes) XMM registers
11768 #ifdef _LP64
11769   if (VM_Version::supports_evex()) {
11770     for (int n = 0; n < num_xmm_regs; n++) {
11771       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11772     }
11773   } else {
11774     for (int n = 0; n < num_xmm_regs; n++) {
11775       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11776     }
11777   }
11778 #else
11779   for (int n = 0; n < num_xmm_regs; n++) {
11780     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11781   }
11782 #endif
11783     addptr(rsp, 16*num_xmm_regs);
11784 
11785 #ifdef COMPILER2
11786     if (MaxVectorSize > 16) {
11787       // Restore upper half of YMM registers.
11788       for (int n = 0; n < num_xmm_regs; n++) {
11789         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11790       }
11791       addptr(rsp, 16*num_xmm_regs);
11792       if(UseAVX > 2) {
11793         for (int n = 0; n < num_xmm_regs; n++) {
11794           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11795         }
11796         addptr(rsp, 32*num_xmm_regs);
11797       }
11798     }
11799 #endif
11800   }
11801 }
11802 
11803 void MacroAssembler::cmpoops(Register src1, Register src2) {
11804   cmpptr(src1, src2);
11805   oopDesc::bs()->asm_acmp_barrier(this, src1, src2);
11806 }
11807 
11808 void MacroAssembler::cmpoops(Register src1, Address src2) {
11809   cmpptr(src1, src2);
11810   if (UseShenandoahGC && ShenandoahAcmpBarrier) {
11811     Label done;
11812     jccb(Assembler::equal, done);
11813     movptr(rscratch2, src2);
11814     oopDesc::bs()->interpreter_read_barrier(this, src1);
11815     oopDesc::bs()->interpreter_read_barrier(this, rscratch2);
11816     cmpptr(src1, rscratch2);
11817     bind(done);
11818   }
11819 }