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/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "runtime/thread.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #include "gc/shenandoah/shenandoahConnectionMatrix.inline.hpp"
  49 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  50 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  51 #endif // INCLUDE_ALL_GCS
  52 #include "crc32c.h"
  53 #ifdef COMPILER2
  54 #include "opto/intrinsicnode.hpp"
  55 #endif
  56 
  57 #ifdef PRODUCT
  58 #define BLOCK_COMMENT(str) /* nothing */
  59 #define STOP(error) stop(error)
  60 #else
  61 #define BLOCK_COMMENT(str) block_comment(str)
  62 #define STOP(error) block_comment(error); stop(error)
  63 #endif
  64 
  65 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  66 
  67 #ifdef ASSERT
  68 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  69 #endif
  70 
  71 static Assembler::Condition reverse[] = {
  72     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  73     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  74     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  75     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  76     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  77     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  78     Assembler::above          /* belowEqual    = 0x6 */ ,
  79     Assembler::belowEqual     /* above         = 0x7 */ ,
  80     Assembler::positive       /* negative      = 0x8 */ ,
  81     Assembler::negative       /* positive      = 0x9 */ ,
  82     Assembler::noParity       /* parity        = 0xa */ ,
  83     Assembler::parity         /* noParity      = 0xb */ ,
  84     Assembler::greaterEqual   /* less          = 0xc */ ,
  85     Assembler::less           /* greaterEqual  = 0xd */ ,
  86     Assembler::greater        /* lessEqual     = 0xe */ ,
  87     Assembler::lessEqual      /* greater       = 0xf, */
  88 
  89 };
  90 
  91 
  92 // Implementation of MacroAssembler
  93 
  94 // First all the versions that have distinct versions depending on 32/64 bit
  95 // Unless the difference is trivial (1 line or so).
  96 
  97 #ifndef _LP64
  98 
  99 // 32bit versions
 100 
 101 Address MacroAssembler::as_Address(AddressLiteral adr) {
 102   return Address(adr.target(), adr.rspec());
 103 }
 104 
 105 Address MacroAssembler::as_Address(ArrayAddress adr) {
 106   return Address::make_array(adr);
 107 }
 108 
 109 void MacroAssembler::call_VM_leaf_base(address entry_point,
 110                                        int number_of_arguments) {
 111   call(RuntimeAddress(entry_point));
 112   increment(rsp, number_of_arguments * wordSize);
 113 }
 114 
 115 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 116   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 117 }
 118 
 119 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 120   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 121 }
 122 
 123 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 124   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 125 }
 126 
 127 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 128   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 129 }
 130 
 131 void MacroAssembler::extend_sign(Register hi, Register lo) {
 132   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 133   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 134     cdql();
 135   } else {
 136     movl(hi, lo);
 137     sarl(hi, 31);
 138   }
 139 }
 140 
 141 void MacroAssembler::jC2(Register tmp, Label& L) {
 142   // set parity bit if FPU flag C2 is set (via rax)
 143   save_rax(tmp);
 144   fwait(); fnstsw_ax();
 145   sahf();
 146   restore_rax(tmp);
 147   // branch
 148   jcc(Assembler::parity, L);
 149 }
 150 
 151 void MacroAssembler::jnC2(Register tmp, Label& L) {
 152   // set parity bit if FPU flag C2 is set (via rax)
 153   save_rax(tmp);
 154   fwait(); fnstsw_ax();
 155   sahf();
 156   restore_rax(tmp);
 157   // branch
 158   jcc(Assembler::noParity, L);
 159 }
 160 
 161 // 32bit can do a case table jump in one instruction but we no longer allow the base
 162 // to be installed in the Address class
 163 void MacroAssembler::jump(ArrayAddress entry) {
 164   jmp(as_Address(entry));
 165 }
 166 
 167 // Note: y_lo will be destroyed
 168 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 169   // Long compare for Java (semantics as described in JVM spec.)
 170   Label high, low, done;
 171 
 172   cmpl(x_hi, y_hi);
 173   jcc(Assembler::less, low);
 174   jcc(Assembler::greater, high);
 175   // x_hi is the return register
 176   xorl(x_hi, x_hi);
 177   cmpl(x_lo, y_lo);
 178   jcc(Assembler::below, low);
 179   jcc(Assembler::equal, done);
 180 
 181   bind(high);
 182   xorl(x_hi, x_hi);
 183   increment(x_hi);
 184   jmp(done);
 185 
 186   bind(low);
 187   xorl(x_hi, x_hi);
 188   decrementl(x_hi);
 189 
 190   bind(done);
 191 }
 192 
 193 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 194     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 195 }
 196 
 197 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 198   // leal(dst, as_Address(adr));
 199   // see note in movl as to why we must use a move
 200   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 201 }
 202 
 203 void MacroAssembler::leave() {
 204   mov(rsp, rbp);
 205   pop(rbp);
 206 }
 207 
 208 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 209   // Multiplication of two Java long values stored on the stack
 210   // as illustrated below. Result is in rdx:rax.
 211   //
 212   // rsp ---> [  ??  ] \               \
 213   //            ....    | y_rsp_offset  |
 214   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 215   //          [ y_hi ]                  | (in bytes)
 216   //            ....                    |
 217   //          [ x_lo ]                 /
 218   //          [ x_hi ]
 219   //            ....
 220   //
 221   // Basic idea: lo(result) = lo(x_lo * y_lo)
 222   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 223   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 224   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 225   Label quick;
 226   // load x_hi, y_hi and check if quick
 227   // multiplication is possible
 228   movl(rbx, x_hi);
 229   movl(rcx, y_hi);
 230   movl(rax, rbx);
 231   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 232   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 233   // do full multiplication
 234   // 1st step
 235   mull(y_lo);                                    // x_hi * y_lo
 236   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 237   // 2nd step
 238   movl(rax, x_lo);
 239   mull(rcx);                                     // x_lo * y_hi
 240   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 241   // 3rd step
 242   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 243   movl(rax, x_lo);
 244   mull(y_lo);                                    // x_lo * y_lo
 245   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 246 }
 247 
 248 void MacroAssembler::lneg(Register hi, Register lo) {
 249   negl(lo);
 250   adcl(hi, 0);
 251   negl(hi);
 252 }
 253 
 254 void MacroAssembler::lshl(Register hi, Register lo) {
 255   // Java shift left long support (semantics as described in JVM spec., p.305)
 256   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 257   // shift value is in rcx !
 258   assert(hi != rcx, "must not use rcx");
 259   assert(lo != rcx, "must not use rcx");
 260   const Register s = rcx;                        // shift count
 261   const int      n = BitsPerWord;
 262   Label L;
 263   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 264   cmpl(s, n);                                    // if (s < n)
 265   jcc(Assembler::less, L);                       // else (s >= n)
 266   movl(hi, lo);                                  // x := x << n
 267   xorl(lo, lo);
 268   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 269   bind(L);                                       // s (mod n) < n
 270   shldl(hi, lo);                                 // x := x << s
 271   shll(lo);
 272 }
 273 
 274 
 275 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 276   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 277   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 278   assert(hi != rcx, "must not use rcx");
 279   assert(lo != rcx, "must not use rcx");
 280   const Register s = rcx;                        // shift count
 281   const int      n = BitsPerWord;
 282   Label L;
 283   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 284   cmpl(s, n);                                    // if (s < n)
 285   jcc(Assembler::less, L);                       // else (s >= n)
 286   movl(lo, hi);                                  // x := x >> n
 287   if (sign_extension) sarl(hi, 31);
 288   else                xorl(hi, hi);
 289   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 290   bind(L);                                       // s (mod n) < n
 291   shrdl(lo, hi);                                 // x := x >> s
 292   if (sign_extension) sarl(hi);
 293   else                shrl(hi);
 294 }
 295 
 296 void MacroAssembler::movoop(Register dst, jobject obj) {
 297   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 298 }
 299 
 300 void MacroAssembler::movoop(Address dst, jobject obj) {
 301   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 302 }
 303 
 304 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 305   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 309   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 310 }
 311 
 312 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 313   // scratch register is not used,
 314   // it is defined to match parameters of 64-bit version of this method.
 315   if (src.is_lval()) {
 316     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 317   } else {
 318     movl(dst, as_Address(src));
 319   }
 320 }
 321 
 322 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 323   movl(as_Address(dst), src);
 324 }
 325 
 326 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 327   movl(dst, as_Address(src));
 328 }
 329 
 330 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 331 void MacroAssembler::movptr(Address dst, intptr_t src) {
 332   movl(dst, src);
 333 }
 334 
 335 
 336 void MacroAssembler::pop_callee_saved_registers() {
 337   pop(rcx);
 338   pop(rdx);
 339   pop(rdi);
 340   pop(rsi);
 341 }
 342 
 343 void MacroAssembler::pop_fTOS() {
 344   fld_d(Address(rsp, 0));
 345   addl(rsp, 2 * wordSize);
 346 }
 347 
 348 void MacroAssembler::push_callee_saved_registers() {
 349   push(rsi);
 350   push(rdi);
 351   push(rdx);
 352   push(rcx);
 353 }
 354 
 355 void MacroAssembler::push_fTOS() {
 356   subl(rsp, 2 * wordSize);
 357   fstp_d(Address(rsp, 0));
 358 }
 359 
 360 
 361 void MacroAssembler::pushoop(jobject obj) {
 362   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 363 }
 364 
 365 void MacroAssembler::pushklass(Metadata* obj) {
 366   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 367 }
 368 
 369 void MacroAssembler::pushptr(AddressLiteral src) {
 370   if (src.is_lval()) {
 371     push_literal32((int32_t)src.target(), src.rspec());
 372   } else {
 373     pushl(as_Address(src));
 374   }
 375 }
 376 
 377 void MacroAssembler::set_word_if_not_zero(Register dst) {
 378   xorl(dst, dst);
 379   set_byte_if_not_zero(dst);
 380 }
 381 
 382 static void pass_arg0(MacroAssembler* masm, Register arg) {
 383   masm->push(arg);
 384 }
 385 
 386 static void pass_arg1(MacroAssembler* masm, Register arg) {
 387   masm->push(arg);
 388 }
 389 
 390 static void pass_arg2(MacroAssembler* masm, Register arg) {
 391   masm->push(arg);
 392 }
 393 
 394 static void pass_arg3(MacroAssembler* masm, Register arg) {
 395   masm->push(arg);
 396 }
 397 
 398 #ifndef PRODUCT
 399 extern "C" void findpc(intptr_t x);
 400 #endif
 401 
 402 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 403   // In order to get locks to work, we need to fake a in_VM state
 404   JavaThread* thread = JavaThread::current();
 405   JavaThreadState saved_state = thread->thread_state();
 406   thread->set_thread_state(_thread_in_vm);
 407   if (ShowMessageBoxOnError) {
 408     JavaThread* thread = JavaThread::current();
 409     JavaThreadState saved_state = thread->thread_state();
 410     thread->set_thread_state(_thread_in_vm);
 411     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 412       ttyLocker ttyl;
 413       BytecodeCounter::print();
 414     }
 415     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 416     // This is the value of eip which points to where verify_oop will return.
 417     if (os::message_box(msg, "Execution stopped, print registers?")) {
 418       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 419       BREAKPOINT;
 420     }
 421   } else {
 422     ttyLocker ttyl;
 423     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 424   }
 425   // Don't assert holding the ttyLock
 426     assert(false, "DEBUG MESSAGE: %s", msg);
 427   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 428 }
 429 
 430 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 431   ttyLocker ttyl;
 432   FlagSetting fs(Debugging, true);
 433   tty->print_cr("eip = 0x%08x", eip);
 434 #ifndef PRODUCT
 435   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 436     tty->cr();
 437     findpc(eip);
 438     tty->cr();
 439   }
 440 #endif
 441 #define PRINT_REG(rax) \
 442   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 443   PRINT_REG(rax);
 444   PRINT_REG(rbx);
 445   PRINT_REG(rcx);
 446   PRINT_REG(rdx);
 447   PRINT_REG(rdi);
 448   PRINT_REG(rsi);
 449   PRINT_REG(rbp);
 450   PRINT_REG(rsp);
 451 #undef PRINT_REG
 452   // Print some words near top of staack.
 453   int* dump_sp = (int*) rsp;
 454   for (int col1 = 0; col1 < 8; col1++) {
 455     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 456     os::print_location(tty, *dump_sp++);
 457   }
 458   for (int row = 0; row < 16; row++) {
 459     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 460     for (int col = 0; col < 8; col++) {
 461       tty->print(" 0x%08x", *dump_sp++);
 462     }
 463     tty->cr();
 464   }
 465   // Print some instructions around pc:
 466   Disassembler::decode((address)eip-64, (address)eip);
 467   tty->print_cr("--------");
 468   Disassembler::decode((address)eip, (address)eip+32);
 469 }
 470 
 471 void MacroAssembler::stop(const char* msg) {
 472   ExternalAddress message((address)msg);
 473   // push address of message
 474   pushptr(message.addr());
 475   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 476   pusha();                                            // push registers
 477   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 478   hlt();
 479 }
 480 
 481 void MacroAssembler::warn(const char* msg) {
 482   push_CPU_state();
 483 
 484   ExternalAddress message((address) msg);
 485   // push address of message
 486   pushptr(message.addr());
 487 
 488   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 489   addl(rsp, wordSize);       // discard argument
 490   pop_CPU_state();
 491 }
 492 
 493 void MacroAssembler::print_state() {
 494   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 495   pusha();                                            // push registers
 496 
 497   push_CPU_state();
 498   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 499   pop_CPU_state();
 500 
 501   popa();
 502   addl(rsp, wordSize);
 503 }
 504 
 505 #else // _LP64
 506 
 507 // 64 bit versions
 508 
 509 Address MacroAssembler::as_Address(AddressLiteral adr) {
 510   // amd64 always does this as a pc-rel
 511   // we can be absolute or disp based on the instruction type
 512   // jmp/call are displacements others are absolute
 513   assert(!adr.is_lval(), "must be rval");
 514   assert(reachable(adr), "must be");
 515   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 516 
 517 }
 518 
 519 Address MacroAssembler::as_Address(ArrayAddress adr) {
 520   AddressLiteral base = adr.base();
 521   lea(rscratch1, base);
 522   Address index = adr.index();
 523   assert(index._disp == 0, "must not have disp"); // maybe it can?
 524   Address array(rscratch1, index._index, index._scale, index._disp);
 525   return array;
 526 }
 527 
 528 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 529   Label L, E;
 530 
 531 #ifdef _WIN64
 532   // Windows always allocates space for it's register args
 533   assert(num_args <= 4, "only register arguments supported");
 534   subq(rsp,  frame::arg_reg_save_area_bytes);
 535 #endif
 536 
 537   // Align stack if necessary
 538   testl(rsp, 15);
 539   jcc(Assembler::zero, L);
 540 
 541   subq(rsp, 8);
 542   {
 543     call(RuntimeAddress(entry_point));
 544   }
 545   addq(rsp, 8);
 546   jmp(E);
 547 
 548   bind(L);
 549   {
 550     call(RuntimeAddress(entry_point));
 551   }
 552 
 553   bind(E);
 554 
 555 #ifdef _WIN64
 556   // restore stack pointer
 557   addq(rsp, frame::arg_reg_save_area_bytes);
 558 #endif
 559 
 560 }
 561 
 562 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 563   assert(!src2.is_lval(), "should use cmpptr");
 564 
 565   if (reachable(src2)) {
 566     cmpq(src1, as_Address(src2));
 567   } else {
 568     lea(rscratch1, src2);
 569     Assembler::cmpq(src1, Address(rscratch1, 0));
 570   }
 571 }
 572 
 573 int MacroAssembler::corrected_idivq(Register reg) {
 574   // Full implementation of Java ldiv and lrem; checks for special
 575   // case as described in JVM spec., p.243 & p.271.  The function
 576   // returns the (pc) offset of the idivl instruction - may be needed
 577   // for implicit exceptions.
 578   //
 579   //         normal case                           special case
 580   //
 581   // input : rax: dividend                         min_long
 582   //         reg: divisor   (may not be eax/edx)   -1
 583   //
 584   // output: rax: quotient  (= rax idiv reg)       min_long
 585   //         rdx: remainder (= rax irem reg)       0
 586   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 587   static const int64_t min_long = 0x8000000000000000;
 588   Label normal_case, special_case;
 589 
 590   // check for special case
 591   cmp64(rax, ExternalAddress((address) &min_long));
 592   jcc(Assembler::notEqual, normal_case);
 593   xorl(rdx, rdx); // prepare rdx for possible special case (where
 594                   // remainder = 0)
 595   cmpq(reg, -1);
 596   jcc(Assembler::equal, special_case);
 597 
 598   // handle normal case
 599   bind(normal_case);
 600   cdqq();
 601   int idivq_offset = offset();
 602   idivq(reg);
 603 
 604   // normal and special case exit
 605   bind(special_case);
 606 
 607   return idivq_offset;
 608 }
 609 
 610 void MacroAssembler::decrementq(Register reg, int value) {
 611   if (value == min_jint) { subq(reg, value); return; }
 612   if (value <  0) { incrementq(reg, -value); return; }
 613   if (value == 0) {                        ; return; }
 614   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 615   /* else */      { subq(reg, value)       ; return; }
 616 }
 617 
 618 void MacroAssembler::decrementq(Address dst, int value) {
 619   if (value == min_jint) { subq(dst, value); return; }
 620   if (value <  0) { incrementq(dst, -value); return; }
 621   if (value == 0) {                        ; return; }
 622   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 623   /* else */      { subq(dst, value)       ; return; }
 624 }
 625 
 626 void MacroAssembler::incrementq(AddressLiteral dst) {
 627   if (reachable(dst)) {
 628     incrementq(as_Address(dst));
 629   } else {
 630     lea(rscratch1, dst);
 631     incrementq(Address(rscratch1, 0));
 632   }
 633 }
 634 
 635 void MacroAssembler::incrementq(Register reg, int value) {
 636   if (value == min_jint) { addq(reg, value); return; }
 637   if (value <  0) { decrementq(reg, -value); return; }
 638   if (value == 0) {                        ; return; }
 639   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 640   /* else */      { addq(reg, value)       ; return; }
 641 }
 642 
 643 void MacroAssembler::incrementq(Address dst, int value) {
 644   if (value == min_jint) { addq(dst, value); return; }
 645   if (value <  0) { decrementq(dst, -value); return; }
 646   if (value == 0) {                        ; return; }
 647   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 648   /* else */      { addq(dst, value)       ; return; }
 649 }
 650 
 651 // 32bit can do a case table jump in one instruction but we no longer allow the base
 652 // to be installed in the Address class
 653 void MacroAssembler::jump(ArrayAddress entry) {
 654   lea(rscratch1, entry.base());
 655   Address dispatch = entry.index();
 656   assert(dispatch._base == noreg, "must be");
 657   dispatch._base = rscratch1;
 658   jmp(dispatch);
 659 }
 660 
 661 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 662   ShouldNotReachHere(); // 64bit doesn't use two regs
 663   cmpq(x_lo, y_lo);
 664 }
 665 
 666 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 667     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 668 }
 669 
 670 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 671   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 672   movptr(dst, rscratch1);
 673 }
 674 
 675 void MacroAssembler::leave() {
 676   // %%% is this really better? Why not on 32bit too?
 677   emit_int8((unsigned char)0xC9); // LEAVE
 678 }
 679 
 680 void MacroAssembler::lneg(Register hi, Register lo) {
 681   ShouldNotReachHere(); // 64bit doesn't use two regs
 682   negq(lo);
 683 }
 684 
 685 void MacroAssembler::movoop(Register dst, jobject obj) {
 686   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 687 }
 688 
 689 void MacroAssembler::movoop(Address dst, jobject obj) {
 690   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 691   movq(dst, rscratch1);
 692 }
 693 
 694 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 695   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 696 }
 697 
 698 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 699   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 700   movq(dst, rscratch1);
 701 }
 702 
 703 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 704   if (src.is_lval()) {
 705     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 706   } else {
 707     if (reachable(src)) {
 708       movq(dst, as_Address(src));
 709     } else {
 710       lea(scratch, src);
 711       movq(dst, Address(scratch, 0));
 712     }
 713   }
 714 }
 715 
 716 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 717   movq(as_Address(dst), src);
 718 }
 719 
 720 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 721   movq(dst, as_Address(src));
 722 }
 723 
 724 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 725 void MacroAssembler::movptr(Address dst, intptr_t src) {
 726   mov64(rscratch1, src);
 727   movq(dst, rscratch1);
 728 }
 729 
 730 // These are mostly for initializing NULL
 731 void MacroAssembler::movptr(Address dst, int32_t src) {
 732   movslq(dst, src);
 733 }
 734 
 735 void MacroAssembler::movptr(Register dst, int32_t src) {
 736   mov64(dst, (intptr_t)src);
 737 }
 738 
 739 void MacroAssembler::pushoop(jobject obj) {
 740   movoop(rscratch1, obj);
 741   push(rscratch1);
 742 }
 743 
 744 void MacroAssembler::pushklass(Metadata* obj) {
 745   mov_metadata(rscratch1, obj);
 746   push(rscratch1);
 747 }
 748 
 749 void MacroAssembler::pushptr(AddressLiteral src) {
 750   lea(rscratch1, src);
 751   if (src.is_lval()) {
 752     push(rscratch1);
 753   } else {
 754     pushq(Address(rscratch1, 0));
 755   }
 756 }
 757 
 758 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 759   // we must set sp to zero to clear frame
 760   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 761   // must clear fp, so that compiled frames are not confused; it is
 762   // possible that we need it only for debugging
 763   if (clear_fp) {
 764     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 765   }
 766 
 767   // Always clear the pc because it could have been set by make_walkable()
 768   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 769 }
 770 
 771 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 772                                          Register last_java_fp,
 773                                          address  last_java_pc) {
 774   // determine last_java_sp register
 775   if (!last_java_sp->is_valid()) {
 776     last_java_sp = rsp;
 777   }
 778 
 779   // last_java_fp is optional
 780   if (last_java_fp->is_valid()) {
 781     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 782            last_java_fp);
 783   }
 784 
 785   // last_java_pc is optional
 786   if (last_java_pc != NULL) {
 787     Address java_pc(r15_thread,
 788                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 789     lea(rscratch1, InternalAddress(last_java_pc));
 790     movptr(java_pc, rscratch1);
 791   }
 792 
 793   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 794 }
 795 
 796 static void pass_arg0(MacroAssembler* masm, Register arg) {
 797   if (c_rarg0 != arg ) {
 798     masm->mov(c_rarg0, arg);
 799   }
 800 }
 801 
 802 static void pass_arg1(MacroAssembler* masm, Register arg) {
 803   if (c_rarg1 != arg ) {
 804     masm->mov(c_rarg1, arg);
 805   }
 806 }
 807 
 808 static void pass_arg2(MacroAssembler* masm, Register arg) {
 809   if (c_rarg2 != arg ) {
 810     masm->mov(c_rarg2, arg);
 811   }
 812 }
 813 
 814 static void pass_arg3(MacroAssembler* masm, Register arg) {
 815   if (c_rarg3 != arg ) {
 816     masm->mov(c_rarg3, arg);
 817   }
 818 }
 819 
 820 void MacroAssembler::stop(const char* msg) {
 821   address rip = pc();
 822   pusha(); // get regs on stack
 823   lea(c_rarg0, ExternalAddress((address) msg));
 824   lea(c_rarg1, InternalAddress(rip));
 825   movq(c_rarg2, rsp); // pass pointer to regs array
 826   andq(rsp, -16); // align stack as required by ABI
 827   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 828   hlt();
 829 }
 830 
 831 void MacroAssembler::warn(const char* msg) {
 832   push(rbp);
 833   movq(rbp, rsp);
 834   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 835   push_CPU_state();   // keeps alignment at 16 bytes
 836   lea(c_rarg0, ExternalAddress((address) msg));
 837   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 838   pop_CPU_state();
 839   mov(rsp, rbp);
 840   pop(rbp);
 841 }
 842 
 843 void MacroAssembler::print_state() {
 844   address rip = pc();
 845   pusha();            // get regs on stack
 846   push(rbp);
 847   movq(rbp, rsp);
 848   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 849   push_CPU_state();   // keeps alignment at 16 bytes
 850 
 851   lea(c_rarg0, InternalAddress(rip));
 852   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 853   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 854 
 855   pop_CPU_state();
 856   mov(rsp, rbp);
 857   pop(rbp);
 858   popa();
 859 }
 860 
 861 #ifndef PRODUCT
 862 extern "C" void findpc(intptr_t x);
 863 #endif
 864 
 865 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 866   // In order to get locks to work, we need to fake a in_VM state
 867   if (ShowMessageBoxOnError) {
 868     JavaThread* thread = JavaThread::current();
 869     JavaThreadState saved_state = thread->thread_state();
 870     thread->set_thread_state(_thread_in_vm);
 871 #ifndef PRODUCT
 872     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 873       ttyLocker ttyl;
 874       BytecodeCounter::print();
 875     }
 876 #endif
 877     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 878     // XXX correct this offset for amd64
 879     // This is the value of eip which points to where verify_oop will return.
 880     if (os::message_box(msg, "Execution stopped, print registers?")) {
 881       print_state64(pc, regs);
 882       BREAKPOINT;
 883       assert(false, "start up GDB");
 884     }
 885     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 886   } else {
 887     ttyLocker ttyl;
 888     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 889                     msg);
 890     assert(false, "DEBUG MESSAGE: %s", msg);
 891   }
 892 }
 893 
 894 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 895   ttyLocker ttyl;
 896   FlagSetting fs(Debugging, true);
 897   tty->print_cr("rip = 0x%016lx", pc);
 898 #ifndef PRODUCT
 899   tty->cr();
 900   findpc(pc);
 901   tty->cr();
 902 #endif
 903 #define PRINT_REG(rax, value) \
 904   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 905   PRINT_REG(rax, regs[15]);
 906   PRINT_REG(rbx, regs[12]);
 907   PRINT_REG(rcx, regs[14]);
 908   PRINT_REG(rdx, regs[13]);
 909   PRINT_REG(rdi, regs[8]);
 910   PRINT_REG(rsi, regs[9]);
 911   PRINT_REG(rbp, regs[10]);
 912   PRINT_REG(rsp, regs[11]);
 913   PRINT_REG(r8 , regs[7]);
 914   PRINT_REG(r9 , regs[6]);
 915   PRINT_REG(r10, regs[5]);
 916   PRINT_REG(r11, regs[4]);
 917   PRINT_REG(r12, regs[3]);
 918   PRINT_REG(r13, regs[2]);
 919   PRINT_REG(r14, regs[1]);
 920   PRINT_REG(r15, regs[0]);
 921 #undef PRINT_REG
 922   // Print some words near top of staack.
 923   int64_t* rsp = (int64_t*) regs[11];
 924   int64_t* dump_sp = rsp;
 925   for (int col1 = 0; col1 < 8; col1++) {
 926     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 927     os::print_location(tty, *dump_sp++);
 928   }
 929   for (int row = 0; row < 25; row++) {
 930     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 931     for (int col = 0; col < 4; col++) {
 932       tty->print(" 0x%016lx", *dump_sp++);
 933     }
 934     tty->cr();
 935   }
 936   // Print some instructions around pc:
 937   Disassembler::decode((address)pc-64, (address)pc);
 938   tty->print_cr("--------");
 939   Disassembler::decode((address)pc, (address)pc+32);
 940 }
 941 
 942 #endif // _LP64
 943 
 944 // Now versions that are common to 32/64 bit
 945 
 946 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 947   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 948 }
 949 
 950 void MacroAssembler::addptr(Register dst, Register src) {
 951   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 952 }
 953 
 954 void MacroAssembler::addptr(Address dst, Register src) {
 955   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 956 }
 957 
 958 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 959   if (reachable(src)) {
 960     Assembler::addsd(dst, as_Address(src));
 961   } else {
 962     lea(rscratch1, src);
 963     Assembler::addsd(dst, Address(rscratch1, 0));
 964   }
 965 }
 966 
 967 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 968   if (reachable(src)) {
 969     addss(dst, as_Address(src));
 970   } else {
 971     lea(rscratch1, src);
 972     addss(dst, Address(rscratch1, 0));
 973   }
 974 }
 975 
 976 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 977   if (reachable(src)) {
 978     Assembler::addpd(dst, as_Address(src));
 979   } else {
 980     lea(rscratch1, src);
 981     Assembler::addpd(dst, Address(rscratch1, 0));
 982   }
 983 }
 984 
 985 void MacroAssembler::align(int modulus) {
 986   align(modulus, offset());
 987 }
 988 
 989 void MacroAssembler::align(int modulus, int target) {
 990   if (target % modulus != 0) {
 991     nop(modulus - (target % modulus));
 992   }
 993 }
 994 
 995 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 996   // Used in sign-masking with aligned address.
 997   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 998   if (reachable(src)) {
 999     Assembler::andpd(dst, as_Address(src));
1000   } else {
1001     lea(rscratch1, src);
1002     Assembler::andpd(dst, Address(rscratch1, 0));
1003   }
1004 }
1005 
1006 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1007   // Used in sign-masking with aligned address.
1008   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1009   if (reachable(src)) {
1010     Assembler::andps(dst, as_Address(src));
1011   } else {
1012     lea(rscratch1, src);
1013     Assembler::andps(dst, Address(rscratch1, 0));
1014   }
1015 }
1016 
1017 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1018   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1019 }
1020 
1021 void MacroAssembler::atomic_incl(Address counter_addr) {
1022   if (os::is_MP())
1023     lock();
1024   incrementl(counter_addr);
1025 }
1026 
1027 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1028   if (reachable(counter_addr)) {
1029     atomic_incl(as_Address(counter_addr));
1030   } else {
1031     lea(scr, counter_addr);
1032     atomic_incl(Address(scr, 0));
1033   }
1034 }
1035 
1036 #ifdef _LP64
1037 void MacroAssembler::atomic_incq(Address counter_addr) {
1038   if (os::is_MP())
1039     lock();
1040   incrementq(counter_addr);
1041 }
1042 
1043 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1044   if (reachable(counter_addr)) {
1045     atomic_incq(as_Address(counter_addr));
1046   } else {
1047     lea(scr, counter_addr);
1048     atomic_incq(Address(scr, 0));
1049   }
1050 }
1051 #endif
1052 
1053 // Writes to stack successive pages until offset reached to check for
1054 // stack overflow + shadow pages.  This clobbers tmp.
1055 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1056   movptr(tmp, rsp);
1057   // Bang stack for total size given plus shadow page size.
1058   // Bang one page at a time because large size can bang beyond yellow and
1059   // red zones.
1060   Label loop;
1061   bind(loop);
1062   movl(Address(tmp, (-os::vm_page_size())), size );
1063   subptr(tmp, os::vm_page_size());
1064   subl(size, os::vm_page_size());
1065   jcc(Assembler::greater, loop);
1066 
1067   // Bang down shadow pages too.
1068   // At this point, (tmp-0) is the last address touched, so don't
1069   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1070   // was post-decremented.)  Skip this address by starting at i=1, and
1071   // touch a few more pages below.  N.B.  It is important to touch all
1072   // the way down including all pages in the shadow zone.
1073   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1074     // this could be any sized move but this is can be a debugging crumb
1075     // so the bigger the better.
1076     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1077   }
1078 }
1079 
1080 void MacroAssembler::reserved_stack_check() {
1081     // testing if reserved zone needs to be enabled
1082     Label no_reserved_zone_enabling;
1083     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1084     NOT_LP64(get_thread(rsi);)
1085 
1086     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1087     jcc(Assembler::below, no_reserved_zone_enabling);
1088 
1089     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1090     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1091     should_not_reach_here();
1092 
1093     bind(no_reserved_zone_enabling);
1094 }
1095 
1096 int MacroAssembler::biased_locking_enter(Register lock_reg,
1097                                          Register obj_reg,
1098                                          Register swap_reg,
1099                                          Register tmp_reg,
1100                                          bool swap_reg_contains_mark,
1101                                          Label& done,
1102                                          Label* slow_case,
1103                                          BiasedLockingCounters* counters) {
1104   assert(UseBiasedLocking, "why call this otherwise?");
1105   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1106   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1107   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1108   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1109   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1110   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1111 
1112   shenandoah_store_addr_check(obj_reg);
1113 
1114   if (PrintBiasedLockingStatistics && counters == NULL) {
1115     counters = BiasedLocking::counters();
1116   }
1117   // Biased locking
1118   // See whether the lock is currently biased toward our thread and
1119   // whether the epoch is still valid
1120   // Note that the runtime guarantees sufficient alignment of JavaThread
1121   // pointers to allow age to be placed into low bits
1122   // First check to see whether biasing is even enabled for this object
1123   Label cas_label;
1124   int null_check_offset = -1;
1125   if (!swap_reg_contains_mark) {
1126     null_check_offset = offset();
1127     movptr(swap_reg, mark_addr);
1128   }
1129   movptr(tmp_reg, swap_reg);
1130   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1131   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1132   jcc(Assembler::notEqual, cas_label);
1133   // The bias pattern is present in the object's header. Need to check
1134   // whether the bias owner and the epoch are both still current.
1135 #ifndef _LP64
1136   // Note that because there is no current thread register on x86_32 we
1137   // need to store off the mark word we read out of the object to
1138   // avoid reloading it and needing to recheck invariants below. This
1139   // store is unfortunate but it makes the overall code shorter and
1140   // simpler.
1141   movptr(saved_mark_addr, swap_reg);
1142 #endif
1143   if (swap_reg_contains_mark) {
1144     null_check_offset = offset();
1145   }
1146   load_prototype_header(tmp_reg, obj_reg);
1147 #ifdef _LP64
1148   orptr(tmp_reg, r15_thread);
1149   xorptr(tmp_reg, swap_reg);
1150   Register header_reg = tmp_reg;
1151 #else
1152   xorptr(tmp_reg, swap_reg);
1153   get_thread(swap_reg);
1154   xorptr(swap_reg, tmp_reg);
1155   Register header_reg = swap_reg;
1156 #endif
1157   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1158   if (counters != NULL) {
1159     cond_inc32(Assembler::zero,
1160                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1161   }
1162   jcc(Assembler::equal, done);
1163 
1164   Label try_revoke_bias;
1165   Label try_rebias;
1166 
1167   // At this point we know that the header has the bias pattern and
1168   // that we are not the bias owner in the current epoch. We need to
1169   // figure out more details about the state of the header in order to
1170   // know what operations can be legally performed on the object's
1171   // header.
1172 
1173   // If the low three bits in the xor result aren't clear, that means
1174   // the prototype header is no longer biased and we have to revoke
1175   // the bias on this object.
1176   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1177   jccb_if_possible(Assembler::notZero, try_revoke_bias);
1178 
1179   // Biasing is still enabled for this data type. See whether the
1180   // epoch of the current bias is still valid, meaning that the epoch
1181   // bits of the mark word are equal to the epoch bits of the
1182   // prototype header. (Note that the prototype header's epoch bits
1183   // only change at a safepoint.) If not, attempt to rebias the object
1184   // toward the current thread. Note that we must be absolutely sure
1185   // that the current epoch is invalid in order to do this because
1186   // otherwise the manipulations it performs on the mark word are
1187   // illegal.
1188   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1189   jccb_if_possible(Assembler::notZero, try_rebias);
1190 
1191   // The epoch of the current bias is still valid but we know nothing
1192   // about the owner; it might be set or it might be clear. Try to
1193   // acquire the bias of the object using an atomic operation. If this
1194   // fails we will go in to the runtime to revoke the object's bias.
1195   // Note that we first construct the presumed unbiased header so we
1196   // don't accidentally blow away another thread's valid bias.
1197   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1198   andptr(swap_reg,
1199          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1200 #ifdef _LP64
1201   movptr(tmp_reg, swap_reg);
1202   orptr(tmp_reg, r15_thread);
1203 #else
1204   get_thread(tmp_reg);
1205   orptr(tmp_reg, swap_reg);
1206 #endif
1207   if (os::is_MP()) {
1208     lock();
1209   }
1210   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1211   // If the biasing toward our thread failed, this means that
1212   // another thread succeeded in biasing it toward itself and we
1213   // need to revoke that bias. The revocation will occur in the
1214   // interpreter runtime in the slow case.
1215   if (counters != NULL) {
1216     cond_inc32(Assembler::zero,
1217                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1218   }
1219   if (slow_case != NULL) {
1220     jcc(Assembler::notZero, *slow_case);
1221   }
1222   jmp(done);
1223 
1224   bind(try_rebias);
1225   // At this point we know the epoch has expired, meaning that the
1226   // current "bias owner", if any, is actually invalid. Under these
1227   // circumstances _only_, we are allowed to use the current header's
1228   // value as the comparison value when doing the cas to acquire the
1229   // bias in the current epoch. In other words, we allow transfer of
1230   // the bias from one thread to another directly in this situation.
1231   //
1232   // FIXME: due to a lack of registers we currently blow away the age
1233   // bits in this situation. Should attempt to preserve them.
1234   load_prototype_header(tmp_reg, obj_reg);
1235 #ifdef _LP64
1236   orptr(tmp_reg, r15_thread);
1237 #else
1238   get_thread(swap_reg);
1239   orptr(tmp_reg, swap_reg);
1240   movptr(swap_reg, saved_mark_addr);
1241 #endif
1242   if (os::is_MP()) {
1243     lock();
1244   }
1245   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1246   // If the biasing toward our thread failed, then another thread
1247   // succeeded in biasing it toward itself and we need to revoke that
1248   // bias. The revocation will occur in the runtime in the slow case.
1249   if (counters != NULL) {
1250     cond_inc32(Assembler::zero,
1251                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1252   }
1253   if (slow_case != NULL) {
1254     jcc(Assembler::notZero, *slow_case);
1255   }
1256   jmp(done);
1257 
1258   bind(try_revoke_bias);
1259   // The prototype mark in the klass doesn't have the bias bit set any
1260   // more, indicating that objects of this data type are not supposed
1261   // to be biased any more. We are going to try to reset the mark of
1262   // this object to the prototype value and fall through to the
1263   // CAS-based locking scheme. Note that if our CAS fails, it means
1264   // that another thread raced us for the privilege of revoking the
1265   // bias of this particular object, so it's okay to continue in the
1266   // normal locking code.
1267   //
1268   // FIXME: due to a lack of registers we currently blow away the age
1269   // bits in this situation. Should attempt to preserve them.
1270   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1271   load_prototype_header(tmp_reg, obj_reg);
1272   if (os::is_MP()) {
1273     lock();
1274   }
1275   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1276   // Fall through to the normal CAS-based lock, because no matter what
1277   // the result of the above CAS, some thread must have succeeded in
1278   // removing the bias bit from the object's header.
1279   if (counters != NULL) {
1280     cond_inc32(Assembler::zero,
1281                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1282   }
1283 
1284   bind(cas_label);
1285 
1286   return null_check_offset;
1287 }
1288 
1289 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1290   assert(UseBiasedLocking, "why call this otherwise?");
1291 
1292   // Check for biased locking unlock case, which is a no-op
1293   // Note: we do not have to check the thread ID for two reasons.
1294   // First, the interpreter checks for IllegalMonitorStateException at
1295   // a higher level. Second, if the bias was revoked while we held the
1296   // lock, the object could not be rebiased toward another thread, so
1297   // the bias bit would be clear.
1298   shenandoah_store_addr_check(obj_reg); // Access mark word
1299   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1300   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1301   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1302   jcc(Assembler::equal, done);
1303 }
1304 
1305 #ifdef COMPILER2
1306 
1307 #if INCLUDE_RTM_OPT
1308 
1309 // Update rtm_counters based on abort status
1310 // input: abort_status
1311 //        rtm_counters (RTMLockingCounters*)
1312 // flags are killed
1313 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1314 
1315   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1316   if (PrintPreciseRTMLockingStatistics) {
1317     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1318       Label check_abort;
1319       testl(abort_status, (1<<i));
1320       jccb(Assembler::equal, check_abort);
1321       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1322       bind(check_abort);
1323     }
1324   }
1325 }
1326 
1327 // Branch if (random & (count-1) != 0), count is 2^n
1328 // tmp, scr and flags are killed
1329 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1330   assert(tmp == rax, "");
1331   assert(scr == rdx, "");
1332   rdtsc(); // modifies EDX:EAX
1333   andptr(tmp, count-1);
1334   jccb(Assembler::notZero, brLabel);
1335 }
1336 
1337 // Perform abort ratio calculation, set no_rtm bit if high ratio
1338 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1339 // tmpReg, rtm_counters_Reg and flags are killed
1340 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1341                                                  Register rtm_counters_Reg,
1342                                                  RTMLockingCounters* rtm_counters,
1343                                                  Metadata* method_data) {
1344   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1345 
1346   if (RTMLockingCalculationDelay > 0) {
1347     // Delay calculation
1348     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1349     testptr(tmpReg, tmpReg);
1350     jccb(Assembler::equal, L_done);
1351   }
1352   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1353   //   Aborted transactions = abort_count * 100
1354   //   All transactions = total_count *  RTMTotalCountIncrRate
1355   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1356 
1357   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1358   cmpptr(tmpReg, RTMAbortThreshold);
1359   jccb(Assembler::below, L_check_always_rtm2);
1360   imulptr(tmpReg, tmpReg, 100);
1361 
1362   Register scrReg = rtm_counters_Reg;
1363   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1364   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1365   imulptr(scrReg, scrReg, RTMAbortRatio);
1366   cmpptr(tmpReg, scrReg);
1367   jccb(Assembler::below, L_check_always_rtm1);
1368   if (method_data != NULL) {
1369     // set rtm_state to "no rtm" in MDO
1370     mov_metadata(tmpReg, method_data);
1371     if (os::is_MP()) {
1372       lock();
1373     }
1374     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1375   }
1376   jmpb(L_done);
1377   bind(L_check_always_rtm1);
1378   // Reload RTMLockingCounters* address
1379   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1380   bind(L_check_always_rtm2);
1381   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1382   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1383   jccb(Assembler::below, L_done);
1384   if (method_data != NULL) {
1385     // set rtm_state to "always rtm" in MDO
1386     mov_metadata(tmpReg, method_data);
1387     if (os::is_MP()) {
1388       lock();
1389     }
1390     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1391   }
1392   bind(L_done);
1393 }
1394 
1395 // Update counters and perform abort ratio calculation
1396 // input:  abort_status_Reg
1397 // rtm_counters_Reg, flags are killed
1398 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1399                                    Register rtm_counters_Reg,
1400                                    RTMLockingCounters* rtm_counters,
1401                                    Metadata* method_data,
1402                                    bool profile_rtm) {
1403 
1404   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1405   // update rtm counters based on rax value at abort
1406   // reads abort_status_Reg, updates flags
1407   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1408   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1409   if (profile_rtm) {
1410     // Save abort status because abort_status_Reg is used by following code.
1411     if (RTMRetryCount > 0) {
1412       push(abort_status_Reg);
1413     }
1414     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1415     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1416     // restore abort status
1417     if (RTMRetryCount > 0) {
1418       pop(abort_status_Reg);
1419     }
1420   }
1421 }
1422 
1423 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1424 // inputs: retry_count_Reg
1425 //       : abort_status_Reg
1426 // output: retry_count_Reg decremented by 1
1427 // flags are killed
1428 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1429   Label doneRetry;
1430   assert(abort_status_Reg == rax, "");
1431   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1432   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1433   // if reason is in 0x6 and retry count != 0 then retry
1434   andptr(abort_status_Reg, 0x6);
1435   jccb(Assembler::zero, doneRetry);
1436   testl(retry_count_Reg, retry_count_Reg);
1437   jccb(Assembler::zero, doneRetry);
1438   pause();
1439   decrementl(retry_count_Reg);
1440   jmp(retryLabel);
1441   bind(doneRetry);
1442 }
1443 
1444 // Spin and retry if lock is busy,
1445 // inputs: box_Reg (monitor address)
1446 //       : retry_count_Reg
1447 // output: retry_count_Reg decremented by 1
1448 //       : clear z flag if retry count exceeded
1449 // tmp_Reg, scr_Reg, flags are killed
1450 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1451                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1452   Label SpinLoop, SpinExit, doneRetry;
1453   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1454 
1455   testl(retry_count_Reg, retry_count_Reg);
1456   jccb(Assembler::zero, doneRetry);
1457   decrementl(retry_count_Reg);
1458   movptr(scr_Reg, RTMSpinLoopCount);
1459 
1460   bind(SpinLoop);
1461   pause();
1462   decrementl(scr_Reg);
1463   jccb(Assembler::lessEqual, SpinExit);
1464   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1465   testptr(tmp_Reg, tmp_Reg);
1466   jccb(Assembler::notZero, SpinLoop);
1467 
1468   bind(SpinExit);
1469   jmp(retryLabel);
1470   bind(doneRetry);
1471   incrementl(retry_count_Reg); // clear z flag
1472 }
1473 
1474 // Use RTM for normal stack locks
1475 // Input: objReg (object to lock)
1476 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1477                                        Register retry_on_abort_count_Reg,
1478                                        RTMLockingCounters* stack_rtm_counters,
1479                                        Metadata* method_data, bool profile_rtm,
1480                                        Label& DONE_LABEL, Label& IsInflated) {
1481   assert(UseRTMForStackLocks, "why call this otherwise?");
1482   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1483   assert(tmpReg == rax, "");
1484   assert(scrReg == rdx, "");
1485   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1486 
1487   if (RTMRetryCount > 0) {
1488     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1489     bind(L_rtm_retry);
1490   }
1491   shenandoah_store_addr_check(objReg); // Access mark word
1492   movptr(tmpReg, Address(objReg, 0));
1493   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1494   jcc(Assembler::notZero, IsInflated);
1495 
1496   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1497     Label L_noincrement;
1498     if (RTMTotalCountIncrRate > 1) {
1499       // tmpReg, scrReg and flags are killed
1500       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1501     }
1502     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1503     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1504     bind(L_noincrement);
1505   }
1506   xbegin(L_on_abort);
1507   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1508   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1509   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1510   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1511 
1512   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1513   if (UseRTMXendForLockBusy) {
1514     xend();
1515     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1516     jmp(L_decrement_retry);
1517   }
1518   else {
1519     xabort(0);
1520   }
1521   bind(L_on_abort);
1522   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1523     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1524   }
1525   bind(L_decrement_retry);
1526   if (RTMRetryCount > 0) {
1527     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1528     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1529   }
1530 }
1531 
1532 // Use RTM for inflating locks
1533 // inputs: objReg (object to lock)
1534 //         boxReg (on-stack box address (displaced header location) - KILLED)
1535 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1536 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1537                                           Register scrReg, Register retry_on_busy_count_Reg,
1538                                           Register retry_on_abort_count_Reg,
1539                                           RTMLockingCounters* rtm_counters,
1540                                           Metadata* method_data, bool profile_rtm,
1541                                           Label& DONE_LABEL) {
1542   assert(UseRTMLocking, "why call this otherwise?");
1543   assert(tmpReg == rax, "");
1544   assert(scrReg == rdx, "");
1545   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1546   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1547 
1548   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1549   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1550   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1551 
1552   if (RTMRetryCount > 0) {
1553     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1554     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1555     bind(L_rtm_retry);
1556   }
1557   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1558     Label L_noincrement;
1559     if (RTMTotalCountIncrRate > 1) {
1560       // tmpReg, scrReg and flags are killed
1561       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1562     }
1563     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1564     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1565     bind(L_noincrement);
1566   }
1567   xbegin(L_on_abort);
1568   shenandoah_store_addr_check(objReg); // Access mark word
1569   movptr(tmpReg, Address(objReg, 0));
1570   movptr(tmpReg, Address(tmpReg, owner_offset));
1571   testptr(tmpReg, tmpReg);
1572   jcc(Assembler::zero, DONE_LABEL);
1573   if (UseRTMXendForLockBusy) {
1574     xend();
1575     jmp(L_decrement_retry);
1576   }
1577   else {
1578     xabort(0);
1579   }
1580   bind(L_on_abort);
1581   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1582   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1583     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1584   }
1585   if (RTMRetryCount > 0) {
1586     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1587     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1588   }
1589 
1590   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1591   testptr(tmpReg, tmpReg) ;
1592   jccb(Assembler::notZero, L_decrement_retry) ;
1593 
1594   // Appears unlocked - try to swing _owner from null to non-null.
1595   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1596 #ifdef _LP64
1597   Register threadReg = r15_thread;
1598 #else
1599   get_thread(scrReg);
1600   Register threadReg = scrReg;
1601 #endif
1602   if (os::is_MP()) {
1603     lock();
1604   }
1605   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1606 
1607   if (RTMRetryCount > 0) {
1608     // success done else retry
1609     jccb(Assembler::equal, DONE_LABEL) ;
1610     bind(L_decrement_retry);
1611     // Spin and retry if lock is busy.
1612     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1613   }
1614   else {
1615     bind(L_decrement_retry);
1616   }
1617 }
1618 
1619 #endif //  INCLUDE_RTM_OPT
1620 
1621 // Fast_Lock and Fast_Unlock used by C2
1622 
1623 // Because the transitions from emitted code to the runtime
1624 // monitorenter/exit helper stubs are so slow it's critical that
1625 // we inline both the stack-locking fast-path and the inflated fast path.
1626 //
1627 // See also: cmpFastLock and cmpFastUnlock.
1628 //
1629 // What follows is a specialized inline transliteration of the code
1630 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1631 // another option would be to emit TrySlowEnter and TrySlowExit methods
1632 // at startup-time.  These methods would accept arguments as
1633 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1634 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1635 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1636 // In practice, however, the # of lock sites is bounded and is usually small.
1637 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1638 // if the processor uses simple bimodal branch predictors keyed by EIP
1639 // Since the helper routines would be called from multiple synchronization
1640 // sites.
1641 //
1642 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1643 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1644 // to those specialized methods.  That'd give us a mostly platform-independent
1645 // implementation that the JITs could optimize and inline at their pleasure.
1646 // Done correctly, the only time we'd need to cross to native could would be
1647 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1648 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1649 // (b) explicit barriers or fence operations.
1650 //
1651 // TODO:
1652 //
1653 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1654 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1655 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1656 //    the lock operators would typically be faster than reifying Self.
1657 //
1658 // *  Ideally I'd define the primitives as:
1659 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1660 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1661 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1662 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1663 //    Furthermore the register assignments are overconstrained, possibly resulting in
1664 //    sub-optimal code near the synchronization site.
1665 //
1666 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1667 //    Alternately, use a better sp-proximity test.
1668 //
1669 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1670 //    Either one is sufficient to uniquely identify a thread.
1671 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1672 //
1673 // *  Intrinsify notify() and notifyAll() for the common cases where the
1674 //    object is locked by the calling thread but the waitlist is empty.
1675 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1676 //
1677 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1678 //    But beware of excessive branch density on AMD Opterons.
1679 //
1680 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1681 //    or failure of the fast-path.  If the fast-path fails then we pass
1682 //    control to the slow-path, typically in C.  In Fast_Lock and
1683 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1684 //    will emit a conditional branch immediately after the node.
1685 //    So we have branches to branches and lots of ICC.ZF games.
1686 //    Instead, it might be better to have C2 pass a "FailureLabel"
1687 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1688 //    will drop through the node.  ICC.ZF is undefined at exit.
1689 //    In the case of failure, the node will branch directly to the
1690 //    FailureLabel
1691 
1692 
1693 // obj: object to lock
1694 // box: on-stack box address (displaced header location) - KILLED
1695 // rax,: tmp -- KILLED
1696 // scr: tmp -- KILLED
1697 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1698                                Register scrReg, Register cx1Reg, Register cx2Reg,
1699                                BiasedLockingCounters* counters,
1700                                RTMLockingCounters* rtm_counters,
1701                                RTMLockingCounters* stack_rtm_counters,
1702                                Metadata* method_data,
1703                                bool use_rtm, bool profile_rtm) {
1704   // Ensure the register assignments are disjoint
1705   assert(tmpReg == rax, "");
1706 
1707   if (use_rtm) {
1708     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1709   } else {
1710     assert(cx1Reg == noreg, "");
1711     assert(cx2Reg == noreg, "");
1712     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1713   }
1714 
1715   shenandoah_store_addr_check(objReg); // Access mark word
1716 
1717   if (counters != NULL) {
1718     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1719   }
1720   if (EmitSync & 1) {
1721       // set box->dhw = markOopDesc::unused_mark()
1722       // Force all sync thru slow-path: slow_enter() and slow_exit()
1723       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1724       cmpptr (rsp, (int32_t)NULL_WORD);
1725   } else {
1726     // Possible cases that we'll encounter in fast_lock
1727     // ------------------------------------------------
1728     // * Inflated
1729     //    -- unlocked
1730     //    -- Locked
1731     //       = by self
1732     //       = by other
1733     // * biased
1734     //    -- by Self
1735     //    -- by other
1736     // * neutral
1737     // * stack-locked
1738     //    -- by self
1739     //       = sp-proximity test hits
1740     //       = sp-proximity test generates false-negative
1741     //    -- by other
1742     //
1743 
1744     Label IsInflated, DONE_LABEL;
1745 
1746     // it's stack-locked, biased or neutral
1747     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1748     // order to reduce the number of conditional branches in the most common cases.
1749     // Beware -- there's a subtle invariant that fetch of the markword
1750     // at [FETCH], below, will never observe a biased encoding (*101b).
1751     // If this invariant is not held we risk exclusion (safety) failure.
1752     if (UseBiasedLocking && !UseOptoBiasInlining) {
1753       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1754     }
1755 
1756 #if INCLUDE_RTM_OPT
1757     if (UseRTMForStackLocks && use_rtm) {
1758       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1759                         stack_rtm_counters, method_data, profile_rtm,
1760                         DONE_LABEL, IsInflated);
1761     }
1762 #endif // INCLUDE_RTM_OPT
1763 
1764     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1765     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1766     jccb_if_possible(Assembler::notZero, IsInflated);
1767 
1768     // Attempt stack-locking ...
1769     orptr (tmpReg, markOopDesc::unlocked_value);
1770     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1771     if (os::is_MP()) {
1772       lock();
1773     }
1774     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1775     if (counters != NULL) {
1776       cond_inc32(Assembler::equal,
1777                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1778     }
1779     jcc(Assembler::equal, DONE_LABEL);           // Success
1780 
1781     // Recursive locking.
1782     // The object is stack-locked: markword contains stack pointer to BasicLock.
1783     // Locked by current thread if difference with current SP is less than one page.
1784     subptr(tmpReg, rsp);
1785     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1786     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1787     movptr(Address(boxReg, 0), tmpReg);
1788     if (counters != NULL) {
1789       cond_inc32(Assembler::equal,
1790                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1791     }
1792     jmp(DONE_LABEL);
1793 
1794     bind(IsInflated);
1795     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1796 
1797 #if INCLUDE_RTM_OPT
1798     // Use the same RTM locking code in 32- and 64-bit VM.
1799     if (use_rtm) {
1800       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1801                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1802     } else {
1803 #endif // INCLUDE_RTM_OPT
1804 
1805 #ifndef _LP64
1806     // The object is inflated.
1807 
1808     // boxReg refers to the on-stack BasicLock in the current frame.
1809     // We'd like to write:
1810     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1811     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1812     // additional latency as we have another ST in the store buffer that must drain.
1813 
1814     if (EmitSync & 8192) {
1815        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1816        get_thread (scrReg);
1817        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1818        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1819        if (os::is_MP()) {
1820          lock();
1821        }
1822        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1823     } else
1824     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1825        // register juggle because we need tmpReg for cmpxchgptr below
1826        movptr(scrReg, boxReg);
1827        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1828 
1829        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1830        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1831           // prefetchw [eax + Offset(_owner)-2]
1832           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1833        }
1834 
1835        if ((EmitSync & 64) == 0) {
1836          // Optimistic form: consider XORL tmpReg,tmpReg
1837          movptr(tmpReg, NULL_WORD);
1838        } else {
1839          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1840          // Test-And-CAS instead of CAS
1841          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1842          testptr(tmpReg, tmpReg);                   // Locked ?
1843          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1844        }
1845 
1846        // Appears unlocked - try to swing _owner from null to non-null.
1847        // Ideally, I'd manifest "Self" with get_thread and then attempt
1848        // to CAS the register containing Self into m->Owner.
1849        // But we don't have enough registers, so instead we can either try to CAS
1850        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1851        // we later store "Self" into m->Owner.  Transiently storing a stack address
1852        // (rsp or the address of the box) into  m->owner is harmless.
1853        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1854        if (os::is_MP()) {
1855          lock();
1856        }
1857        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1858        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1859        // If we weren't able to swing _owner from NULL to the BasicLock
1860        // then take the slow path.
1861        jccb_if_possible(Assembler::notZero, DONE_LABEL);
1862        // update _owner from BasicLock to thread
1863        get_thread (scrReg);                    // beware: clobbers ICCs
1864        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1865        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1866 
1867        // If the CAS fails we can either retry or pass control to the slow-path.
1868        // We use the latter tactic.
1869        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1870        // If the CAS was successful ...
1871        //   Self has acquired the lock
1872        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1873        // Intentional fall-through into DONE_LABEL ...
1874     } else {
1875        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1876        movptr(boxReg, tmpReg);
1877 
1878        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1879        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1880           // prefetchw [eax + Offset(_owner)-2]
1881           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1882        }
1883 
1884        if ((EmitSync & 64) == 0) {
1885          // Optimistic form
1886          xorptr  (tmpReg, tmpReg);
1887        } else {
1888          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1889          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1890          testptr(tmpReg, tmpReg);                   // Locked ?
1891          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1892        }
1893 
1894        // Appears unlocked - try to swing _owner from null to non-null.
1895        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1896        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1897        get_thread (scrReg);
1898        if (os::is_MP()) {
1899          lock();
1900        }
1901        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1902 
1903        // If the CAS fails we can either retry or pass control to the slow-path.
1904        // We use the latter tactic.
1905        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1906        // If the CAS was successful ...
1907        //   Self has acquired the lock
1908        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1909        // Intentional fall-through into DONE_LABEL ...
1910     }
1911 #else // _LP64
1912     // It's inflated
1913     movq(scrReg, tmpReg);
1914     xorq(tmpReg, tmpReg);
1915 
1916     if (os::is_MP()) {
1917       lock();
1918     }
1919     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1920     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1921     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1922     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1923     // Intentional fall-through into DONE_LABEL ...
1924     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1925 #endif // _LP64
1926 #if INCLUDE_RTM_OPT
1927     } // use_rtm()
1928 #endif
1929     // DONE_LABEL is a hot target - we'd really like to place it at the
1930     // start of cache line by padding with NOPs.
1931     // See the AMD and Intel software optimization manuals for the
1932     // most efficient "long" NOP encodings.
1933     // Unfortunately none of our alignment mechanisms suffice.
1934     bind(DONE_LABEL);
1935 
1936     // At DONE_LABEL the icc ZFlag is set as follows ...
1937     // Fast_Unlock uses the same protocol.
1938     // ZFlag == 1 -> Success
1939     // ZFlag == 0 -> Failure - force control through the slow-path
1940   }
1941 }
1942 
1943 // obj: object to unlock
1944 // box: box address (displaced header location), killed.  Must be EAX.
1945 // tmp: killed, cannot be obj nor box.
1946 //
1947 // Some commentary on balanced locking:
1948 //
1949 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1950 // Methods that don't have provably balanced locking are forced to run in the
1951 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1952 // The interpreter provides two properties:
1953 // I1:  At return-time the interpreter automatically and quietly unlocks any
1954 //      objects acquired the current activation (frame).  Recall that the
1955 //      interpreter maintains an on-stack list of locks currently held by
1956 //      a frame.
1957 // I2:  If a method attempts to unlock an object that is not held by the
1958 //      the frame the interpreter throws IMSX.
1959 //
1960 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1961 // B() doesn't have provably balanced locking so it runs in the interpreter.
1962 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1963 // is still locked by A().
1964 //
1965 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1966 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1967 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1968 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1969 // Arguably given that the spec legislates the JNI case as undefined our implementation
1970 // could reasonably *avoid* checking owner in Fast_Unlock().
1971 // In the interest of performance we elide m->Owner==Self check in unlock.
1972 // A perfectly viable alternative is to elide the owner check except when
1973 // Xcheck:jni is enabled.
1974 
1975 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1976   assert(boxReg == rax, "");
1977   assert_different_registers(objReg, boxReg, tmpReg);
1978 
1979   shenandoah_store_addr_check(objReg); // Access mark word
1980 
1981   if (EmitSync & 4) {
1982     // Disable - inhibit all inlining.  Force control through the slow-path
1983     cmpptr (rsp, 0);
1984   } else {
1985     Label DONE_LABEL, Stacked, CheckSucc;
1986 
1987     // Critically, the biased locking test must have precedence over
1988     // and appear before the (box->dhw == 0) recursive stack-lock test.
1989     if (UseBiasedLocking && !UseOptoBiasInlining) {
1990        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1991     }
1992 
1993 #if INCLUDE_RTM_OPT
1994     if (UseRTMForStackLocks && use_rtm) {
1995       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1996       Label L_regular_unlock;
1997       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1998       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1999       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
2000       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2001       xend();                                       // otherwise end...
2002       jmp(DONE_LABEL);                              // ... and we're done
2003       bind(L_regular_unlock);
2004     }
2005 #endif
2006 
2007     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2008     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2009     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
2010     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2011     jccb  (Assembler::zero, Stacked);
2012 
2013     // It's inflated.
2014 #if INCLUDE_RTM_OPT
2015     if (use_rtm) {
2016       Label L_regular_inflated_unlock;
2017       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2018       movptr(boxReg, Address(tmpReg, owner_offset));
2019       testptr(boxReg, boxReg);
2020       jccb(Assembler::notZero, L_regular_inflated_unlock);
2021       xend();
2022       jmpb_if_possible(DONE_LABEL);
2023       bind(L_regular_inflated_unlock);
2024     }
2025 #endif
2026 
2027     // Despite our balanced locking property we still check that m->_owner == Self
2028     // as java routines or native JNI code called by this thread might
2029     // have released the lock.
2030     // Refer to the comments in synchronizer.cpp for how we might encode extra
2031     // state in _succ so we can avoid fetching EntryList|cxq.
2032     //
2033     // I'd like to add more cases in fast_lock() and fast_unlock() --
2034     // such as recursive enter and exit -- but we have to be wary of
2035     // I$ bloat, T$ effects and BP$ effects.
2036     //
2037     // If there's no contention try a 1-0 exit.  That is, exit without
2038     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2039     // we detect and recover from the race that the 1-0 exit admits.
2040     //
2041     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2042     // before it STs null into _owner, releasing the lock.  Updates
2043     // to data protected by the critical section must be visible before
2044     // we drop the lock (and thus before any other thread could acquire
2045     // the lock and observe the fields protected by the lock).
2046     // IA32's memory-model is SPO, so STs are ordered with respect to
2047     // each other and there's no need for an explicit barrier (fence).
2048     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2049 #ifndef _LP64
2050     get_thread (boxReg);
2051     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2052       // prefetchw [ebx + Offset(_owner)-2]
2053       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2054     }
2055 
2056     // Note that we could employ various encoding schemes to reduce
2057     // the number of loads below (currently 4) to just 2 or 3.
2058     // Refer to the comments in synchronizer.cpp.
2059     // In practice the chain of fetches doesn't seem to impact performance, however.
2060     xorptr(boxReg, boxReg);
2061     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2062        // Attempt to reduce branch density - AMD's branch predictor.
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2064        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2065        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2066        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2067        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2068        jmpb_if_possible(DONE_LABEL);
2069     } else {
2070        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2071        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2072        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2073        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2074        jccb  (Assembler::notZero, CheckSucc);
2075        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2076        jmpb_if_possible(DONE_LABEL);
2077     }
2078 
2079     // The Following code fragment (EmitSync & 65536) improves the performance of
2080     // contended applications and contended synchronization microbenchmarks.
2081     // Unfortunately the emission of the code - even though not executed - causes regressions
2082     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2083     // with an equal number of never-executed NOPs results in the same regression.
2084     // We leave it off by default.
2085 
2086     if ((EmitSync & 65536) != 0) {
2087        Label LSuccess, LGoSlowPath ;
2088 
2089        bind  (CheckSucc);
2090 
2091        // Optional pre-test ... it's safe to elide this
2092        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2093        jccb(Assembler::zero, LGoSlowPath);
2094 
2095        // We have a classic Dekker-style idiom:
2096        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2097        // There are a number of ways to implement the barrier:
2098        // (1) lock:andl &m->_owner, 0
2099        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2100        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2101        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2102        // (2) If supported, an explicit MFENCE is appealing.
2103        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2104        //     particularly if the write-buffer is full as might be the case if
2105        //     if stores closely precede the fence or fence-equivalent instruction.
2106        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2107        //     as the situation has changed with Nehalem and Shanghai.
2108        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2109        //     The $lines underlying the top-of-stack should be in M-state.
2110        //     The locked add instruction is serializing, of course.
2111        // (4) Use xchg, which is serializing
2112        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2113        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2114        //     The integer condition codes will tell us if succ was 0.
2115        //     Since _succ and _owner should reside in the same $line and
2116        //     we just stored into _owner, it's likely that the $line
2117        //     remains in M-state for the lock:orl.
2118        //
2119        // We currently use (3), although it's likely that switching to (2)
2120        // is correct for the future.
2121 
2122        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2123        if (os::is_MP()) {
2124          lock(); addptr(Address(rsp, 0), 0);
2125        }
2126        // Ratify _succ remains non-null
2127        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2128        jccb  (Assembler::notZero, LSuccess);
2129 
2130        xorptr(boxReg, boxReg);                  // box is really EAX
2131        if (os::is_MP()) { lock(); }
2132        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2133        // There's no successor so we tried to regrab the lock with the
2134        // placeholder value. If that didn't work, then another thread
2135        // grabbed the lock so we're done (and exit was a success).
2136        jccb  (Assembler::notEqual, LSuccess);
2137        // Since we're low on registers we installed rsp as a placeholding in _owner.
2138        // Now install Self over rsp.  This is safe as we're transitioning from
2139        // non-null to non=null
2140        get_thread (boxReg);
2141        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2142        // Intentional fall-through into LGoSlowPath ...
2143 
2144        bind  (LGoSlowPath);
2145        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2146        jmpb_if_possible(DONE_LABEL);
2147 
2148        bind  (LSuccess);
2149        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2150        jmpb_if_possible(DONE_LABEL);
2151     }
2152 
2153     bind (Stacked);
2154     // It's not inflated and it's not recursively stack-locked and it's not biased.
2155     // It must be stack-locked.
2156     // Try to reset the header to displaced header.
2157     // The "box" value on the stack is stable, so we can reload
2158     // and be assured we observe the same value as above.
2159     movptr(tmpReg, Address(boxReg, 0));
2160     if (os::is_MP()) {
2161       lock();
2162     }
2163     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2164     // Intention fall-thru into DONE_LABEL
2165 
2166     // DONE_LABEL is a hot target - we'd really like to place it at the
2167     // start of cache line by padding with NOPs.
2168     // See the AMD and Intel software optimization manuals for the
2169     // most efficient "long" NOP encodings.
2170     // Unfortunately none of our alignment mechanisms suffice.
2171     if ((EmitSync & 65536) == 0) {
2172        bind (CheckSucc);
2173     }
2174 #else // _LP64
2175     // It's inflated
2176     if (EmitSync & 1024) {
2177       // Emit code to check that _owner == Self
2178       // We could fold the _owner test into subsequent code more efficiently
2179       // than using a stand-alone check, but since _owner checking is off by
2180       // default we don't bother. We also might consider predicating the
2181       // _owner==Self check on Xcheck:jni or running on a debug build.
2182       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2183       xorptr(boxReg, r15_thread);
2184     } else {
2185       xorptr(boxReg, boxReg);
2186     }
2187     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2188     jccb_if_possible(Assembler::notZero, DONE_LABEL);
2189     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2190     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2191     jccb  (Assembler::notZero, CheckSucc);
2192     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2193     jmpb_if_possible(DONE_LABEL);
2194 
2195     if ((EmitSync & 65536) == 0) {
2196       // Try to avoid passing control into the slow_path ...
2197       Label LSuccess, LGoSlowPath ;
2198       bind  (CheckSucc);
2199 
2200       // The following optional optimization can be elided if necessary
2201       // Effectively: if (succ == null) goto SlowPath
2202       // The code reduces the window for a race, however,
2203       // and thus benefits performance.
2204       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2205       jccb  (Assembler::zero, LGoSlowPath);
2206 
2207       xorptr(boxReg, boxReg);
2208       if ((EmitSync & 16) && os::is_MP()) {
2209         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2210       } else {
2211         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2212         if (os::is_MP()) {
2213           // Memory barrier/fence
2214           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2215           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2216           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2217           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2218           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2219           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2220           lock(); addl(Address(rsp, 0), 0);
2221         }
2222       }
2223       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2224       jccb  (Assembler::notZero, LSuccess);
2225 
2226       // Rare inopportune interleaving - race.
2227       // The successor vanished in the small window above.
2228       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2229       // We need to ensure progress and succession.
2230       // Try to reacquire the lock.
2231       // If that fails then the new owner is responsible for succession and this
2232       // thread needs to take no further action and can exit via the fast path (success).
2233       // If the re-acquire succeeds then pass control into the slow path.
2234       // As implemented, this latter mode is horrible because we generated more
2235       // coherence traffic on the lock *and* artifically extended the critical section
2236       // length while by virtue of passing control into the slow path.
2237 
2238       // box is really RAX -- the following CMPXCHG depends on that binding
2239       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2240       if (os::is_MP()) { lock(); }
2241       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2242       // There's no successor so we tried to regrab the lock.
2243       // If that didn't work, then another thread grabbed the
2244       // lock so we're done (and exit was a success).
2245       jccb  (Assembler::notEqual, LSuccess);
2246       // Intentional fall-through into slow-path
2247 
2248       bind  (LGoSlowPath);
2249       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2250       jmpb_if_possible(DONE_LABEL);
2251 
2252       bind  (LSuccess);
2253       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2254       jmpb_if_possible  (DONE_LABEL);
2255     }
2256 
2257     bind  (Stacked);
2258     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2259     if (os::is_MP()) { lock(); }
2260     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2261 
2262     if (EmitSync & 65536) {
2263        bind (CheckSucc);
2264     }
2265 #endif
2266     bind(DONE_LABEL);
2267   }
2268 }
2269 #endif // COMPILER2
2270 
2271 void MacroAssembler::c2bool(Register x) {
2272   // implements x == 0 ? 0 : 1
2273   // note: must only look at least-significant byte of x
2274   //       since C-style booleans are stored in one byte
2275   //       only! (was bug)
2276   andl(x, 0xFF);
2277   setb(Assembler::notZero, x);
2278 }
2279 
2280 // Wouldn't need if AddressLiteral version had new name
2281 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2282   Assembler::call(L, rtype);
2283 }
2284 
2285 void MacroAssembler::call(Register entry) {
2286   Assembler::call(entry);
2287 }
2288 
2289 void MacroAssembler::call(AddressLiteral entry) {
2290   if (reachable(entry)) {
2291     Assembler::call_literal(entry.target(), entry.rspec());
2292   } else {
2293     lea(rscratch1, entry);
2294     Assembler::call(rscratch1);
2295   }
2296 }
2297 
2298 void MacroAssembler::ic_call(address entry, jint method_index) {
2299   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2300   movptr(rax, (intptr_t)Universe::non_oop_word());
2301   call(AddressLiteral(entry, rh));
2302 }
2303 
2304 // Implementation of call_VM versions
2305 
2306 void MacroAssembler::call_VM(Register oop_result,
2307                              address entry_point,
2308                              bool check_exceptions) {
2309   Label C, E;
2310   call(C, relocInfo::none);
2311   jmp(E);
2312 
2313   bind(C);
2314   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2315   ret(0);
2316 
2317   bind(E);
2318 }
2319 
2320 void MacroAssembler::call_VM(Register oop_result,
2321                              address entry_point,
2322                              Register arg_1,
2323                              bool check_exceptions) {
2324   Label C, E;
2325   call(C, relocInfo::none);
2326   jmp(E);
2327 
2328   bind(C);
2329   pass_arg1(this, arg_1);
2330   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2331   ret(0);
2332 
2333   bind(E);
2334 }
2335 
2336 void MacroAssembler::call_VM(Register oop_result,
2337                              address entry_point,
2338                              Register arg_1,
2339                              Register arg_2,
2340                              bool check_exceptions) {
2341   Label C, E;
2342   call(C, relocInfo::none);
2343   jmp(E);
2344 
2345   bind(C);
2346 
2347   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2348 
2349   pass_arg2(this, arg_2);
2350   pass_arg1(this, arg_1);
2351   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2352   ret(0);
2353 
2354   bind(E);
2355 }
2356 
2357 void MacroAssembler::call_VM(Register oop_result,
2358                              address entry_point,
2359                              Register arg_1,
2360                              Register arg_2,
2361                              Register arg_3,
2362                              bool check_exceptions) {
2363   Label C, E;
2364   call(C, relocInfo::none);
2365   jmp(E);
2366 
2367   bind(C);
2368 
2369   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2370   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2371   pass_arg3(this, arg_3);
2372 
2373   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2374   pass_arg2(this, arg_2);
2375 
2376   pass_arg1(this, arg_1);
2377   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2378   ret(0);
2379 
2380   bind(E);
2381 }
2382 
2383 void MacroAssembler::call_VM(Register oop_result,
2384                              Register last_java_sp,
2385                              address entry_point,
2386                              int number_of_arguments,
2387                              bool check_exceptions) {
2388   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2389   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2390 }
2391 
2392 void MacroAssembler::call_VM(Register oop_result,
2393                              Register last_java_sp,
2394                              address entry_point,
2395                              Register arg_1,
2396                              bool check_exceptions) {
2397   pass_arg1(this, arg_1);
2398   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2399 }
2400 
2401 void MacroAssembler::call_VM(Register oop_result,
2402                              Register last_java_sp,
2403                              address entry_point,
2404                              Register arg_1,
2405                              Register arg_2,
2406                              bool check_exceptions) {
2407 
2408   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2409   pass_arg2(this, arg_2);
2410   pass_arg1(this, arg_1);
2411   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2412 }
2413 
2414 void MacroAssembler::call_VM(Register oop_result,
2415                              Register last_java_sp,
2416                              address entry_point,
2417                              Register arg_1,
2418                              Register arg_2,
2419                              Register arg_3,
2420                              bool check_exceptions) {
2421   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2422   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2423   pass_arg3(this, arg_3);
2424   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2425   pass_arg2(this, arg_2);
2426   pass_arg1(this, arg_1);
2427   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2428 }
2429 
2430 void MacroAssembler::super_call_VM(Register oop_result,
2431                                    Register last_java_sp,
2432                                    address entry_point,
2433                                    int number_of_arguments,
2434                                    bool check_exceptions) {
2435   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2436   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2437 }
2438 
2439 void MacroAssembler::super_call_VM(Register oop_result,
2440                                    Register last_java_sp,
2441                                    address entry_point,
2442                                    Register arg_1,
2443                                    bool check_exceptions) {
2444   pass_arg1(this, arg_1);
2445   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2446 }
2447 
2448 void MacroAssembler::super_call_VM(Register oop_result,
2449                                    Register last_java_sp,
2450                                    address entry_point,
2451                                    Register arg_1,
2452                                    Register arg_2,
2453                                    bool check_exceptions) {
2454 
2455   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2456   pass_arg2(this, arg_2);
2457   pass_arg1(this, arg_1);
2458   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2459 }
2460 
2461 void MacroAssembler::super_call_VM(Register oop_result,
2462                                    Register last_java_sp,
2463                                    address entry_point,
2464                                    Register arg_1,
2465                                    Register arg_2,
2466                                    Register arg_3,
2467                                    bool check_exceptions) {
2468   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2469   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2470   pass_arg3(this, arg_3);
2471   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2472   pass_arg2(this, arg_2);
2473   pass_arg1(this, arg_1);
2474   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2475 }
2476 
2477 void MacroAssembler::call_VM_base(Register oop_result,
2478                                   Register java_thread,
2479                                   Register last_java_sp,
2480                                   address  entry_point,
2481                                   int      number_of_arguments,
2482                                   bool     check_exceptions) {
2483   // determine java_thread register
2484   if (!java_thread->is_valid()) {
2485 #ifdef _LP64
2486     java_thread = r15_thread;
2487 #else
2488     java_thread = rdi;
2489     get_thread(java_thread);
2490 #endif // LP64
2491   }
2492   // determine last_java_sp register
2493   if (!last_java_sp->is_valid()) {
2494     last_java_sp = rsp;
2495   }
2496   // debugging support
2497   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2498   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2499 #ifdef ASSERT
2500   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2501   // r12 is the heapbase.
2502   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2503 #endif // ASSERT
2504 
2505   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2506   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2507 
2508   // push java thread (becomes first argument of C function)
2509 
2510   NOT_LP64(push(java_thread); number_of_arguments++);
2511   LP64_ONLY(mov(c_rarg0, r15_thread));
2512 
2513   // set last Java frame before call
2514   assert(last_java_sp != rbp, "can't use ebp/rbp");
2515 
2516   // Only interpreter should have to set fp
2517   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2518 
2519   // do the call, remove parameters
2520   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2521 
2522   // restore the thread (cannot use the pushed argument since arguments
2523   // may be overwritten by C code generated by an optimizing compiler);
2524   // however can use the register value directly if it is callee saved.
2525   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2526     // rdi & rsi (also r15) are callee saved -> nothing to do
2527 #ifdef ASSERT
2528     guarantee(java_thread != rax, "change this code");
2529     push(rax);
2530     { Label L;
2531       get_thread(rax);
2532       cmpptr(java_thread, rax);
2533       jcc(Assembler::equal, L);
2534       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2535       bind(L);
2536     }
2537     pop(rax);
2538 #endif
2539   } else {
2540     get_thread(java_thread);
2541   }
2542   // reset last Java frame
2543   // Only interpreter should have to clear fp
2544   reset_last_Java_frame(java_thread, true);
2545 
2546    // C++ interp handles this in the interpreter
2547   check_and_handle_popframe(java_thread);
2548   check_and_handle_earlyret(java_thread);
2549 
2550   if (check_exceptions) {
2551     // check for pending exceptions (java_thread is set upon return)
2552     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2553 #ifndef _LP64
2554     jump_cc(Assembler::notEqual,
2555             RuntimeAddress(StubRoutines::forward_exception_entry()));
2556 #else
2557     // This used to conditionally jump to forward_exception however it is
2558     // possible if we relocate that the branch will not reach. So we must jump
2559     // around so we can always reach
2560 
2561     Label ok;
2562     jcc(Assembler::equal, ok);
2563     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2564     bind(ok);
2565 #endif // LP64
2566   }
2567 
2568   // get oop result if there is one and reset the value in the thread
2569   if (oop_result->is_valid()) {
2570     get_vm_result(oop_result, java_thread);
2571   }
2572 }
2573 
2574 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2575 
2576   // Calculate the value for last_Java_sp
2577   // somewhat subtle. call_VM does an intermediate call
2578   // which places a return address on the stack just under the
2579   // stack pointer as the user finsihed with it. This allows
2580   // use to retrieve last_Java_pc from last_Java_sp[-1].
2581   // On 32bit we then have to push additional args on the stack to accomplish
2582   // the actual requested call. On 64bit call_VM only can use register args
2583   // so the only extra space is the return address that call_VM created.
2584   // This hopefully explains the calculations here.
2585 
2586 #ifdef _LP64
2587   // We've pushed one address, correct last_Java_sp
2588   lea(rax, Address(rsp, wordSize));
2589 #else
2590   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2591 #endif // LP64
2592 
2593   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2594 
2595 }
2596 
2597 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2598 void MacroAssembler::call_VM_leaf0(address entry_point) {
2599   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2600 }
2601 
2602 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2603   call_VM_leaf_base(entry_point, number_of_arguments);
2604 }
2605 
2606 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2607   pass_arg0(this, arg_0);
2608   call_VM_leaf(entry_point, 1);
2609 }
2610 
2611 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2612 
2613   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2614   pass_arg1(this, arg_1);
2615   pass_arg0(this, arg_0);
2616   call_VM_leaf(entry_point, 2);
2617 }
2618 
2619 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2620   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2621   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2622   pass_arg2(this, arg_2);
2623   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2624   pass_arg1(this, arg_1);
2625   pass_arg0(this, arg_0);
2626   call_VM_leaf(entry_point, 3);
2627 }
2628 
2629 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2630   pass_arg0(this, arg_0);
2631   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2632 }
2633 
2634 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2635 
2636   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2637   pass_arg1(this, arg_1);
2638   pass_arg0(this, arg_0);
2639   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2640 }
2641 
2642 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2643   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2644   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2645   pass_arg2(this, arg_2);
2646   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2647   pass_arg1(this, arg_1);
2648   pass_arg0(this, arg_0);
2649   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2650 }
2651 
2652 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2653   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2654   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2655   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2656   pass_arg3(this, arg_3);
2657   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2658   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2659   pass_arg2(this, arg_2);
2660   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2661   pass_arg1(this, arg_1);
2662   pass_arg0(this, arg_0);
2663   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2664 }
2665 
2666 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2667   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2668   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2669   verify_oop(oop_result, "broken oop in call_VM_base");
2670 }
2671 
2672 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2673   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2674   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2675 }
2676 
2677 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2678 }
2679 
2680 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2681 }
2682 
2683 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2684   if (reachable(src1)) {
2685     cmpl(as_Address(src1), imm);
2686   } else {
2687     lea(rscratch1, src1);
2688     cmpl(Address(rscratch1, 0), imm);
2689   }
2690 }
2691 
2692 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2693   assert(!src2.is_lval(), "use cmpptr");
2694   if (reachable(src2)) {
2695     cmpl(src1, as_Address(src2));
2696   } else {
2697     lea(rscratch1, src2);
2698     cmpl(src1, Address(rscratch1, 0));
2699   }
2700 }
2701 
2702 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2703   Assembler::cmpl(src1, imm);
2704 }
2705 
2706 void MacroAssembler::cmp32(Register src1, Address src2) {
2707   Assembler::cmpl(src1, src2);
2708 }
2709 
2710 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2711   ucomisd(opr1, opr2);
2712 
2713   Label L;
2714   if (unordered_is_less) {
2715     movl(dst, -1);
2716     jcc(Assembler::parity, L);
2717     jcc(Assembler::below , L);
2718     movl(dst, 0);
2719     jcc(Assembler::equal , L);
2720     increment(dst);
2721   } else { // unordered is greater
2722     movl(dst, 1);
2723     jcc(Assembler::parity, L);
2724     jcc(Assembler::above , L);
2725     movl(dst, 0);
2726     jcc(Assembler::equal , L);
2727     decrementl(dst);
2728   }
2729   bind(L);
2730 }
2731 
2732 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2733   ucomiss(opr1, opr2);
2734 
2735   Label L;
2736   if (unordered_is_less) {
2737     movl(dst, -1);
2738     jcc(Assembler::parity, L);
2739     jcc(Assembler::below , L);
2740     movl(dst, 0);
2741     jcc(Assembler::equal , L);
2742     increment(dst);
2743   } else { // unordered is greater
2744     movl(dst, 1);
2745     jcc(Assembler::parity, L);
2746     jcc(Assembler::above , L);
2747     movl(dst, 0);
2748     jcc(Assembler::equal , L);
2749     decrementl(dst);
2750   }
2751   bind(L);
2752 }
2753 
2754 
2755 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2756   if (reachable(src1)) {
2757     cmpb(as_Address(src1), imm);
2758   } else {
2759     lea(rscratch1, src1);
2760     cmpb(Address(rscratch1, 0), imm);
2761   }
2762 }
2763 
2764 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2765 #ifdef _LP64
2766   if (src2.is_lval()) {
2767     movptr(rscratch1, src2);
2768     Assembler::cmpq(src1, rscratch1);
2769   } else if (reachable(src2)) {
2770     cmpq(src1, as_Address(src2));
2771   } else {
2772     lea(rscratch1, src2);
2773     Assembler::cmpq(src1, Address(rscratch1, 0));
2774   }
2775 #else
2776   if (src2.is_lval()) {
2777     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2778   } else {
2779     cmpl(src1, as_Address(src2));
2780   }
2781 #endif // _LP64
2782 }
2783 
2784 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2785   assert(src2.is_lval(), "not a mem-mem compare");
2786 #ifdef _LP64
2787   // moves src2's literal address
2788   movptr(rscratch1, src2);
2789   Assembler::cmpq(src1, rscratch1);
2790 #else
2791   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2792 #endif // _LP64
2793 }
2794 
2795 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2796   if (reachable(adr)) {
2797     if (os::is_MP())
2798       lock();
2799     cmpxchgptr(reg, as_Address(adr));
2800   } else {
2801     lea(rscratch1, adr);
2802     if (os::is_MP())
2803       lock();
2804     cmpxchgptr(reg, Address(rscratch1, 0));
2805   }
2806 }
2807 
2808 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2809   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2810 }
2811 
2812 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2813   if (reachable(src)) {
2814     Assembler::comisd(dst, as_Address(src));
2815   } else {
2816     lea(rscratch1, src);
2817     Assembler::comisd(dst, Address(rscratch1, 0));
2818   }
2819 }
2820 
2821 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2822   if (reachable(src)) {
2823     Assembler::comiss(dst, as_Address(src));
2824   } else {
2825     lea(rscratch1, src);
2826     Assembler::comiss(dst, Address(rscratch1, 0));
2827   }
2828 }
2829 
2830 
2831 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2832   Condition negated_cond = negate_condition(cond);
2833   Label L;
2834   jcc(negated_cond, L);
2835   pushf(); // Preserve flags
2836   atomic_incl(counter_addr);
2837   popf();
2838   bind(L);
2839 }
2840 
2841 int MacroAssembler::corrected_idivl(Register reg) {
2842   // Full implementation of Java idiv and irem; checks for
2843   // special case as described in JVM spec., p.243 & p.271.
2844   // The function returns the (pc) offset of the idivl
2845   // instruction - may be needed for implicit exceptions.
2846   //
2847   //         normal case                           special case
2848   //
2849   // input : rax,: dividend                         min_int
2850   //         reg: divisor   (may not be rax,/rdx)   -1
2851   //
2852   // output: rax,: quotient  (= rax, idiv reg)       min_int
2853   //         rdx: remainder (= rax, irem reg)       0
2854   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2855   const int min_int = 0x80000000;
2856   Label normal_case, special_case;
2857 
2858   // check for special case
2859   cmpl(rax, min_int);
2860   jcc(Assembler::notEqual, normal_case);
2861   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2862   cmpl(reg, -1);
2863   jcc(Assembler::equal, special_case);
2864 
2865   // handle normal case
2866   bind(normal_case);
2867   cdql();
2868   int idivl_offset = offset();
2869   idivl(reg);
2870 
2871   // normal and special case exit
2872   bind(special_case);
2873 
2874   return idivl_offset;
2875 }
2876 
2877 
2878 
2879 void MacroAssembler::decrementl(Register reg, int value) {
2880   if (value == min_jint) {subl(reg, value) ; return; }
2881   if (value <  0) { incrementl(reg, -value); return; }
2882   if (value == 0) {                        ; return; }
2883   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2884   /* else */      { subl(reg, value)       ; return; }
2885 }
2886 
2887 void MacroAssembler::decrementl(Address dst, int value) {
2888   if (value == min_jint) {subl(dst, value) ; return; }
2889   if (value <  0) { incrementl(dst, -value); return; }
2890   if (value == 0) {                        ; return; }
2891   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2892   /* else */      { subl(dst, value)       ; return; }
2893 }
2894 
2895 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2896   assert (shift_value > 0, "illegal shift value");
2897   Label _is_positive;
2898   testl (reg, reg);
2899   jcc (Assembler::positive, _is_positive);
2900   int offset = (1 << shift_value) - 1 ;
2901 
2902   if (offset == 1) {
2903     incrementl(reg);
2904   } else {
2905     addl(reg, offset);
2906   }
2907 
2908   bind (_is_positive);
2909   sarl(reg, shift_value);
2910 }
2911 
2912 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2913   if (reachable(src)) {
2914     Assembler::divsd(dst, as_Address(src));
2915   } else {
2916     lea(rscratch1, src);
2917     Assembler::divsd(dst, Address(rscratch1, 0));
2918   }
2919 }
2920 
2921 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2922   if (reachable(src)) {
2923     Assembler::divss(dst, as_Address(src));
2924   } else {
2925     lea(rscratch1, src);
2926     Assembler::divss(dst, Address(rscratch1, 0));
2927   }
2928 }
2929 
2930 // !defined(COMPILER2) is because of stupid core builds
2931 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2932 void MacroAssembler::empty_FPU_stack() {
2933   if (VM_Version::supports_mmx()) {
2934     emms();
2935   } else {
2936     for (int i = 8; i-- > 0; ) ffree(i);
2937   }
2938 }
2939 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2940 
2941 
2942 // Defines obj, preserves var_size_in_bytes
2943 void MacroAssembler::eden_allocate(Register obj,
2944                                    Register var_size_in_bytes,
2945                                    int con_size_in_bytes,
2946                                    Register t1,
2947                                    Label& slow_case) {
2948   assert(obj == rax, "obj must be in rax, for cmpxchg");
2949   assert_different_registers(obj, var_size_in_bytes, t1);
2950   if (!Universe::heap()->supports_inline_contig_alloc()) {
2951     jmp(slow_case);
2952   } else {
2953     Register end = t1;
2954     Label retry;
2955     bind(retry);
2956     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2957     movptr(obj, heap_top);
2958     if (var_size_in_bytes == noreg) {
2959       lea(end, Address(obj, con_size_in_bytes));
2960     } else {
2961       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2962     }
2963     // if end < obj then we wrapped around => object too long => slow case
2964     cmpptr(end, obj);
2965     jcc(Assembler::below, slow_case);
2966     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2967     jcc(Assembler::above, slow_case);
2968     // Compare obj with the top addr, and if still equal, store the new top addr in
2969     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2970     // it otherwise. Use lock prefix for atomicity on MPs.
2971     locked_cmpxchgptr(end, heap_top);
2972     jcc(Assembler::notEqual, retry);
2973   }
2974 }
2975 
2976 void MacroAssembler::enter() {
2977   push(rbp);
2978   mov(rbp, rsp);
2979 }
2980 
2981 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2982 void MacroAssembler::fat_nop() {
2983   if (UseAddressNop) {
2984     addr_nop_5();
2985   } else {
2986     emit_int8(0x26); // es:
2987     emit_int8(0x2e); // cs:
2988     emit_int8(0x64); // fs:
2989     emit_int8(0x65); // gs:
2990     emit_int8((unsigned char)0x90);
2991   }
2992 }
2993 
2994 void MacroAssembler::fcmp(Register tmp) {
2995   fcmp(tmp, 1, true, true);
2996 }
2997 
2998 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2999   assert(!pop_right || pop_left, "usage error");
3000   if (VM_Version::supports_cmov()) {
3001     assert(tmp == noreg, "unneeded temp");
3002     if (pop_left) {
3003       fucomip(index);
3004     } else {
3005       fucomi(index);
3006     }
3007     if (pop_right) {
3008       fpop();
3009     }
3010   } else {
3011     assert(tmp != noreg, "need temp");
3012     if (pop_left) {
3013       if (pop_right) {
3014         fcompp();
3015       } else {
3016         fcomp(index);
3017       }
3018     } else {
3019       fcom(index);
3020     }
3021     // convert FPU condition into eflags condition via rax,
3022     save_rax(tmp);
3023     fwait(); fnstsw_ax();
3024     sahf();
3025     restore_rax(tmp);
3026   }
3027   // condition codes set as follows:
3028   //
3029   // CF (corresponds to C0) if x < y
3030   // PF (corresponds to C2) if unordered
3031   // ZF (corresponds to C3) if x = y
3032 }
3033 
3034 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3035   fcmp2int(dst, unordered_is_less, 1, true, true);
3036 }
3037 
3038 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3039   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3040   Label L;
3041   if (unordered_is_less) {
3042     movl(dst, -1);
3043     jcc(Assembler::parity, L);
3044     jcc(Assembler::below , L);
3045     movl(dst, 0);
3046     jcc(Assembler::equal , L);
3047     increment(dst);
3048   } else { // unordered is greater
3049     movl(dst, 1);
3050     jcc(Assembler::parity, L);
3051     jcc(Assembler::above , L);
3052     movl(dst, 0);
3053     jcc(Assembler::equal , L);
3054     decrementl(dst);
3055   }
3056   bind(L);
3057 }
3058 
3059 void MacroAssembler::fld_d(AddressLiteral src) {
3060   fld_d(as_Address(src));
3061 }
3062 
3063 void MacroAssembler::fld_s(AddressLiteral src) {
3064   fld_s(as_Address(src));
3065 }
3066 
3067 void MacroAssembler::fld_x(AddressLiteral src) {
3068   Assembler::fld_x(as_Address(src));
3069 }
3070 
3071 void MacroAssembler::fldcw(AddressLiteral src) {
3072   Assembler::fldcw(as_Address(src));
3073 }
3074 
3075 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3076   if (reachable(src)) {
3077     Assembler::mulpd(dst, as_Address(src));
3078   } else {
3079     lea(rscratch1, src);
3080     Assembler::mulpd(dst, Address(rscratch1, 0));
3081   }
3082 }
3083 
3084 void MacroAssembler::increase_precision() {
3085   subptr(rsp, BytesPerWord);
3086   fnstcw(Address(rsp, 0));
3087   movl(rax, Address(rsp, 0));
3088   orl(rax, 0x300);
3089   push(rax);
3090   fldcw(Address(rsp, 0));
3091   pop(rax);
3092 }
3093 
3094 void MacroAssembler::restore_precision() {
3095   fldcw(Address(rsp, 0));
3096   addptr(rsp, BytesPerWord);
3097 }
3098 
3099 void MacroAssembler::fpop() {
3100   ffree();
3101   fincstp();
3102 }
3103 
3104 void MacroAssembler::load_float(Address src) {
3105   if (UseSSE >= 1) {
3106     movflt(xmm0, src);
3107   } else {
3108     LP64_ONLY(ShouldNotReachHere());
3109     NOT_LP64(fld_s(src));
3110   }
3111 }
3112 
3113 void MacroAssembler::store_float(Address dst) {
3114   if (UseSSE >= 1) {
3115     movflt(dst, xmm0);
3116   } else {
3117     LP64_ONLY(ShouldNotReachHere());
3118     NOT_LP64(fstp_s(dst));
3119   }
3120 }
3121 
3122 void MacroAssembler::load_double(Address src) {
3123   if (UseSSE >= 2) {
3124     movdbl(xmm0, src);
3125   } else {
3126     LP64_ONLY(ShouldNotReachHere());
3127     NOT_LP64(fld_d(src));
3128   }
3129 }
3130 
3131 void MacroAssembler::store_double(Address dst) {
3132   if (UseSSE >= 2) {
3133     movdbl(dst, xmm0);
3134   } else {
3135     LP64_ONLY(ShouldNotReachHere());
3136     NOT_LP64(fstp_d(dst));
3137   }
3138 }
3139 
3140 void MacroAssembler::fremr(Register tmp) {
3141   save_rax(tmp);
3142   { Label L;
3143     bind(L);
3144     fprem();
3145     fwait(); fnstsw_ax();
3146 #ifdef _LP64
3147     testl(rax, 0x400);
3148     jcc(Assembler::notEqual, L);
3149 #else
3150     sahf();
3151     jcc(Assembler::parity, L);
3152 #endif // _LP64
3153   }
3154   restore_rax(tmp);
3155   // Result is in ST0.
3156   // Note: fxch & fpop to get rid of ST1
3157   // (otherwise FPU stack could overflow eventually)
3158   fxch(1);
3159   fpop();
3160 }
3161 
3162 // dst = c = a * b + c
3163 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3164   Assembler::vfmadd231sd(c, a, b);
3165   if (dst != c) {
3166     movdbl(dst, c);
3167   }
3168 }
3169 
3170 // dst = c = a * b + c
3171 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3172   Assembler::vfmadd231ss(c, a, b);
3173   if (dst != c) {
3174     movflt(dst, c);
3175   }
3176 }
3177 
3178 
3179 
3180 
3181 void MacroAssembler::incrementl(AddressLiteral dst) {
3182   if (reachable(dst)) {
3183     incrementl(as_Address(dst));
3184   } else {
3185     lea(rscratch1, dst);
3186     incrementl(Address(rscratch1, 0));
3187   }
3188 }
3189 
3190 void MacroAssembler::incrementl(ArrayAddress dst) {
3191   incrementl(as_Address(dst));
3192 }
3193 
3194 void MacroAssembler::incrementl(Register reg, int value) {
3195   if (value == min_jint) {addl(reg, value) ; return; }
3196   if (value <  0) { decrementl(reg, -value); return; }
3197   if (value == 0) {                        ; return; }
3198   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3199   /* else */      { addl(reg, value)       ; return; }
3200 }
3201 
3202 void MacroAssembler::incrementl(Address dst, int value) {
3203   if (value == min_jint) {addl(dst, value) ; return; }
3204   if (value <  0) { decrementl(dst, -value); return; }
3205   if (value == 0) {                        ; return; }
3206   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3207   /* else */      { addl(dst, value)       ; return; }
3208 }
3209 
3210 void MacroAssembler::jump(AddressLiteral dst) {
3211   if (reachable(dst)) {
3212     jmp_literal(dst.target(), dst.rspec());
3213   } else {
3214     lea(rscratch1, dst);
3215     jmp(rscratch1);
3216   }
3217 }
3218 
3219 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3220   if (reachable(dst)) {
3221     InstructionMark im(this);
3222     relocate(dst.reloc());
3223     const int short_size = 2;
3224     const int long_size = 6;
3225     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3226     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3227       // 0111 tttn #8-bit disp
3228       emit_int8(0x70 | cc);
3229       emit_int8((offs - short_size) & 0xFF);
3230     } else {
3231       // 0000 1111 1000 tttn #32-bit disp
3232       emit_int8(0x0F);
3233       emit_int8((unsigned char)(0x80 | cc));
3234       emit_int32(offs - long_size);
3235     }
3236   } else {
3237 #ifdef ASSERT
3238     warning("reversing conditional branch");
3239 #endif /* ASSERT */
3240     Label skip;
3241     jccb(reverse[cc], skip);
3242     lea(rscratch1, dst);
3243     Assembler::jmp(rscratch1);
3244     bind(skip);
3245   }
3246 }
3247 
3248 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3249   if (reachable(src)) {
3250     Assembler::ldmxcsr(as_Address(src));
3251   } else {
3252     lea(rscratch1, src);
3253     Assembler::ldmxcsr(Address(rscratch1, 0));
3254   }
3255 }
3256 
3257 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3258   int off;
3259   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3260     off = offset();
3261     movsbl(dst, src); // movsxb
3262   } else {
3263     off = load_unsigned_byte(dst, src);
3264     shll(dst, 24);
3265     sarl(dst, 24);
3266   }
3267   return off;
3268 }
3269 
3270 // Note: load_signed_short used to be called load_signed_word.
3271 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3272 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3273 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3274 int MacroAssembler::load_signed_short(Register dst, Address src) {
3275   int off;
3276   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3277     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3278     // version but this is what 64bit has always done. This seems to imply
3279     // that users are only using 32bits worth.
3280     off = offset();
3281     movswl(dst, src); // movsxw
3282   } else {
3283     off = load_unsigned_short(dst, src);
3284     shll(dst, 16);
3285     sarl(dst, 16);
3286   }
3287   return off;
3288 }
3289 
3290 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3291   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3292   // and "3.9 Partial Register Penalties", p. 22).
3293   int off;
3294   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3295     off = offset();
3296     movzbl(dst, src); // movzxb
3297   } else {
3298     xorl(dst, dst);
3299     off = offset();
3300     movb(dst, src);
3301   }
3302   return off;
3303 }
3304 
3305 // Note: load_unsigned_short used to be called load_unsigned_word.
3306 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3307   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3308   // and "3.9 Partial Register Penalties", p. 22).
3309   int off;
3310   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3311     off = offset();
3312     movzwl(dst, src); // movzxw
3313   } else {
3314     xorl(dst, dst);
3315     off = offset();
3316     movw(dst, src);
3317   }
3318   return off;
3319 }
3320 
3321 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3322   switch (size_in_bytes) {
3323 #ifndef _LP64
3324   case  8:
3325     assert(dst2 != noreg, "second dest register required");
3326     movl(dst,  src);
3327     movl(dst2, src.plus_disp(BytesPerInt));
3328     break;
3329 #else
3330   case  8:  movq(dst, src); break;
3331 #endif
3332   case  4:  movl(dst, src); break;
3333   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3334   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3335   default:  ShouldNotReachHere();
3336   }
3337 }
3338 
3339 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3340   switch (size_in_bytes) {
3341 #ifndef _LP64
3342   case  8:
3343     assert(src2 != noreg, "second source register required");
3344     movl(dst,                        src);
3345     movl(dst.plus_disp(BytesPerInt), src2);
3346     break;
3347 #else
3348   case  8:  movq(dst, src); break;
3349 #endif
3350   case  4:  movl(dst, src); break;
3351   case  2:  movw(dst, src); break;
3352   case  1:  movb(dst, src); break;
3353   default:  ShouldNotReachHere();
3354   }
3355 }
3356 
3357 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3358   if (reachable(dst)) {
3359     movl(as_Address(dst), src);
3360   } else {
3361     lea(rscratch1, dst);
3362     movl(Address(rscratch1, 0), src);
3363   }
3364 }
3365 
3366 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3367   if (reachable(src)) {
3368     movl(dst, as_Address(src));
3369   } else {
3370     lea(rscratch1, src);
3371     movl(dst, Address(rscratch1, 0));
3372   }
3373 }
3374 
3375 // C++ bool manipulation
3376 
3377 void MacroAssembler::movbool(Register dst, Address src) {
3378   if(sizeof(bool) == 1)
3379     movb(dst, src);
3380   else if(sizeof(bool) == 2)
3381     movw(dst, src);
3382   else if(sizeof(bool) == 4)
3383     movl(dst, src);
3384   else
3385     // unsupported
3386     ShouldNotReachHere();
3387 }
3388 
3389 void MacroAssembler::movbool(Address dst, bool boolconst) {
3390   if(sizeof(bool) == 1)
3391     movb(dst, (int) boolconst);
3392   else if(sizeof(bool) == 2)
3393     movw(dst, (int) boolconst);
3394   else if(sizeof(bool) == 4)
3395     movl(dst, (int) boolconst);
3396   else
3397     // unsupported
3398     ShouldNotReachHere();
3399 }
3400 
3401 void MacroAssembler::movbool(Address dst, Register src) {
3402   if(sizeof(bool) == 1)
3403     movb(dst, src);
3404   else if(sizeof(bool) == 2)
3405     movw(dst, src);
3406   else if(sizeof(bool) == 4)
3407     movl(dst, src);
3408   else
3409     // unsupported
3410     ShouldNotReachHere();
3411 }
3412 
3413 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3414   movb(as_Address(dst), src);
3415 }
3416 
3417 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3418   if (reachable(src)) {
3419     movdl(dst, as_Address(src));
3420   } else {
3421     lea(rscratch1, src);
3422     movdl(dst, Address(rscratch1, 0));
3423   }
3424 }
3425 
3426 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3427   if (reachable(src)) {
3428     movq(dst, as_Address(src));
3429   } else {
3430     lea(rscratch1, src);
3431     movq(dst, Address(rscratch1, 0));
3432   }
3433 }
3434 
3435 void MacroAssembler::setvectmask(Register dst, Register src) {
3436   Assembler::movl(dst, 1);
3437   Assembler::shlxl(dst, dst, src);
3438   Assembler::decl(dst);
3439   Assembler::kmovdl(k1, dst);
3440   Assembler::movl(dst, src);
3441 }
3442 
3443 void MacroAssembler::restorevectmask() {
3444   Assembler::knotwl(k1, k0);
3445 }
3446 
3447 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3448   if (reachable(src)) {
3449     if (UseXmmLoadAndClearUpper) {
3450       movsd (dst, as_Address(src));
3451     } else {
3452       movlpd(dst, as_Address(src));
3453     }
3454   } else {
3455     lea(rscratch1, src);
3456     if (UseXmmLoadAndClearUpper) {
3457       movsd (dst, Address(rscratch1, 0));
3458     } else {
3459       movlpd(dst, Address(rscratch1, 0));
3460     }
3461   }
3462 }
3463 
3464 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3465   if (reachable(src)) {
3466     movss(dst, as_Address(src));
3467   } else {
3468     lea(rscratch1, src);
3469     movss(dst, Address(rscratch1, 0));
3470   }
3471 }
3472 
3473 void MacroAssembler::movptr(Register dst, Register src) {
3474   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3475 }
3476 
3477 void MacroAssembler::movptr(Register dst, Address src) {
3478   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3479 }
3480 
3481 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3482 void MacroAssembler::movptr(Register dst, intptr_t src) {
3483   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3484 }
3485 
3486 void MacroAssembler::movptr(Address dst, Register src) {
3487   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3488 }
3489 
3490 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3491   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3492     Assembler::vextractf32x4(dst, src, 0);
3493   } else {
3494     Assembler::movdqu(dst, src);
3495   }
3496 }
3497 
3498 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3499   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3500     Assembler::vinsertf32x4(dst, dst, src, 0);
3501   } else {
3502     Assembler::movdqu(dst, src);
3503   }
3504 }
3505 
3506 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3507   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3508     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3509   } else {
3510     Assembler::movdqu(dst, src);
3511   }
3512 }
3513 
3514 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3515   if (reachable(src)) {
3516     movdqu(dst, as_Address(src));
3517   } else {
3518     lea(scratchReg, src);
3519     movdqu(dst, Address(scratchReg, 0));
3520   }
3521 }
3522 
3523 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3524   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3525     vextractf64x4_low(dst, src);
3526   } else {
3527     Assembler::vmovdqu(dst, src);
3528   }
3529 }
3530 
3531 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3532   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3533     vinsertf64x4_low(dst, src);
3534   } else {
3535     Assembler::vmovdqu(dst, src);
3536   }
3537 }
3538 
3539 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3540   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3541     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3542   }
3543   else {
3544     Assembler::vmovdqu(dst, src);
3545   }
3546 }
3547 
3548 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3549   if (reachable(src)) {
3550     vmovdqu(dst, as_Address(src));
3551   }
3552   else {
3553     lea(rscratch1, src);
3554     vmovdqu(dst, Address(rscratch1, 0));
3555   }
3556 }
3557 
3558 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3559   if (reachable(src)) {
3560     Assembler::movdqa(dst, as_Address(src));
3561   } else {
3562     lea(rscratch1, src);
3563     Assembler::movdqa(dst, Address(rscratch1, 0));
3564   }
3565 }
3566 
3567 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3568   if (reachable(src)) {
3569     Assembler::movsd(dst, as_Address(src));
3570   } else {
3571     lea(rscratch1, src);
3572     Assembler::movsd(dst, Address(rscratch1, 0));
3573   }
3574 }
3575 
3576 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3577   if (reachable(src)) {
3578     Assembler::movss(dst, as_Address(src));
3579   } else {
3580     lea(rscratch1, src);
3581     Assembler::movss(dst, Address(rscratch1, 0));
3582   }
3583 }
3584 
3585 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3586   if (reachable(src)) {
3587     Assembler::mulsd(dst, as_Address(src));
3588   } else {
3589     lea(rscratch1, src);
3590     Assembler::mulsd(dst, Address(rscratch1, 0));
3591   }
3592 }
3593 
3594 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3595   if (reachable(src)) {
3596     Assembler::mulss(dst, as_Address(src));
3597   } else {
3598     lea(rscratch1, src);
3599     Assembler::mulss(dst, Address(rscratch1, 0));
3600   }
3601 }
3602 
3603 void MacroAssembler::null_check(Register reg, int offset) {
3604   if (needs_explicit_null_check(offset)) {
3605     // provoke OS NULL exception if reg = NULL by
3606     // accessing M[reg] w/o changing any (non-CC) registers
3607     // NOTE: cmpl is plenty here to provoke a segv
3608     cmpptr(rax, Address(reg, 0));
3609     // Note: should probably use testl(rax, Address(reg, 0));
3610     //       may be shorter code (however, this version of
3611     //       testl needs to be implemented first)
3612   } else {
3613     // nothing to do, (later) access of M[reg + offset]
3614     // will provoke OS NULL exception if reg = NULL
3615   }
3616 }
3617 
3618 void MacroAssembler::os_breakpoint() {
3619   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3620   // (e.g., MSVC can't call ps() otherwise)
3621   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3622 }
3623 
3624 #ifdef _LP64
3625 #define XSTATE_BV 0x200
3626 #endif
3627 
3628 void MacroAssembler::pop_CPU_state() {
3629   pop_FPU_state();
3630   pop_IU_state();
3631 }
3632 
3633 void MacroAssembler::pop_FPU_state() {
3634 #ifndef _LP64
3635   frstor(Address(rsp, 0));
3636 #else
3637   fxrstor(Address(rsp, 0));
3638 #endif
3639   addptr(rsp, FPUStateSizeInWords * wordSize);
3640 }
3641 
3642 void MacroAssembler::pop_IU_state() {
3643   popa();
3644   LP64_ONLY(addq(rsp, 8));
3645   popf();
3646 }
3647 
3648 // Save Integer and Float state
3649 // Warning: Stack must be 16 byte aligned (64bit)
3650 void MacroAssembler::push_CPU_state() {
3651   push_IU_state();
3652   push_FPU_state();
3653 }
3654 
3655 void MacroAssembler::push_FPU_state() {
3656   subptr(rsp, FPUStateSizeInWords * wordSize);
3657 #ifndef _LP64
3658   fnsave(Address(rsp, 0));
3659   fwait();
3660 #else
3661   fxsave(Address(rsp, 0));
3662 #endif // LP64
3663 }
3664 
3665 void MacroAssembler::push_IU_state() {
3666   // Push flags first because pusha kills them
3667   pushf();
3668   // Make sure rsp stays 16-byte aligned
3669   LP64_ONLY(subq(rsp, 8));
3670   pusha();
3671 }
3672 
3673 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3674   if (!java_thread->is_valid()) {
3675     java_thread = rdi;
3676     get_thread(java_thread);
3677   }
3678   // we must set sp to zero to clear frame
3679   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3680   if (clear_fp) {
3681     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3682   }
3683 
3684   // Always clear the pc because it could have been set by make_walkable()
3685   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3686 
3687 }
3688 
3689 void MacroAssembler::restore_rax(Register tmp) {
3690   if (tmp == noreg) pop(rax);
3691   else if (tmp != rax) mov(rax, tmp);
3692 }
3693 
3694 void MacroAssembler::round_to(Register reg, int modulus) {
3695   addptr(reg, modulus - 1);
3696   andptr(reg, -modulus);
3697 }
3698 
3699 void MacroAssembler::save_rax(Register tmp) {
3700   if (tmp == noreg) push(rax);
3701   else if (tmp != rax) mov(tmp, rax);
3702 }
3703 
3704 // Write serialization page so VM thread can do a pseudo remote membar.
3705 // We use the current thread pointer to calculate a thread specific
3706 // offset to write to within the page. This minimizes bus traffic
3707 // due to cache line collision.
3708 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3709   movl(tmp, thread);
3710   shrl(tmp, os::get_serialize_page_shift_count());
3711   andl(tmp, (os::vm_page_size() - sizeof(int)));
3712 
3713   Address index(noreg, tmp, Address::times_1);
3714   ExternalAddress page(os::get_memory_serialize_page());
3715 
3716   // Size of store must match masking code above
3717   movl(as_Address(ArrayAddress(page, index)), tmp);
3718 }
3719 
3720 // Special Shenandoah CAS implementation that handles false negatives
3721 // due to concurrent evacuation.
3722 #ifndef _LP64
3723 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3724                               bool exchange,
3725                               Register tmp1, Register tmp2) {
3726   // Shenandoah has no 32-bit version for this.
3727   Unimplemented();
3728 }
3729 #else
3730 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3731                               bool exchange,
3732                               Register tmp1, Register tmp2) {
3733   assert(UseShenandoahGC, "Should only be used with Shenandoah");
3734   assert(ShenandoahCASBarrier, "Should only be used when CAS barrier is enabled");
3735   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
3736 
3737   Label retry, done;
3738 
3739   // Remember oldval for retry logic below
3740   if (UseCompressedOops) {
3741     movl(tmp1, oldval);
3742   } else {
3743     movptr(tmp1, oldval);
3744   }
3745 
3746   // Step 1. Try to CAS with given arguments. If successful, then we are done,
3747   // and can safely return.
3748   if (os::is_MP()) lock();
3749   if (UseCompressedOops) {
3750     cmpxchgl(newval, addr);
3751   } else {
3752     cmpxchgptr(newval, addr);
3753   }
3754   jcc(Assembler::equal, done, true);
3755 
3756   // Step 2. CAS had failed. This may be a false negative.
3757   //
3758   // The trouble comes when we compare the to-space pointer with the from-space
3759   // pointer to the same object. To resolve this, it will suffice to read both
3760   // oldval and the value from memory through the read barriers -- this will give
3761   // both to-space pointers. If they mismatch, then it was a legitimate failure.
3762   //
3763   if (UseCompressedOops) {
3764     decode_heap_oop(tmp1);
3765   }
3766   oopDesc::bs()->interpreter_read_barrier(this, tmp1);
3767 
3768   if (UseCompressedOops) {
3769     movl(tmp2, oldval);
3770     decode_heap_oop(tmp2);
3771   } else {
3772     movptr(tmp2, oldval);
3773   }
3774   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3775 
3776   cmpptr(tmp1, tmp2);
3777   jcc(Assembler::notEqual, done, true);
3778 
3779   // Step 3. Try to CAS again with resolved to-space pointers.
3780   //
3781   // Corner case: it may happen that somebody stored the from-space pointer
3782   // to memory while we were preparing for retry. Therefore, we can fail again
3783   // on retry, and so need to do this in loop, always re-reading the failure
3784   // witness through the read barrier.
3785   bind(retry);
3786   if (os::is_MP()) lock();
3787   if (UseCompressedOops) {
3788     cmpxchgl(newval, addr);
3789   } else {
3790     cmpxchgptr(newval, addr);
3791   }
3792   jcc(Assembler::equal, done, true);
3793 
3794   if (UseCompressedOops) {
3795     movl(tmp2, oldval);
3796     decode_heap_oop(tmp2);
3797   } else {
3798     movptr(tmp2, oldval);
3799   }
3800   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3801 
3802   cmpptr(tmp1, tmp2);
3803   jcc(Assembler::equal, retry, true);
3804 
3805   // Step 4. If we need a boolean result out of CAS, check the flag again,
3806   // and promote the result. Note that we handle the flag from both the CAS
3807   // itself and from the retry loop.
3808   bind(done);
3809   if (!exchange) {
3810     setb(Assembler::equal, res);
3811     movzbl(res, res);
3812   }
3813 }
3814 #endif
3815 
3816 // Calls to C land
3817 //
3818 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3819 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3820 // has to be reset to 0. This is required to allow proper stack traversal.
3821 void MacroAssembler::set_last_Java_frame(Register java_thread,
3822                                          Register last_java_sp,
3823                                          Register last_java_fp,
3824                                          address  last_java_pc) {
3825   // determine java_thread register
3826   if (!java_thread->is_valid()) {
3827     java_thread = rdi;
3828     get_thread(java_thread);
3829   }
3830   // determine last_java_sp register
3831   if (!last_java_sp->is_valid()) {
3832     last_java_sp = rsp;
3833   }
3834 
3835   // last_java_fp is optional
3836 
3837   if (last_java_fp->is_valid()) {
3838     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3839   }
3840 
3841   // last_java_pc is optional
3842 
3843   if (last_java_pc != NULL) {
3844     lea(Address(java_thread,
3845                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3846         InternalAddress(last_java_pc));
3847 
3848   }
3849   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3850 }
3851 
3852 void MacroAssembler::shlptr(Register dst, int imm8) {
3853   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3854 }
3855 
3856 void MacroAssembler::shrptr(Register dst, int imm8) {
3857   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3858 }
3859 
3860 void MacroAssembler::sign_extend_byte(Register reg) {
3861   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3862     movsbl(reg, reg); // movsxb
3863   } else {
3864     shll(reg, 24);
3865     sarl(reg, 24);
3866   }
3867 }
3868 
3869 void MacroAssembler::sign_extend_short(Register reg) {
3870   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3871     movswl(reg, reg); // movsxw
3872   } else {
3873     shll(reg, 16);
3874     sarl(reg, 16);
3875   }
3876 }
3877 
3878 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3879   assert(reachable(src), "Address should be reachable");
3880   testl(dst, as_Address(src));
3881 }
3882 
3883 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3884   int dst_enc = dst->encoding();
3885   int src_enc = src->encoding();
3886   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3887     Assembler::pcmpeqb(dst, src);
3888   } else if ((dst_enc < 16) && (src_enc < 16)) {
3889     Assembler::pcmpeqb(dst, src);
3890   } else if (src_enc < 16) {
3891     subptr(rsp, 64);
3892     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3893     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3894     Assembler::pcmpeqb(xmm0, src);
3895     movdqu(dst, xmm0);
3896     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3897     addptr(rsp, 64);
3898   } else if (dst_enc < 16) {
3899     subptr(rsp, 64);
3900     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3901     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3902     Assembler::pcmpeqb(dst, xmm0);
3903     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3904     addptr(rsp, 64);
3905   } else {
3906     subptr(rsp, 64);
3907     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3908     subptr(rsp, 64);
3909     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3910     movdqu(xmm0, src);
3911     movdqu(xmm1, dst);
3912     Assembler::pcmpeqb(xmm1, xmm0);
3913     movdqu(dst, xmm1);
3914     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3915     addptr(rsp, 64);
3916     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3917     addptr(rsp, 64);
3918   }
3919 }
3920 
3921 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3922   int dst_enc = dst->encoding();
3923   int src_enc = src->encoding();
3924   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3925     Assembler::pcmpeqw(dst, src);
3926   } else if ((dst_enc < 16) && (src_enc < 16)) {
3927     Assembler::pcmpeqw(dst, src);
3928   } else if (src_enc < 16) {
3929     subptr(rsp, 64);
3930     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3931     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3932     Assembler::pcmpeqw(xmm0, src);
3933     movdqu(dst, xmm0);
3934     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3935     addptr(rsp, 64);
3936   } else if (dst_enc < 16) {
3937     subptr(rsp, 64);
3938     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3939     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3940     Assembler::pcmpeqw(dst, xmm0);
3941     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3942     addptr(rsp, 64);
3943   } else {
3944     subptr(rsp, 64);
3945     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3946     subptr(rsp, 64);
3947     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3948     movdqu(xmm0, src);
3949     movdqu(xmm1, dst);
3950     Assembler::pcmpeqw(xmm1, xmm0);
3951     movdqu(dst, xmm1);
3952     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3953     addptr(rsp, 64);
3954     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3955     addptr(rsp, 64);
3956   }
3957 }
3958 
3959 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3960   int dst_enc = dst->encoding();
3961   if (dst_enc < 16) {
3962     Assembler::pcmpestri(dst, src, imm8);
3963   } else {
3964     subptr(rsp, 64);
3965     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3966     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3967     Assembler::pcmpestri(xmm0, src, imm8);
3968     movdqu(dst, xmm0);
3969     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3970     addptr(rsp, 64);
3971   }
3972 }
3973 
3974 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3975   int dst_enc = dst->encoding();
3976   int src_enc = src->encoding();
3977   if ((dst_enc < 16) && (src_enc < 16)) {
3978     Assembler::pcmpestri(dst, src, imm8);
3979   } else if (src_enc < 16) {
3980     subptr(rsp, 64);
3981     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3982     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3983     Assembler::pcmpestri(xmm0, src, imm8);
3984     movdqu(dst, xmm0);
3985     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3986     addptr(rsp, 64);
3987   } else if (dst_enc < 16) {
3988     subptr(rsp, 64);
3989     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3990     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3991     Assembler::pcmpestri(dst, xmm0, imm8);
3992     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3993     addptr(rsp, 64);
3994   } else {
3995     subptr(rsp, 64);
3996     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3997     subptr(rsp, 64);
3998     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3999     movdqu(xmm0, src);
4000     movdqu(xmm1, dst);
4001     Assembler::pcmpestri(xmm1, xmm0, imm8);
4002     movdqu(dst, xmm1);
4003     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4004     addptr(rsp, 64);
4005     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4006     addptr(rsp, 64);
4007   }
4008 }
4009 
4010 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4011   int dst_enc = dst->encoding();
4012   int src_enc = src->encoding();
4013   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4014     Assembler::pmovzxbw(dst, src);
4015   } else if ((dst_enc < 16) && (src_enc < 16)) {
4016     Assembler::pmovzxbw(dst, src);
4017   } else if (src_enc < 16) {
4018     subptr(rsp, 64);
4019     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4020     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4021     Assembler::pmovzxbw(xmm0, src);
4022     movdqu(dst, xmm0);
4023     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4024     addptr(rsp, 64);
4025   } else if (dst_enc < 16) {
4026     subptr(rsp, 64);
4027     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4028     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4029     Assembler::pmovzxbw(dst, xmm0);
4030     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4031     addptr(rsp, 64);
4032   } else {
4033     subptr(rsp, 64);
4034     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4035     subptr(rsp, 64);
4036     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4037     movdqu(xmm0, src);
4038     movdqu(xmm1, dst);
4039     Assembler::pmovzxbw(xmm1, xmm0);
4040     movdqu(dst, xmm1);
4041     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4042     addptr(rsp, 64);
4043     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4044     addptr(rsp, 64);
4045   }
4046 }
4047 
4048 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4049   int dst_enc = dst->encoding();
4050   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4051     Assembler::pmovzxbw(dst, src);
4052   } else if (dst_enc < 16) {
4053     Assembler::pmovzxbw(dst, src);
4054   } else {
4055     subptr(rsp, 64);
4056     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4057     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4058     Assembler::pmovzxbw(xmm0, src);
4059     movdqu(dst, xmm0);
4060     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4061     addptr(rsp, 64);
4062   }
4063 }
4064 
4065 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4066   int src_enc = src->encoding();
4067   if (src_enc < 16) {
4068     Assembler::pmovmskb(dst, src);
4069   } else {
4070     subptr(rsp, 64);
4071     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4072     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4073     Assembler::pmovmskb(dst, xmm0);
4074     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4075     addptr(rsp, 64);
4076   }
4077 }
4078 
4079 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4080   int dst_enc = dst->encoding();
4081   int src_enc = src->encoding();
4082   if ((dst_enc < 16) && (src_enc < 16)) {
4083     Assembler::ptest(dst, src);
4084   } else if (src_enc < 16) {
4085     subptr(rsp, 64);
4086     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4087     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4088     Assembler::ptest(xmm0, src);
4089     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4090     addptr(rsp, 64);
4091   } else if (dst_enc < 16) {
4092     subptr(rsp, 64);
4093     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4094     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4095     Assembler::ptest(dst, xmm0);
4096     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4097     addptr(rsp, 64);
4098   } else {
4099     subptr(rsp, 64);
4100     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4101     subptr(rsp, 64);
4102     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4103     movdqu(xmm0, src);
4104     movdqu(xmm1, dst);
4105     Assembler::ptest(xmm1, xmm0);
4106     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4107     addptr(rsp, 64);
4108     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4109     addptr(rsp, 64);
4110   }
4111 }
4112 
4113 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4114   if (reachable(src)) {
4115     Assembler::sqrtsd(dst, as_Address(src));
4116   } else {
4117     lea(rscratch1, src);
4118     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4119   }
4120 }
4121 
4122 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4123   if (reachable(src)) {
4124     Assembler::sqrtss(dst, as_Address(src));
4125   } else {
4126     lea(rscratch1, src);
4127     Assembler::sqrtss(dst, Address(rscratch1, 0));
4128   }
4129 }
4130 
4131 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4132   if (reachable(src)) {
4133     Assembler::subsd(dst, as_Address(src));
4134   } else {
4135     lea(rscratch1, src);
4136     Assembler::subsd(dst, Address(rscratch1, 0));
4137   }
4138 }
4139 
4140 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4141   if (reachable(src)) {
4142     Assembler::subss(dst, as_Address(src));
4143   } else {
4144     lea(rscratch1, src);
4145     Assembler::subss(dst, Address(rscratch1, 0));
4146   }
4147 }
4148 
4149 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4150   if (reachable(src)) {
4151     Assembler::ucomisd(dst, as_Address(src));
4152   } else {
4153     lea(rscratch1, src);
4154     Assembler::ucomisd(dst, Address(rscratch1, 0));
4155   }
4156 }
4157 
4158 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4159   if (reachable(src)) {
4160     Assembler::ucomiss(dst, as_Address(src));
4161   } else {
4162     lea(rscratch1, src);
4163     Assembler::ucomiss(dst, Address(rscratch1, 0));
4164   }
4165 }
4166 
4167 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4168   // Used in sign-bit flipping with aligned address.
4169   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4170   if (reachable(src)) {
4171     Assembler::xorpd(dst, as_Address(src));
4172   } else {
4173     lea(rscratch1, src);
4174     Assembler::xorpd(dst, Address(rscratch1, 0));
4175   }
4176 }
4177 
4178 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4179   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4180     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4181   }
4182   else {
4183     Assembler::xorpd(dst, src);
4184   }
4185 }
4186 
4187 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4188   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4189     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4190   } else {
4191     Assembler::xorps(dst, src);
4192   }
4193 }
4194 
4195 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4196   // Used in sign-bit flipping with aligned address.
4197   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4198   if (reachable(src)) {
4199     Assembler::xorps(dst, as_Address(src));
4200   } else {
4201     lea(rscratch1, src);
4202     Assembler::xorps(dst, Address(rscratch1, 0));
4203   }
4204 }
4205 
4206 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4207   // Used in sign-bit flipping with aligned address.
4208   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4209   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4210   if (reachable(src)) {
4211     Assembler::pshufb(dst, as_Address(src));
4212   } else {
4213     lea(rscratch1, src);
4214     Assembler::pshufb(dst, Address(rscratch1, 0));
4215   }
4216 }
4217 
4218 // AVX 3-operands instructions
4219 
4220 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4221   if (reachable(src)) {
4222     vaddsd(dst, nds, as_Address(src));
4223   } else {
4224     lea(rscratch1, src);
4225     vaddsd(dst, nds, Address(rscratch1, 0));
4226   }
4227 }
4228 
4229 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4230   if (reachable(src)) {
4231     vaddss(dst, nds, as_Address(src));
4232   } else {
4233     lea(rscratch1, src);
4234     vaddss(dst, nds, Address(rscratch1, 0));
4235   }
4236 }
4237 
4238 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4239   int dst_enc = dst->encoding();
4240   int nds_enc = nds->encoding();
4241   int src_enc = src->encoding();
4242   if ((dst_enc < 16) && (nds_enc < 16)) {
4243     vandps(dst, nds, negate_field, vector_len);
4244   } else if ((src_enc < 16) && (dst_enc < 16)) {
4245     movss(src, nds);
4246     vandps(dst, src, negate_field, vector_len);
4247   } else if (src_enc < 16) {
4248     movss(src, nds);
4249     vandps(src, src, negate_field, vector_len);
4250     movss(dst, src);
4251   } else if (dst_enc < 16) {
4252     movdqu(src, xmm0);
4253     movss(xmm0, nds);
4254     vandps(dst, xmm0, negate_field, vector_len);
4255     movdqu(xmm0, src);
4256   } else if (nds_enc < 16) {
4257     movdqu(src, xmm0);
4258     vandps(xmm0, nds, negate_field, vector_len);
4259     movss(dst, xmm0);
4260     movdqu(xmm0, src);
4261   } else {
4262     movdqu(src, xmm0);
4263     movss(xmm0, nds);
4264     vandps(xmm0, xmm0, negate_field, vector_len);
4265     movss(dst, xmm0);
4266     movdqu(xmm0, src);
4267   }
4268 }
4269 
4270 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4271   int dst_enc = dst->encoding();
4272   int nds_enc = nds->encoding();
4273   int src_enc = src->encoding();
4274   if ((dst_enc < 16) && (nds_enc < 16)) {
4275     vandpd(dst, nds, negate_field, vector_len);
4276   } else if ((src_enc < 16) && (dst_enc < 16)) {
4277     movsd(src, nds);
4278     vandpd(dst, src, negate_field, vector_len);
4279   } else if (src_enc < 16) {
4280     movsd(src, nds);
4281     vandpd(src, src, negate_field, vector_len);
4282     movsd(dst, src);
4283   } else if (dst_enc < 16) {
4284     movdqu(src, xmm0);
4285     movsd(xmm0, nds);
4286     vandpd(dst, xmm0, negate_field, vector_len);
4287     movdqu(xmm0, src);
4288   } else if (nds_enc < 16) {
4289     movdqu(src, xmm0);
4290     vandpd(xmm0, nds, negate_field, vector_len);
4291     movsd(dst, xmm0);
4292     movdqu(xmm0, src);
4293   } else {
4294     movdqu(src, xmm0);
4295     movsd(xmm0, nds);
4296     vandpd(xmm0, xmm0, negate_field, vector_len);
4297     movsd(dst, xmm0);
4298     movdqu(xmm0, src);
4299   }
4300 }
4301 
4302 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4303   int dst_enc = dst->encoding();
4304   int nds_enc = nds->encoding();
4305   int src_enc = src->encoding();
4306   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4307     Assembler::vpaddb(dst, nds, src, vector_len);
4308   } else if ((dst_enc < 16) && (src_enc < 16)) {
4309     Assembler::vpaddb(dst, dst, src, vector_len);
4310   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4311     // use nds as scratch for src
4312     evmovdqul(nds, src, Assembler::AVX_512bit);
4313     Assembler::vpaddb(dst, dst, nds, vector_len);
4314   } else if ((src_enc < 16) && (nds_enc < 16)) {
4315     // use nds as scratch for dst
4316     evmovdqul(nds, dst, Assembler::AVX_512bit);
4317     Assembler::vpaddb(nds, nds, src, vector_len);
4318     evmovdqul(dst, nds, Assembler::AVX_512bit);
4319   } else if (dst_enc < 16) {
4320     // use nds as scatch for xmm0 to hold src
4321     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4322     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4323     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4324     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4325   } else {
4326     // worse case scenario, all regs are in the upper bank
4327     subptr(rsp, 64);
4328     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4329     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4330     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4331     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4332     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4333     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4334     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4335     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4336     addptr(rsp, 64);
4337   }
4338 }
4339 
4340 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4341   int dst_enc = dst->encoding();
4342   int nds_enc = nds->encoding();
4343   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4344     Assembler::vpaddb(dst, nds, src, vector_len);
4345   } else if (dst_enc < 16) {
4346     Assembler::vpaddb(dst, dst, src, vector_len);
4347   } else if (nds_enc < 16) {
4348     // implies dst_enc in upper bank with src as scratch
4349     evmovdqul(nds, dst, Assembler::AVX_512bit);
4350     Assembler::vpaddb(nds, nds, src, vector_len);
4351     evmovdqul(dst, nds, Assembler::AVX_512bit);
4352   } else {
4353     // worse case scenario, all regs in upper bank
4354     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4355     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4356     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4357     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4358   }
4359 }
4360 
4361 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4362   int dst_enc = dst->encoding();
4363   int nds_enc = nds->encoding();
4364   int src_enc = src->encoding();
4365   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4366     Assembler::vpaddw(dst, nds, src, vector_len);
4367   } else if ((dst_enc < 16) && (src_enc < 16)) {
4368     Assembler::vpaddw(dst, dst, src, vector_len);
4369   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4370     // use nds as scratch for src
4371     evmovdqul(nds, src, Assembler::AVX_512bit);
4372     Assembler::vpaddw(dst, dst, nds, vector_len);
4373   } else if ((src_enc < 16) && (nds_enc < 16)) {
4374     // use nds as scratch for dst
4375     evmovdqul(nds, dst, Assembler::AVX_512bit);
4376     Assembler::vpaddw(nds, nds, src, vector_len);
4377     evmovdqul(dst, nds, Assembler::AVX_512bit);
4378   } else if (dst_enc < 16) {
4379     // use nds as scatch for xmm0 to hold src
4380     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4381     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4382     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4383     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4384   } else {
4385     // worse case scenario, all regs are in the upper bank
4386     subptr(rsp, 64);
4387     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4388     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4389     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4390     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4391     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4392     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4393     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4394     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4395     addptr(rsp, 64);
4396   }
4397 }
4398 
4399 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4400   int dst_enc = dst->encoding();
4401   int nds_enc = nds->encoding();
4402   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4403     Assembler::vpaddw(dst, nds, src, vector_len);
4404   } else if (dst_enc < 16) {
4405     Assembler::vpaddw(dst, dst, src, vector_len);
4406   } else if (nds_enc < 16) {
4407     // implies dst_enc in upper bank with src as scratch
4408     evmovdqul(nds, dst, Assembler::AVX_512bit);
4409     Assembler::vpaddw(nds, nds, src, vector_len);
4410     evmovdqul(dst, nds, Assembler::AVX_512bit);
4411   } else {
4412     // worse case scenario, all regs in upper bank
4413     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4414     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4415     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4416     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4417   }
4418 }
4419 
4420 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4421   if (reachable(src)) {
4422     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4423   } else {
4424     lea(rscratch1, src);
4425     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4426   }
4427 }
4428 
4429 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4430   int dst_enc = dst->encoding();
4431   int src_enc = src->encoding();
4432   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4433     Assembler::vpbroadcastw(dst, src);
4434   } else if ((dst_enc < 16) && (src_enc < 16)) {
4435     Assembler::vpbroadcastw(dst, src);
4436   } else if (src_enc < 16) {
4437     subptr(rsp, 64);
4438     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4439     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4440     Assembler::vpbroadcastw(xmm0, src);
4441     movdqu(dst, xmm0);
4442     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4443     addptr(rsp, 64);
4444   } else if (dst_enc < 16) {
4445     subptr(rsp, 64);
4446     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4447     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4448     Assembler::vpbroadcastw(dst, xmm0);
4449     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4450     addptr(rsp, 64);
4451   } else {
4452     subptr(rsp, 64);
4453     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4454     subptr(rsp, 64);
4455     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4456     movdqu(xmm0, src);
4457     movdqu(xmm1, dst);
4458     Assembler::vpbroadcastw(xmm1, xmm0);
4459     movdqu(dst, xmm1);
4460     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4461     addptr(rsp, 64);
4462     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4463     addptr(rsp, 64);
4464   }
4465 }
4466 
4467 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4468   int dst_enc = dst->encoding();
4469   int nds_enc = nds->encoding();
4470   int src_enc = src->encoding();
4471   assert(dst_enc == nds_enc, "");
4472   if ((dst_enc < 16) && (src_enc < 16)) {
4473     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4474   } else if (src_enc < 16) {
4475     subptr(rsp, 64);
4476     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4477     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4478     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4479     movdqu(dst, xmm0);
4480     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4481     addptr(rsp, 64);
4482   } else if (dst_enc < 16) {
4483     subptr(rsp, 64);
4484     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4485     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4486     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4487     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4488     addptr(rsp, 64);
4489   } else {
4490     subptr(rsp, 64);
4491     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4492     subptr(rsp, 64);
4493     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4494     movdqu(xmm0, src);
4495     movdqu(xmm1, dst);
4496     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4497     movdqu(dst, xmm1);
4498     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4499     addptr(rsp, 64);
4500     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4501     addptr(rsp, 64);
4502   }
4503 }
4504 
4505 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4506   int dst_enc = dst->encoding();
4507   int nds_enc = nds->encoding();
4508   int src_enc = src->encoding();
4509   assert(dst_enc == nds_enc, "");
4510   if ((dst_enc < 16) && (src_enc < 16)) {
4511     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4512   } else if (src_enc < 16) {
4513     subptr(rsp, 64);
4514     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4515     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4516     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4517     movdqu(dst, xmm0);
4518     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4519     addptr(rsp, 64);
4520   } else if (dst_enc < 16) {
4521     subptr(rsp, 64);
4522     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4523     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4524     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4525     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4526     addptr(rsp, 64);
4527   } else {
4528     subptr(rsp, 64);
4529     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4530     subptr(rsp, 64);
4531     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4532     movdqu(xmm0, src);
4533     movdqu(xmm1, dst);
4534     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4535     movdqu(dst, xmm1);
4536     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4537     addptr(rsp, 64);
4538     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4539     addptr(rsp, 64);
4540   }
4541 }
4542 
4543 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4544   int dst_enc = dst->encoding();
4545   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4546     Assembler::vpmovzxbw(dst, src, vector_len);
4547   } else if (dst_enc < 16) {
4548     Assembler::vpmovzxbw(dst, src, vector_len);
4549   } else {
4550     subptr(rsp, 64);
4551     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4552     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4553     Assembler::vpmovzxbw(xmm0, src, vector_len);
4554     movdqu(dst, xmm0);
4555     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4556     addptr(rsp, 64);
4557   }
4558 }
4559 
4560 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4561   int src_enc = src->encoding();
4562   if (src_enc < 16) {
4563     Assembler::vpmovmskb(dst, src);
4564   } else {
4565     subptr(rsp, 64);
4566     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4567     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4568     Assembler::vpmovmskb(dst, xmm0);
4569     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4570     addptr(rsp, 64);
4571   }
4572 }
4573 
4574 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4575   int dst_enc = dst->encoding();
4576   int nds_enc = nds->encoding();
4577   int src_enc = src->encoding();
4578   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4579     Assembler::vpmullw(dst, nds, src, vector_len);
4580   } else if ((dst_enc < 16) && (src_enc < 16)) {
4581     Assembler::vpmullw(dst, dst, src, vector_len);
4582   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4583     // use nds as scratch for src
4584     evmovdqul(nds, src, Assembler::AVX_512bit);
4585     Assembler::vpmullw(dst, dst, nds, vector_len);
4586   } else if ((src_enc < 16) && (nds_enc < 16)) {
4587     // use nds as scratch for dst
4588     evmovdqul(nds, dst, Assembler::AVX_512bit);
4589     Assembler::vpmullw(nds, nds, src, vector_len);
4590     evmovdqul(dst, nds, Assembler::AVX_512bit);
4591   } else if (dst_enc < 16) {
4592     // use nds as scatch for xmm0 to hold src
4593     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4594     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4595     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4596     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4597   } else {
4598     // worse case scenario, all regs are in the upper bank
4599     subptr(rsp, 64);
4600     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4601     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4603     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4604     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4605     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4606     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4607     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4608     addptr(rsp, 64);
4609   }
4610 }
4611 
4612 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4613   int dst_enc = dst->encoding();
4614   int nds_enc = nds->encoding();
4615   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4616     Assembler::vpmullw(dst, nds, src, vector_len);
4617   } else if (dst_enc < 16) {
4618     Assembler::vpmullw(dst, dst, src, vector_len);
4619   } else if (nds_enc < 16) {
4620     // implies dst_enc in upper bank with src as scratch
4621     evmovdqul(nds, dst, Assembler::AVX_512bit);
4622     Assembler::vpmullw(nds, nds, src, vector_len);
4623     evmovdqul(dst, nds, Assembler::AVX_512bit);
4624   } else {
4625     // worse case scenario, all regs in upper bank
4626     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4627     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4628     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4629     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4630   }
4631 }
4632 
4633 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4634   int dst_enc = dst->encoding();
4635   int nds_enc = nds->encoding();
4636   int src_enc = src->encoding();
4637   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4638     Assembler::vpsubb(dst, nds, src, vector_len);
4639   } else if ((dst_enc < 16) && (src_enc < 16)) {
4640     Assembler::vpsubb(dst, dst, src, vector_len);
4641   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4642     // use nds as scratch for src
4643     evmovdqul(nds, src, Assembler::AVX_512bit);
4644     Assembler::vpsubb(dst, dst, nds, vector_len);
4645   } else if ((src_enc < 16) && (nds_enc < 16)) {
4646     // use nds as scratch for dst
4647     evmovdqul(nds, dst, Assembler::AVX_512bit);
4648     Assembler::vpsubb(nds, nds, src, vector_len);
4649     evmovdqul(dst, nds, Assembler::AVX_512bit);
4650   } else if (dst_enc < 16) {
4651     // use nds as scatch for xmm0 to hold src
4652     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4653     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4654     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4655     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4656   } else {
4657     // worse case scenario, all regs are in the upper bank
4658     subptr(rsp, 64);
4659     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4660     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4661     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4662     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4663     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4664     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4665     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4666     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4667     addptr(rsp, 64);
4668   }
4669 }
4670 
4671 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4672   int dst_enc = dst->encoding();
4673   int nds_enc = nds->encoding();
4674   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4675     Assembler::vpsubb(dst, nds, src, vector_len);
4676   } else if (dst_enc < 16) {
4677     Assembler::vpsubb(dst, dst, src, vector_len);
4678   } else if (nds_enc < 16) {
4679     // implies dst_enc in upper bank with src as scratch
4680     evmovdqul(nds, dst, Assembler::AVX_512bit);
4681     Assembler::vpsubb(nds, nds, src, vector_len);
4682     evmovdqul(dst, nds, Assembler::AVX_512bit);
4683   } else {
4684     // worse case scenario, all regs in upper bank
4685     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4686     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4687     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4688     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4689   }
4690 }
4691 
4692 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4693   int dst_enc = dst->encoding();
4694   int nds_enc = nds->encoding();
4695   int src_enc = src->encoding();
4696   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4697     Assembler::vpsubw(dst, nds, src, vector_len);
4698   } else if ((dst_enc < 16) && (src_enc < 16)) {
4699     Assembler::vpsubw(dst, dst, src, vector_len);
4700   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4701     // use nds as scratch for src
4702     evmovdqul(nds, src, Assembler::AVX_512bit);
4703     Assembler::vpsubw(dst, dst, nds, vector_len);
4704   } else if ((src_enc < 16) && (nds_enc < 16)) {
4705     // use nds as scratch for dst
4706     evmovdqul(nds, dst, Assembler::AVX_512bit);
4707     Assembler::vpsubw(nds, nds, src, vector_len);
4708     evmovdqul(dst, nds, Assembler::AVX_512bit);
4709   } else if (dst_enc < 16) {
4710     // use nds as scatch for xmm0 to hold src
4711     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4712     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4713     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4714     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4715   } else {
4716     // worse case scenario, all regs are in the upper bank
4717     subptr(rsp, 64);
4718     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4719     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4720     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4721     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4722     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4723     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4724     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4725     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4726     addptr(rsp, 64);
4727   }
4728 }
4729 
4730 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4731   int dst_enc = dst->encoding();
4732   int nds_enc = nds->encoding();
4733   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4734     Assembler::vpsubw(dst, nds, src, vector_len);
4735   } else if (dst_enc < 16) {
4736     Assembler::vpsubw(dst, dst, src, vector_len);
4737   } else if (nds_enc < 16) {
4738     // implies dst_enc in upper bank with src as scratch
4739     evmovdqul(nds, dst, Assembler::AVX_512bit);
4740     Assembler::vpsubw(nds, nds, src, vector_len);
4741     evmovdqul(dst, nds, Assembler::AVX_512bit);
4742   } else {
4743     // worse case scenario, all regs in upper bank
4744     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4745     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4746     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4747     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4748   }
4749 }
4750 
4751 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4752   int dst_enc = dst->encoding();
4753   int nds_enc = nds->encoding();
4754   int shift_enc = shift->encoding();
4755   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4756     Assembler::vpsraw(dst, nds, shift, vector_len);
4757   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4758     Assembler::vpsraw(dst, dst, shift, vector_len);
4759   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4760     // use nds_enc as scratch with shift
4761     evmovdqul(nds, shift, Assembler::AVX_512bit);
4762     Assembler::vpsraw(dst, dst, nds, vector_len);
4763   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4764     // use nds as scratch with dst
4765     evmovdqul(nds, dst, Assembler::AVX_512bit);
4766     Assembler::vpsraw(nds, nds, shift, vector_len);
4767     evmovdqul(dst, nds, Assembler::AVX_512bit);
4768   } else if (dst_enc < 16) {
4769     // use nds to save a copy of xmm0 and hold shift
4770     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4771     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4772     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4773     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4774   } else if (nds_enc < 16) {
4775     // use nds as dest as temps
4776     evmovdqul(nds, dst, Assembler::AVX_512bit);
4777     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4778     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4779     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4780     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4781     evmovdqul(dst, nds, Assembler::AVX_512bit);
4782   } else {
4783     // worse case scenario, all regs are in the upper bank
4784     subptr(rsp, 64);
4785     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4786     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4787     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4788     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4789     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4790     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4791     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4792     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4793     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4794     addptr(rsp, 64);
4795   }
4796 }
4797 
4798 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4799   int dst_enc = dst->encoding();
4800   int nds_enc = nds->encoding();
4801   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4802     Assembler::vpsraw(dst, nds, shift, vector_len);
4803   } else if (dst_enc < 16) {
4804     Assembler::vpsraw(dst, dst, shift, vector_len);
4805   } else if (nds_enc < 16) {
4806     // use nds as scratch
4807     evmovdqul(nds, dst, Assembler::AVX_512bit);
4808     Assembler::vpsraw(nds, nds, shift, vector_len);
4809     evmovdqul(dst, nds, Assembler::AVX_512bit);
4810   } else {
4811     // use nds as scratch for xmm0
4812     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4813     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4814     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4815     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4816   }
4817 }
4818 
4819 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4820   int dst_enc = dst->encoding();
4821   int nds_enc = nds->encoding();
4822   int shift_enc = shift->encoding();
4823   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4824     Assembler::vpsrlw(dst, nds, shift, vector_len);
4825   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4826     Assembler::vpsrlw(dst, dst, shift, vector_len);
4827   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4828     // use nds_enc as scratch with shift
4829     evmovdqul(nds, shift, Assembler::AVX_512bit);
4830     Assembler::vpsrlw(dst, dst, nds, vector_len);
4831   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4832     // use nds as scratch with dst
4833     evmovdqul(nds, dst, Assembler::AVX_512bit);
4834     Assembler::vpsrlw(nds, nds, shift, vector_len);
4835     evmovdqul(dst, nds, Assembler::AVX_512bit);
4836   } else if (dst_enc < 16) {
4837     // use nds to save a copy of xmm0 and hold shift
4838     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4839     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4840     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4841     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4842   } else if (nds_enc < 16) {
4843     // use nds as dest as temps
4844     evmovdqul(nds, dst, Assembler::AVX_512bit);
4845     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4846     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4847     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4848     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4849     evmovdqul(dst, nds, Assembler::AVX_512bit);
4850   } else {
4851     // worse case scenario, all regs are in the upper bank
4852     subptr(rsp, 64);
4853     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4854     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4855     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4856     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4857     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4858     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4859     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4860     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4861     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4862     addptr(rsp, 64);
4863   }
4864 }
4865 
4866 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4867   int dst_enc = dst->encoding();
4868   int nds_enc = nds->encoding();
4869   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4870     Assembler::vpsrlw(dst, nds, shift, vector_len);
4871   } else if (dst_enc < 16) {
4872     Assembler::vpsrlw(dst, dst, shift, vector_len);
4873   } else if (nds_enc < 16) {
4874     // use nds as scratch
4875     evmovdqul(nds, dst, Assembler::AVX_512bit);
4876     Assembler::vpsrlw(nds, nds, shift, vector_len);
4877     evmovdqul(dst, nds, Assembler::AVX_512bit);
4878   } else {
4879     // use nds as scratch for xmm0
4880     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4881     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4882     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4883     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4884   }
4885 }
4886 
4887 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4888   int dst_enc = dst->encoding();
4889   int nds_enc = nds->encoding();
4890   int shift_enc = shift->encoding();
4891   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4892     Assembler::vpsllw(dst, nds, shift, vector_len);
4893   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4894     Assembler::vpsllw(dst, dst, shift, vector_len);
4895   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4896     // use nds_enc as scratch with shift
4897     evmovdqul(nds, shift, Assembler::AVX_512bit);
4898     Assembler::vpsllw(dst, dst, nds, vector_len);
4899   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4900     // use nds as scratch with dst
4901     evmovdqul(nds, dst, Assembler::AVX_512bit);
4902     Assembler::vpsllw(nds, nds, shift, vector_len);
4903     evmovdqul(dst, nds, Assembler::AVX_512bit);
4904   } else if (dst_enc < 16) {
4905     // use nds to save a copy of xmm0 and hold shift
4906     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4907     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4908     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4909     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4910   } else if (nds_enc < 16) {
4911     // use nds as dest as temps
4912     evmovdqul(nds, dst, Assembler::AVX_512bit);
4913     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4914     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4915     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4916     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4917     evmovdqul(dst, nds, Assembler::AVX_512bit);
4918   } else {
4919     // worse case scenario, all regs are in the upper bank
4920     subptr(rsp, 64);
4921     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4922     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4923     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4924     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4925     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4926     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4927     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4928     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4929     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4930     addptr(rsp, 64);
4931   }
4932 }
4933 
4934 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4935   int dst_enc = dst->encoding();
4936   int nds_enc = nds->encoding();
4937   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4938     Assembler::vpsllw(dst, nds, shift, vector_len);
4939   } else if (dst_enc < 16) {
4940     Assembler::vpsllw(dst, dst, shift, vector_len);
4941   } else if (nds_enc < 16) {
4942     // use nds as scratch
4943     evmovdqul(nds, dst, Assembler::AVX_512bit);
4944     Assembler::vpsllw(nds, nds, shift, vector_len);
4945     evmovdqul(dst, nds, Assembler::AVX_512bit);
4946   } else {
4947     // use nds as scratch for xmm0
4948     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4949     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4950     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4951     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4952   }
4953 }
4954 
4955 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4956   int dst_enc = dst->encoding();
4957   int src_enc = src->encoding();
4958   if ((dst_enc < 16) && (src_enc < 16)) {
4959     Assembler::vptest(dst, src);
4960   } else if (src_enc < 16) {
4961     subptr(rsp, 64);
4962     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4963     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4964     Assembler::vptest(xmm0, src);
4965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4966     addptr(rsp, 64);
4967   } else if (dst_enc < 16) {
4968     subptr(rsp, 64);
4969     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4970     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4971     Assembler::vptest(dst, xmm0);
4972     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4973     addptr(rsp, 64);
4974   } else {
4975     subptr(rsp, 64);
4976     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4977     subptr(rsp, 64);
4978     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4979     movdqu(xmm0, src);
4980     movdqu(xmm1, dst);
4981     Assembler::vptest(xmm1, xmm0);
4982     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4983     addptr(rsp, 64);
4984     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4985     addptr(rsp, 64);
4986   }
4987 }
4988 
4989 // This instruction exists within macros, ergo we cannot control its input
4990 // when emitted through those patterns.
4991 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4992   if (VM_Version::supports_avx512nobw()) {
4993     int dst_enc = dst->encoding();
4994     int src_enc = src->encoding();
4995     if (dst_enc == src_enc) {
4996       if (dst_enc < 16) {
4997         Assembler::punpcklbw(dst, src);
4998       } else {
4999         subptr(rsp, 64);
5000         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5001         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5002         Assembler::punpcklbw(xmm0, xmm0);
5003         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5004         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5005         addptr(rsp, 64);
5006       }
5007     } else {
5008       if ((src_enc < 16) && (dst_enc < 16)) {
5009         Assembler::punpcklbw(dst, src);
5010       } else if (src_enc < 16) {
5011         subptr(rsp, 64);
5012         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5013         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5014         Assembler::punpcklbw(xmm0, src);
5015         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5016         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5017         addptr(rsp, 64);
5018       } else if (dst_enc < 16) {
5019         subptr(rsp, 64);
5020         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5021         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5022         Assembler::punpcklbw(dst, xmm0);
5023         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5024         addptr(rsp, 64);
5025       } else {
5026         subptr(rsp, 64);
5027         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5028         subptr(rsp, 64);
5029         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5030         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5031         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5032         Assembler::punpcklbw(xmm0, xmm1);
5033         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
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   } else {
5041     Assembler::punpcklbw(dst, src);
5042   }
5043 }
5044 
5045 // This instruction exists within macros, ergo we cannot control its input
5046 // when emitted through those patterns.
5047 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5048   if (VM_Version::supports_avx512nobw()) {
5049     int dst_enc = dst->encoding();
5050     int src_enc = src->encoding();
5051     if (dst_enc == src_enc) {
5052       if (dst_enc < 16) {
5053         Assembler::pshuflw(dst, src, mode);
5054       } else {
5055         subptr(rsp, 64);
5056         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5057         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5058         Assembler::pshuflw(xmm0, xmm0, mode);
5059         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5060         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5061         addptr(rsp, 64);
5062       }
5063     } else {
5064       if ((src_enc < 16) && (dst_enc < 16)) {
5065         Assembler::pshuflw(dst, src, mode);
5066       } else if (src_enc < 16) {
5067         subptr(rsp, 64);
5068         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5069         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5070         Assembler::pshuflw(xmm0, src, mode);
5071         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5072         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5073         addptr(rsp, 64);
5074       } else if (dst_enc < 16) {
5075         subptr(rsp, 64);
5076         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5078         Assembler::pshuflw(dst, xmm0, mode);
5079         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5080         addptr(rsp, 64);
5081       } else {
5082         subptr(rsp, 64);
5083         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5084         subptr(rsp, 64);
5085         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5086         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5087         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5088         Assembler::pshuflw(xmm0, xmm1, mode);
5089         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5090         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5091         addptr(rsp, 64);
5092         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5093         addptr(rsp, 64);
5094       }
5095     }
5096   } else {
5097     Assembler::pshuflw(dst, src, mode);
5098   }
5099 }
5100 
5101 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5102   if (reachable(src)) {
5103     vandpd(dst, nds, as_Address(src), vector_len);
5104   } else {
5105     lea(rscratch1, src);
5106     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5107   }
5108 }
5109 
5110 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5111   if (reachable(src)) {
5112     vandps(dst, nds, as_Address(src), vector_len);
5113   } else {
5114     lea(rscratch1, src);
5115     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5116   }
5117 }
5118 
5119 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5120   if (reachable(src)) {
5121     vdivsd(dst, nds, as_Address(src));
5122   } else {
5123     lea(rscratch1, src);
5124     vdivsd(dst, nds, Address(rscratch1, 0));
5125   }
5126 }
5127 
5128 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5129   if (reachable(src)) {
5130     vdivss(dst, nds, as_Address(src));
5131   } else {
5132     lea(rscratch1, src);
5133     vdivss(dst, nds, Address(rscratch1, 0));
5134   }
5135 }
5136 
5137 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5138   if (reachable(src)) {
5139     vmulsd(dst, nds, as_Address(src));
5140   } else {
5141     lea(rscratch1, src);
5142     vmulsd(dst, nds, Address(rscratch1, 0));
5143   }
5144 }
5145 
5146 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5147   if (reachable(src)) {
5148     vmulss(dst, nds, as_Address(src));
5149   } else {
5150     lea(rscratch1, src);
5151     vmulss(dst, nds, Address(rscratch1, 0));
5152   }
5153 }
5154 
5155 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5156   if (reachable(src)) {
5157     vsubsd(dst, nds, as_Address(src));
5158   } else {
5159     lea(rscratch1, src);
5160     vsubsd(dst, nds, Address(rscratch1, 0));
5161   }
5162 }
5163 
5164 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5165   if (reachable(src)) {
5166     vsubss(dst, nds, as_Address(src));
5167   } else {
5168     lea(rscratch1, src);
5169     vsubss(dst, nds, Address(rscratch1, 0));
5170   }
5171 }
5172 
5173 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5174   int nds_enc = nds->encoding();
5175   int dst_enc = dst->encoding();
5176   bool dst_upper_bank = (dst_enc > 15);
5177   bool nds_upper_bank = (nds_enc > 15);
5178   if (VM_Version::supports_avx512novl() &&
5179       (nds_upper_bank || dst_upper_bank)) {
5180     if (dst_upper_bank) {
5181       subptr(rsp, 64);
5182       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5183       movflt(xmm0, nds);
5184       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5185       movflt(dst, xmm0);
5186       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5187       addptr(rsp, 64);
5188     } else {
5189       movflt(dst, nds);
5190       vxorps(dst, dst, src, Assembler::AVX_128bit);
5191     }
5192   } else {
5193     vxorps(dst, nds, src, Assembler::AVX_128bit);
5194   }
5195 }
5196 
5197 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5198   int nds_enc = nds->encoding();
5199   int dst_enc = dst->encoding();
5200   bool dst_upper_bank = (dst_enc > 15);
5201   bool nds_upper_bank = (nds_enc > 15);
5202   if (VM_Version::supports_avx512novl() &&
5203       (nds_upper_bank || dst_upper_bank)) {
5204     if (dst_upper_bank) {
5205       subptr(rsp, 64);
5206       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5207       movdbl(xmm0, nds);
5208       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5209       movdbl(dst, xmm0);
5210       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5211       addptr(rsp, 64);
5212     } else {
5213       movdbl(dst, nds);
5214       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5215     }
5216   } else {
5217     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5218   }
5219 }
5220 
5221 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5222   if (reachable(src)) {
5223     vxorpd(dst, nds, as_Address(src), vector_len);
5224   } else {
5225     lea(rscratch1, src);
5226     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5227   }
5228 }
5229 
5230 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5231   if (reachable(src)) {
5232     vxorps(dst, nds, as_Address(src), vector_len);
5233   } else {
5234     lea(rscratch1, src);
5235     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5236   }
5237 }
5238 
5239 
5240 void MacroAssembler::resolve_jobject(Register value,
5241                                      Register thread,
5242                                      Register tmp) {
5243   assert_different_registers(value, thread, tmp);
5244   Label done, not_weak;
5245   testptr(value, value);
5246   jcc(Assembler::zero, done);                // Use NULL as-is.
5247   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5248   jcc(Assembler::zero, not_weak);
5249   // Resolve jweak.
5250   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5251   verify_oop(value);
5252 #if INCLUDE_ALL_GCS
5253   if (UseG1GC || UseShenandoahGC) {
5254     g1_write_barrier_pre(noreg /* obj */,
5255                          value /* pre_val */,
5256                          thread /* thread */,
5257                          tmp /* tmp */,
5258                          true /* tosca_live */,
5259                          true /* expand_call */);
5260   }
5261 #endif // INCLUDE_ALL_GCS
5262   jmp(done);
5263   bind(not_weak);
5264   // Resolve (untagged) jobject.
5265   movptr(value, Address(value, 0));
5266   verify_oop(value);
5267   bind(done);
5268 }
5269 
5270 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5271   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5272   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5273   // The inverted mask is sign-extended
5274   andptr(possibly_jweak, inverted_jweak_mask);
5275 }
5276 
5277 //////////////////////////////////////////////////////////////////////////////////
5278 #if INCLUDE_ALL_GCS
5279 
5280 void MacroAssembler::g1_write_barrier_pre(Register obj,
5281                                           Register pre_val,
5282                                           Register thread,
5283                                           Register tmp,
5284                                           bool tosca_live,
5285                                           bool expand_call) {
5286 
5287   // If expand_call is true then we expand the call_VM_leaf macro
5288   // directly to skip generating the check by
5289   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5290 
5291 #ifdef _LP64
5292   assert(thread == r15_thread, "must be");
5293 #endif // _LP64
5294 
5295   Label done;
5296   Label runtime;
5297 
5298   assert(pre_val != noreg, "check this code");
5299 
5300   if (obj != noreg) {
5301     assert_different_registers(obj, pre_val, tmp);
5302     assert(pre_val != rax, "check this code");
5303   }
5304 
5305   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5306                                        SATBMarkQueue::byte_offset_of_active()));
5307   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5308                                        SATBMarkQueue::byte_offset_of_index()));
5309   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5310                                        SATBMarkQueue::byte_offset_of_buf()));
5311 
5312 
5313   // Is marking active?
5314   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5315     cmpl(in_progress, 0);
5316   } else {
5317     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5318     cmpb(in_progress, 0);
5319   }
5320   jcc(Assembler::equal, done);
5321 
5322   // Do we need to load the previous value?
5323   if (obj != noreg) {
5324     load_heap_oop(pre_val, Address(obj, 0));
5325   }
5326 
5327   // Is the previous value null?
5328   cmpptr(pre_val, (int32_t) NULL_WORD);
5329   jcc(Assembler::equal, done);
5330 
5331   // Can we store original value in the thread's buffer?
5332   // Is index == 0?
5333   // (The index field is typed as size_t.)
5334 
5335   movptr(tmp, index);                   // tmp := *index_adr
5336   cmpptr(tmp, 0);                       // tmp == 0?
5337   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5338 
5339   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5340   movptr(index, tmp);                   // *index_adr := tmp
5341   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5342 
5343   // Record the previous value
5344   movptr(Address(tmp, 0), pre_val);
5345   jmp(done);
5346 
5347   bind(runtime);
5348   // save the live input values
5349   if(tosca_live) push(rax);
5350 
5351   if (obj != noreg && obj != rax)
5352     push(obj);
5353 
5354   if (pre_val != rax)
5355     push(pre_val);
5356 
5357   // Calling the runtime using the regular call_VM_leaf mechanism generates
5358   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5359   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5360   //
5361   // If we care generating the pre-barrier without a frame (e.g. in the
5362   // intrinsified Reference.get() routine) then ebp might be pointing to
5363   // the caller frame and so this check will most likely fail at runtime.
5364   //
5365   // Expanding the call directly bypasses the generation of the check.
5366   // So when we do not have have a full interpreter frame on the stack
5367   // expand_call should be passed true.
5368 
5369   NOT_LP64( push(thread); )
5370 
5371   if (expand_call) {
5372     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5373     pass_arg1(this, thread);
5374     pass_arg0(this, pre_val);
5375     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5376   } else {
5377     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5378   }
5379 
5380   NOT_LP64( pop(thread); )
5381 
5382   // save the live input values
5383   if (pre_val != rax)
5384     pop(pre_val);
5385 
5386   if (obj != noreg && obj != rax)
5387     pop(obj);
5388 
5389   if(tosca_live) pop(rax);
5390 
5391   bind(done);
5392 }
5393 
5394 void MacroAssembler::shenandoah_write_barrier_post(Register store_addr,
5395                                                    Register new_val,
5396                                                    Register thread,
5397                                                    Register tmp,
5398                                                    Register tmp2) {
5399   assert(UseShenandoahGC, "why else should we be here?");
5400 
5401   if (! UseShenandoahMatrix) {
5402     // No need for that barrier if not using matrix.
5403     return;
5404   }
5405 
5406   Label done;
5407   testptr(new_val, new_val);
5408   jcc(Assembler::zero, done);
5409   ShenandoahConnectionMatrix* matrix = ShenandoahHeap::heap()->connection_matrix();
5410   address matrix_addr = matrix->matrix_addr();
5411   movptr(rscratch1, (intptr_t) ShenandoahHeap::heap()->first_region_bottom());
5412   // Compute to-region index
5413   movptr(tmp, new_val);
5414   subptr(tmp, rscratch1);
5415   shrptr(tmp, ShenandoahHeapRegion::region_size_shift_jint());
5416   // Compute from-region index
5417   movptr(tmp2, store_addr);
5418   subptr(tmp2, rscratch1);
5419   shrptr(tmp2, ShenandoahHeapRegion::region_size_shift_jint());
5420   // Compute matrix index
5421   imulptr(tmp, tmp, matrix->stride_jint());
5422   addptr(tmp, tmp2);
5423   // Address is _matrix[from * stride + to]
5424   movptr(rscratch1, (intptr_t) matrix_addr);
5425   // Test if the element is already set.
5426   testb(Address(rscratch1, tmp, Address::times_1), 0);
5427   jcc(Assembler::notZero, done);
5428   // Store true, if not yet set.
5429   movb(Address(rscratch1, tmp, Address::times_1), 1);
5430   bind(done);
5431 }
5432 
5433 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5434                                            Register new_val,
5435                                            Register thread,
5436                                            Register tmp,
5437                                            Register tmp2) {
5438 #ifdef _LP64
5439   assert(thread == r15_thread, "must be");
5440 #endif // _LP64
5441 
5442   assert(UseG1GC, "expect G1 GC");
5443 
5444   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5445                                        DirtyCardQueue::byte_offset_of_index()));
5446   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5447                                        DirtyCardQueue::byte_offset_of_buf()));
5448 
5449   CardTableModRefBS* ct =
5450     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5451   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5452 
5453   Label done;
5454   Label runtime;
5455 
5456   // Does store cross heap regions?
5457 
5458   movptr(tmp, store_addr);
5459   xorptr(tmp, new_val);
5460   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5461   jcc(Assembler::equal, done);
5462 
5463   // crosses regions, storing NULL?
5464 
5465   cmpptr(new_val, (int32_t) NULL_WORD);
5466   jcc(Assembler::equal, done);
5467 
5468   // storing region crossing non-NULL, is card already dirty?
5469 
5470   const Register card_addr = tmp;
5471   const Register cardtable = tmp2;
5472 
5473   movptr(card_addr, store_addr);
5474   shrptr(card_addr, CardTableModRefBS::card_shift);
5475   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5476   // a valid address and therefore is not properly handled by the relocation code.
5477   movptr(cardtable, (intptr_t)ct->byte_map_base);
5478   addptr(card_addr, cardtable);
5479 
5480   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5481   jcc(Assembler::equal, done);
5482 
5483   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5484   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5485   jcc(Assembler::equal, done);
5486 
5487 
5488   // storing a region crossing, non-NULL oop, card is clean.
5489   // dirty card and log.
5490 
5491   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5492 
5493   cmpl(queue_index, 0);
5494   jcc(Assembler::equal, runtime);
5495   subl(queue_index, wordSize);
5496   movptr(tmp2, buffer);
5497 #ifdef _LP64
5498   movslq(rscratch1, queue_index);
5499   addq(tmp2, rscratch1);
5500   movq(Address(tmp2, 0), card_addr);
5501 #else
5502   addl(tmp2, queue_index);
5503   movl(Address(tmp2, 0), card_addr);
5504 #endif
5505   jmp(done);
5506 
5507   bind(runtime);
5508   // save the live input values
5509   push(store_addr);
5510   push(new_val);
5511 #ifdef _LP64
5512   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5513 #else
5514   push(thread);
5515   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5516   pop(thread);
5517 #endif
5518   pop(new_val);
5519   pop(store_addr);
5520 
5521   bind(done);
5522 }
5523 
5524 #ifndef _LP64
5525 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5526   Unimplemented();
5527 }
5528 #else
5529 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5530   assert(UseShenandoahGC, "must only be called with Shenandoah GC active");
5531   assert(ShenandoahWriteBarrier, "must only be called when write barriers are enabled");
5532 
5533   Label done;
5534 
5535   // Check for evacuation-in-progress
5536   Address evacuation_in_progress = Address(r15_thread, in_bytes(JavaThread::evacuation_in_progress_offset()));
5537   cmpb(evacuation_in_progress, 0);
5538 
5539   // The read-barrier.
5540   movptr(dst, Address(dst, BrooksPointer::byte_offset()));
5541 
5542   jccb(Assembler::equal, done);
5543 
5544   if (dst != rax) {
5545     xchgptr(dst, rax); // Move obj into rax and save rax into obj.
5546   }
5547 
5548   assert(StubRoutines::x86::shenandoah_wb() != NULL, "need write barrier stub");
5549   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::shenandoah_wb())));
5550 
5551   if (dst != rax) {
5552     xchgptr(rax, dst); // Swap back obj with rax.
5553   }
5554 
5555   bind(done);
5556 }
5557 #endif // _LP64
5558 
5559 #endif // INCLUDE_ALL_GCS
5560 //////////////////////////////////////////////////////////////////////////////////
5561 
5562 
5563 void MacroAssembler::store_check(Register obj, Address dst) {
5564   store_check(obj);
5565 }
5566 
5567 void MacroAssembler::store_check(Register obj) {
5568   // Does a store check for the oop in register obj. The content of
5569   // register obj is destroyed afterwards.
5570   BarrierSet* bs = Universe::heap()->barrier_set();
5571   assert(bs->kind() == BarrierSet::CardTableForRS ||
5572          bs->kind() == BarrierSet::CardTableExtension,
5573          "Wrong barrier set kind");
5574 
5575   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5576   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5577 
5578   shrptr(obj, CardTableModRefBS::card_shift);
5579 
5580   Address card_addr;
5581 
5582   // The calculation for byte_map_base is as follows:
5583   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5584   // So this essentially converts an address to a displacement and it will
5585   // never need to be relocated. On 64bit however the value may be too
5586   // large for a 32bit displacement.
5587   intptr_t disp = (intptr_t) ct->byte_map_base;
5588   if (is_simm32(disp)) {
5589     card_addr = Address(noreg, obj, Address::times_1, disp);
5590   } else {
5591     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5592     // displacement and done in a single instruction given favorable mapping and a
5593     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5594     // entry and that entry is not properly handled by the relocation code.
5595     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5596     Address index(noreg, obj, Address::times_1);
5597     card_addr = as_Address(ArrayAddress(cardtable, index));
5598   }
5599 
5600   int dirty = CardTableModRefBS::dirty_card_val();
5601   if (UseCondCardMark) {
5602     Label L_already_dirty;
5603     if (UseConcMarkSweepGC) {
5604       membar(Assembler::StoreLoad);
5605     }
5606     cmpb(card_addr, dirty);
5607     jcc(Assembler::equal, L_already_dirty);
5608     movb(card_addr, dirty);
5609     bind(L_already_dirty);
5610   } else {
5611     movb(card_addr, dirty);
5612   }
5613 }
5614 
5615 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5616   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5617 }
5618 
5619 // Force generation of a 4 byte immediate value even if it fits into 8bit
5620 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5621   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5622 }
5623 
5624 void MacroAssembler::subptr(Register dst, Register src) {
5625   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5626 }
5627 
5628 // C++ bool manipulation
5629 void MacroAssembler::testbool(Register dst) {
5630   if(sizeof(bool) == 1)
5631     testb(dst, 0xff);
5632   else if(sizeof(bool) == 2) {
5633     // testw implementation needed for two byte bools
5634     ShouldNotReachHere();
5635   } else if(sizeof(bool) == 4)
5636     testl(dst, dst);
5637   else
5638     // unsupported
5639     ShouldNotReachHere();
5640 }
5641 
5642 void MacroAssembler::testptr(Register dst, Register src) {
5643   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5644 }
5645 
5646 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5647 void MacroAssembler::tlab_allocate(Register obj,
5648                                    Register var_size_in_bytes,
5649                                    int con_size_in_bytes,
5650                                    Register t1,
5651                                    Register t2,
5652                                    Label& slow_case) {
5653   assert_different_registers(obj, t1, t2);
5654   assert_different_registers(obj, var_size_in_bytes, t1);
5655   Register end = t2;
5656   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5657 
5658   verify_tlab();
5659 
5660   NOT_LP64(get_thread(thread));
5661 
5662   uint oop_extra_words = Universe::heap()->oop_extra_words();
5663 
5664   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5665   if (var_size_in_bytes == noreg) {
5666     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5667   } else {
5668     if (oop_extra_words > 0) {
5669       addptr(var_size_in_bytes, oop_extra_words * HeapWordSize);
5670     }
5671     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5672   }
5673   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5674   jcc(Assembler::above, slow_case);
5675 
5676   // update the tlab top pointer
5677   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5678 
5679   Universe::heap()->compile_prepare_oop(this, obj);
5680 
5681   // recover var_size_in_bytes if necessary
5682   if (var_size_in_bytes == end) {
5683     subptr(var_size_in_bytes, obj);
5684   }
5685   verify_tlab();
5686 }
5687 
5688 // Preserves rbx, and rdx.
5689 Register MacroAssembler::tlab_refill(Label& retry,
5690                                      Label& try_eden,
5691                                      Label& slow_case) {
5692   Register top = rax;
5693   Register t1  = rcx; // object size
5694   Register t2  = rsi;
5695   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5696   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5697   Label do_refill, discard_tlab;
5698 
5699   if (!Universe::heap()->supports_inline_contig_alloc()) {
5700     // No allocation in the shared eden.
5701     jmp(slow_case);
5702   }
5703 
5704   NOT_LP64(get_thread(thread_reg));
5705 
5706   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5707   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5708 
5709   // calculate amount of free space
5710   subptr(t1, top);
5711   shrptr(t1, LogHeapWordSize);
5712 
5713   // Retain tlab and allocate object in shared space if
5714   // the amount free in the tlab is too large to discard.
5715   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5716   jcc(Assembler::lessEqual, discard_tlab);
5717 
5718   // Retain
5719   // %%% yuck as movptr...
5720   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5721   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5722   if (TLABStats) {
5723     // increment number of slow_allocations
5724     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5725   }
5726   jmp(try_eden);
5727 
5728   bind(discard_tlab);
5729   if (TLABStats) {
5730     // increment number of refills
5731     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5732     // accumulate wastage -- t1 is amount free in tlab
5733     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5734   }
5735 
5736   // if tlab is currently allocated (top or end != null) then
5737   // fill [top, end + alignment_reserve) with array object
5738   testptr(top, top);
5739   jcc(Assembler::zero, do_refill);
5740 
5741   // set up the mark word
5742   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5743   // set the length to the remaining space
5744   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5745   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5746   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5747   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5748   // set klass to intArrayKlass
5749   // dubious reloc why not an oop reloc?
5750   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5751   // store klass last.  concurrent gcs assumes klass length is valid if
5752   // klass field is not null.
5753   store_klass(top, t1);
5754 
5755   movptr(t1, top);
5756   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5757   incr_allocated_bytes(thread_reg, t1, 0);
5758 
5759   // refill the tlab with an eden allocation
5760   bind(do_refill);
5761   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5762   shlptr(t1, LogHeapWordSize);
5763   // allocate new tlab, address returned in top
5764   eden_allocate(top, t1, 0, t2, slow_case);
5765 
5766   // Check that t1 was preserved in eden_allocate.
5767 #ifdef ASSERT
5768   if (UseTLAB) {
5769     Label ok;
5770     Register tsize = rsi;
5771     assert_different_registers(tsize, thread_reg, t1);
5772     push(tsize);
5773     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5774     shlptr(tsize, LogHeapWordSize);
5775     cmpptr(t1, tsize);
5776     jcc(Assembler::equal, ok);
5777     STOP("assert(t1 != tlab size)");
5778     should_not_reach_here();
5779 
5780     bind(ok);
5781     pop(tsize);
5782   }
5783 #endif
5784   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5785   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5786   addptr(top, t1);
5787   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5788   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5789 
5790   if (ZeroTLAB) {
5791     // This is a fast TLAB refill, therefore the GC is not notified of it.
5792     // So compiled code must fill the new TLAB with zeroes.
5793     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5794     zero_memory(top, t1, 0, t2);
5795   }
5796 
5797   verify_tlab();
5798   jmp(retry);
5799 
5800   return thread_reg; // for use by caller
5801 }
5802 
5803 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5804 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5805   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5806   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5807   Label done;
5808 
5809   testptr(length_in_bytes, length_in_bytes);
5810   jcc(Assembler::zero, done);
5811 
5812   // initialize topmost word, divide index by 2, check if odd and test if zero
5813   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5814 #ifdef ASSERT
5815   {
5816     Label L;
5817     testptr(length_in_bytes, BytesPerWord - 1);
5818     jcc(Assembler::zero, L);
5819     stop("length must be a multiple of BytesPerWord");
5820     bind(L);
5821   }
5822 #endif
5823   Register index = length_in_bytes;
5824   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5825   if (UseIncDec) {
5826     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5827   } else {
5828     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5829     shrptr(index, 1);
5830   }
5831 #ifndef _LP64
5832   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5833   {
5834     Label even;
5835     // note: if index was a multiple of 8, then it cannot
5836     //       be 0 now otherwise it must have been 0 before
5837     //       => if it is even, we don't need to check for 0 again
5838     jcc(Assembler::carryClear, even);
5839     // clear topmost word (no jump would be needed if conditional assignment worked here)
5840     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5841     // index could be 0 now, must check again
5842     jcc(Assembler::zero, done);
5843     bind(even);
5844   }
5845 #endif // !_LP64
5846   // initialize remaining object fields: index is a multiple of 2 now
5847   {
5848     Label loop;
5849     bind(loop);
5850     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5851     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5852     decrement(index);
5853     jcc(Assembler::notZero, loop);
5854   }
5855 
5856   bind(done);
5857 }
5858 
5859 void MacroAssembler::incr_allocated_bytes(Register thread,
5860                                           Register var_size_in_bytes,
5861                                           int con_size_in_bytes,
5862                                           Register t1) {
5863   if (!thread->is_valid()) {
5864 #ifdef _LP64
5865     thread = r15_thread;
5866 #else
5867     assert(t1->is_valid(), "need temp reg");
5868     thread = t1;
5869     get_thread(thread);
5870 #endif
5871   }
5872 
5873 #ifdef _LP64
5874   if (var_size_in_bytes->is_valid()) {
5875     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5876   } else {
5877     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5878   }
5879 #else
5880   if (var_size_in_bytes->is_valid()) {
5881     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5882   } else {
5883     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5884   }
5885   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5886 #endif
5887 }
5888 
5889 // Look up the method for a megamorphic invokeinterface call.
5890 // The target method is determined by <intf_klass, itable_index>.
5891 // The receiver klass is in recv_klass.
5892 // On success, the result will be in method_result, and execution falls through.
5893 // On failure, execution transfers to the given label.
5894 void MacroAssembler::lookup_interface_method(Register recv_klass,
5895                                              Register intf_klass,
5896                                              RegisterOrConstant itable_index,
5897                                              Register method_result,
5898                                              Register scan_temp,
5899                                              Label& L_no_such_interface) {
5900   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5901   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5902          "caller must use same register for non-constant itable index as for method");
5903 
5904   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5905   int vtable_base = in_bytes(Klass::vtable_start_offset());
5906   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5907   int scan_step   = itableOffsetEntry::size() * wordSize;
5908   int vte_size    = vtableEntry::size_in_bytes();
5909   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5910   assert(vte_size == wordSize, "else adjust times_vte_scale");
5911 
5912   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5913 
5914   // %%% Could store the aligned, prescaled offset in the klassoop.
5915   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5916 
5917   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5918   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5919   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5920 
5921   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5922   //   if (scan->interface() == intf) {
5923   //     result = (klass + scan->offset() + itable_index);
5924   //   }
5925   // }
5926   Label search, found_method;
5927 
5928   for (int peel = 1; peel >= 0; peel--) {
5929     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5930     cmpptr(intf_klass, method_result);
5931 
5932     if (peel) {
5933       jccb(Assembler::equal, found_method);
5934     } else {
5935       jccb(Assembler::notEqual, search);
5936       // (invert the test to fall through to found_method...)
5937     }
5938 
5939     if (!peel)  break;
5940 
5941     bind(search);
5942 
5943     // Check that the previous entry is non-null.  A null entry means that
5944     // the receiver class doesn't implement the interface, and wasn't the
5945     // same as when the caller was compiled.
5946     testptr(method_result, method_result);
5947     jcc(Assembler::zero, L_no_such_interface);
5948     addptr(scan_temp, scan_step);
5949   }
5950 
5951   bind(found_method);
5952 
5953   // Got a hit.
5954   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5955   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5956 }
5957 
5958 
5959 // virtual method calling
5960 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5961                                            RegisterOrConstant vtable_index,
5962                                            Register method_result) {
5963   const int base = in_bytes(Klass::vtable_start_offset());
5964   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5965   Address vtable_entry_addr(recv_klass,
5966                             vtable_index, Address::times_ptr,
5967                             base + vtableEntry::method_offset_in_bytes());
5968   movptr(method_result, vtable_entry_addr);
5969 }
5970 
5971 
5972 void MacroAssembler::check_klass_subtype(Register sub_klass,
5973                            Register super_klass,
5974                            Register temp_reg,
5975                            Label& L_success) {
5976   Label L_failure;
5977   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5978   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5979   bind(L_failure);
5980 }
5981 
5982 
5983 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5984                                                    Register super_klass,
5985                                                    Register temp_reg,
5986                                                    Label* L_success,
5987                                                    Label* L_failure,
5988                                                    Label* L_slow_path,
5989                                         RegisterOrConstant super_check_offset) {
5990   assert_different_registers(sub_klass, super_klass, temp_reg);
5991   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5992   if (super_check_offset.is_register()) {
5993     assert_different_registers(sub_klass, super_klass,
5994                                super_check_offset.as_register());
5995   } else if (must_load_sco) {
5996     assert(temp_reg != noreg, "supply either a temp or a register offset");
5997   }
5998 
5999   Label L_fallthrough;
6000   int label_nulls = 0;
6001   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6002   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6003   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6004   assert(label_nulls <= 1, "at most one NULL in the batch");
6005 
6006   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6007   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6008   Address super_check_offset_addr(super_klass, sco_offset);
6009 
6010   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6011   // range of a jccb.  If this routine grows larger, reconsider at
6012   // least some of these.
6013 #define local_jcc(assembler_cond, label)                                \
6014   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6015   else                             jcc( assembler_cond, label) /*omit semi*/
6016 
6017   // Hacked jmp, which may only be used just before L_fallthrough.
6018 #define final_jmp(label)                                                \
6019   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6020   else                            jmp(label)                /*omit semi*/
6021 
6022   // If the pointers are equal, we are done (e.g., String[] elements).
6023   // This self-check enables sharing of secondary supertype arrays among
6024   // non-primary types such as array-of-interface.  Otherwise, each such
6025   // type would need its own customized SSA.
6026   // We move this check to the front of the fast path because many
6027   // type checks are in fact trivially successful in this manner,
6028   // so we get a nicely predicted branch right at the start of the check.
6029   cmpptr(sub_klass, super_klass);
6030   local_jcc(Assembler::equal, *L_success);
6031 
6032   // Check the supertype display:
6033   if (must_load_sco) {
6034     // Positive movl does right thing on LP64.
6035     movl(temp_reg, super_check_offset_addr);
6036     super_check_offset = RegisterOrConstant(temp_reg);
6037   }
6038   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6039   cmpptr(super_klass, super_check_addr); // load displayed supertype
6040 
6041   // This check has worked decisively for primary supers.
6042   // Secondary supers are sought in the super_cache ('super_cache_addr').
6043   // (Secondary supers are interfaces and very deeply nested subtypes.)
6044   // This works in the same check above because of a tricky aliasing
6045   // between the super_cache and the primary super display elements.
6046   // (The 'super_check_addr' can address either, as the case requires.)
6047   // Note that the cache is updated below if it does not help us find
6048   // what we need immediately.
6049   // So if it was a primary super, we can just fail immediately.
6050   // Otherwise, it's the slow path for us (no success at this point).
6051 
6052   if (super_check_offset.is_register()) {
6053     local_jcc(Assembler::equal, *L_success);
6054     cmpl(super_check_offset.as_register(), sc_offset);
6055     if (L_failure == &L_fallthrough) {
6056       local_jcc(Assembler::equal, *L_slow_path);
6057     } else {
6058       local_jcc(Assembler::notEqual, *L_failure);
6059       final_jmp(*L_slow_path);
6060     }
6061   } else if (super_check_offset.as_constant() == sc_offset) {
6062     // Need a slow path; fast failure is impossible.
6063     if (L_slow_path == &L_fallthrough) {
6064       local_jcc(Assembler::equal, *L_success);
6065     } else {
6066       local_jcc(Assembler::notEqual, *L_slow_path);
6067       final_jmp(*L_success);
6068     }
6069   } else {
6070     // No slow path; it's a fast decision.
6071     if (L_failure == &L_fallthrough) {
6072       local_jcc(Assembler::equal, *L_success);
6073     } else {
6074       local_jcc(Assembler::notEqual, *L_failure);
6075       final_jmp(*L_success);
6076     }
6077   }
6078 
6079   bind(L_fallthrough);
6080 
6081 #undef local_jcc
6082 #undef final_jmp
6083 }
6084 
6085 
6086 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6087                                                    Register super_klass,
6088                                                    Register temp_reg,
6089                                                    Register temp2_reg,
6090                                                    Label* L_success,
6091                                                    Label* L_failure,
6092                                                    bool set_cond_codes) {
6093   assert_different_registers(sub_klass, super_klass, temp_reg);
6094   if (temp2_reg != noreg)
6095     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6096 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6097 
6098   Label L_fallthrough;
6099   int label_nulls = 0;
6100   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6101   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6102   assert(label_nulls <= 1, "at most one NULL in the batch");
6103 
6104   // a couple of useful fields in sub_klass:
6105   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6106   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6107   Address secondary_supers_addr(sub_klass, ss_offset);
6108   Address super_cache_addr(     sub_klass, sc_offset);
6109 
6110   // Do a linear scan of the secondary super-klass chain.
6111   // This code is rarely used, so simplicity is a virtue here.
6112   // The repne_scan instruction uses fixed registers, which we must spill.
6113   // Don't worry too much about pre-existing connections with the input regs.
6114 
6115   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6116   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6117 
6118   // Get super_klass value into rax (even if it was in rdi or rcx).
6119   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6120   if (super_klass != rax || UseCompressedOops) {
6121     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6122     mov(rax, super_klass);
6123   }
6124   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6125   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6126 
6127 #ifndef PRODUCT
6128   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6129   ExternalAddress pst_counter_addr((address) pst_counter);
6130   NOT_LP64(  incrementl(pst_counter_addr) );
6131   LP64_ONLY( lea(rcx, pst_counter_addr) );
6132   LP64_ONLY( incrementl(Address(rcx, 0)) );
6133 #endif //PRODUCT
6134 
6135   // We will consult the secondary-super array.
6136   movptr(rdi, secondary_supers_addr);
6137   // Load the array length.  (Positive movl does right thing on LP64.)
6138   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6139   // Skip to start of data.
6140   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6141 
6142   // Scan RCX words at [RDI] for an occurrence of RAX.
6143   // Set NZ/Z based on last compare.
6144   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6145   // not change flags (only scas instruction which is repeated sets flags).
6146   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6147 
6148     testptr(rax,rax); // Set Z = 0
6149     repne_scan();
6150 
6151   // Unspill the temp. registers:
6152   if (pushed_rdi)  pop(rdi);
6153   if (pushed_rcx)  pop(rcx);
6154   if (pushed_rax)  pop(rax);
6155 
6156   if (set_cond_codes) {
6157     // Special hack for the AD files:  rdi is guaranteed non-zero.
6158     assert(!pushed_rdi, "rdi must be left non-NULL");
6159     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6160   }
6161 
6162   if (L_failure == &L_fallthrough)
6163         jccb(Assembler::notEqual, *L_failure);
6164   else  jcc(Assembler::notEqual, *L_failure);
6165 
6166   // Success.  Cache the super we found and proceed in triumph.
6167   movptr(super_cache_addr, super_klass);
6168 
6169   if (L_success != &L_fallthrough) {
6170     jmp(*L_success);
6171   }
6172 
6173 #undef IS_A_TEMP
6174 
6175   bind(L_fallthrough);
6176 }
6177 
6178 
6179 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6180   if (VM_Version::supports_cmov()) {
6181     cmovl(cc, dst, src);
6182   } else {
6183     Label L;
6184     jccb(negate_condition(cc), L);
6185     movl(dst, src);
6186     bind(L);
6187   }
6188 }
6189 
6190 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6191   if (VM_Version::supports_cmov()) {
6192     cmovl(cc, dst, src);
6193   } else {
6194     Label L;
6195     jccb(negate_condition(cc), L);
6196     movl(dst, src);
6197     bind(L);
6198   }
6199 }
6200 
6201 void MacroAssembler::verify_oop(Register reg, const char* s) {
6202   if (!VerifyOops) return;
6203 
6204   // Pass register number to verify_oop_subroutine
6205   const char* b = NULL;
6206   {
6207     ResourceMark rm;
6208     stringStream ss;
6209     ss.print("verify_oop: %s: %s", reg->name(), s);
6210     b = code_string(ss.as_string());
6211   }
6212   BLOCK_COMMENT("verify_oop {");
6213 #ifdef _LP64
6214   push(rscratch1);                    // save r10, trashed by movptr()
6215 #endif
6216   push(rax);                          // save rax,
6217   push(reg);                          // pass register argument
6218   ExternalAddress buffer((address) b);
6219   // avoid using pushptr, as it modifies scratch registers
6220   // and our contract is not to modify anything
6221   movptr(rax, buffer.addr());
6222   push(rax);
6223   // call indirectly to solve generation ordering problem
6224   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6225   call(rax);
6226   // Caller pops the arguments (oop, message) and restores rax, r10
6227   BLOCK_COMMENT("} verify_oop");
6228 }
6229 
6230 void MacroAssembler::in_heap_check(Register raddr, Register tmp, Label& done) {
6231   ShenandoahHeap *h = (ShenandoahHeap *)Universe::heap();
6232 
6233   HeapWord* first_region_bottom = h->first_region_bottom();
6234   HeapWord* last_region_end = first_region_bottom + (ShenandoahHeapRegion::region_size_bytes() / HeapWordSize) * h->max_regions();
6235   guarantee(first_region_bottom < last_region_end, "sanity: %p < %p", first_region_bottom, last_region_end);
6236   movptr(tmp, (intptr_t) first_region_bottom);
6237   cmpptr(raddr, tmp);
6238   jcc(Assembler::below, done);
6239   movptr(tmp, (intptr_t) last_region_end);
6240   cmpptr(raddr, tmp);
6241   jcc(Assembler::aboveEqual, done);
6242 
6243 }
6244 
6245 void MacroAssembler::shenandoah_cset_check(Register raddr, Register tmp1, Register tmp2, Label& done) {
6246   // Test that oop is not in to-space.
6247   movptr(tmp1, raddr);
6248   shrptr(tmp1, ShenandoahHeapRegion::region_size_shift_jint());
6249   movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
6250   movbool(tmp2, Address(tmp2, tmp1, Address::times_1));
6251   testbool(tmp2);
6252   jcc(Assembler::zero, done);
6253 
6254   // Check for cancelled GC.
6255   movptr(tmp2, (intptr_t) ShenandoahHeap::cancelled_concgc_addr());
6256   movbool(tmp2, Address(tmp2, 0));
6257   testbool(tmp2);
6258   jcc(Assembler::notZero, done);
6259 
6260 }
6261 
6262 #ifndef _LP64
6263 void MacroAssembler::_shenandoah_store_addr_check(Address addr, const char* msg, const char* file, int line) {
6264   // Not implemented on 32-bit, pass.
6265 }
6266 void MacroAssembler::_shenandoah_store_addr_check(Register dst, const char* msg, const char* file, int line) {
6267   // Not implemented on 32-bit, pass.
6268 }
6269 void MacroAssembler::_shenandoah_store_check(Register dst, Register value, const char* msg, const char* file, int line) {
6270   // Not implemented on 32-bit, pass.
6271 }
6272 void MacroAssembler::_shenandoah_store_check(Address addr, Register value, const char* msg, const char* file, int line) {
6273   // Not implemented on 32-bit, pass.
6274 }
6275 void MacroAssembler::_shenandoah_lock_check(Register dst, const char* msg, const char* file, int line) {
6276   // Not implemented on 32-bit, pass.
6277 }
6278 #else
6279 void MacroAssembler::_shenandoah_store_addr_check(Address addr, const char* msg, const char* file, int line) {
6280   _shenandoah_store_addr_check(addr.base(), msg, file, line);
6281 }
6282 
6283 void MacroAssembler::_shenandoah_store_addr_check(Register dst, const char* msg, const char* file, int line) {
6284   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6285   if (dst == rsp) return; // Stack-based target
6286 
6287   Register raddr = r9;
6288   Register tmp1 = r10;
6289   Register tmp2 = r11;
6290 
6291   Label done;
6292 
6293   pushf();
6294   push(raddr);
6295   push(tmp1);
6296   push(tmp2);
6297 
6298   movptr(raddr, dst);
6299 
6300   // Check null.
6301   testptr(raddr, raddr);
6302   jcc(Assembler::zero, done);
6303 
6304   in_heap_check(raddr, tmp1, done);
6305   shenandoah_cset_check(raddr, tmp1, tmp2, done);
6306 
6307   // Fail.
6308   pop(tmp2);
6309   pop(tmp1);
6310   pop(raddr);
6311   popf();
6312   const char* b = NULL;
6313   {
6314     ResourceMark rm;
6315     stringStream ss;
6316     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
6317     b = code_string(ss.as_string());
6318   }
6319   stop(b);
6320 
6321   bind(done);
6322 
6323   pop(tmp2);
6324   pop(tmp1);
6325   pop(raddr);
6326   popf();
6327 }
6328 
6329 void MacroAssembler::_shenandoah_store_check(Register dst, Register value, const char* msg, const char* file, int line) {
6330   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6331   if (dst == rsp) return; // Stack-based target
6332 
6333   Register raddr = r8;
6334   Register rval =  r9;
6335   Register tmp1 = r10;
6336   Register tmp2 = r11;
6337 
6338   // Push tmp regs and flags.
6339   pushf();
6340   push(raddr);
6341   push(rval);
6342   push(tmp1);
6343   push(tmp2);
6344 
6345   movptr(raddr, dst);
6346   movptr(rval, value);
6347 
6348   Label done;
6349 
6350   // If not in-heap target, skip check.
6351   in_heap_check(raddr, tmp1, done);
6352 
6353   // Test that target oop is not in to-space.
6354   shenandoah_cset_check(raddr, tmp1, tmp2, done);
6355 
6356   // Do value-check only when concurrent mark is in progress.
6357   movptr(tmp1, (intptr_t) ShenandoahHeap::concurrent_mark_in_progress_addr());
6358   movbool(tmp1, Address(tmp1, 0));
6359   testbool(tmp1);
6360   jcc(Assembler::zero, done);
6361 
6362   // Null-check value.
6363   testptr(rval, rval);
6364   jcc(Assembler::zero, done);
6365 
6366   // Test that value oop is not in to-space.
6367   shenandoah_cset_check(rval, tmp1, tmp2, done);
6368 
6369   // Failure.
6370   // Pop tmp regs and flags.
6371   pop(tmp2);
6372   pop(tmp1);
6373   pop(rval);
6374   pop(raddr);
6375   popf();
6376   const char* b = NULL;
6377   {
6378     ResourceMark rm;
6379     stringStream ss;
6380     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
6381     b = code_string(ss.as_string());
6382   }
6383   stop(b);
6384 
6385   bind(done);
6386 
6387   // Pop tmp regs and flags.
6388   pop(tmp2);
6389   pop(tmp1);
6390   pop(rval);
6391   pop(raddr);
6392   popf();
6393 }
6394 
6395 void MacroAssembler::_shenandoah_store_check(Address addr, Register value, const char* msg, const char* file, int line) {
6396   _shenandoah_store_check(addr.base(), value, msg, file, line);
6397 }
6398 
6399 void MacroAssembler::_shenandoah_lock_check(Register dst, const char* msg, const char* file, int line) {
6400 #ifdef ASSERT
6401   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6402 
6403   push(r8);
6404   movptr(r8, Address(dst, BasicObjectLock::obj_offset_in_bytes()));
6405   _shenandoah_store_addr_check(r8, msg, file, line);
6406   pop(r8);
6407 #endif
6408 }
6409 #endif // _LP64
6410 
6411 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6412                                                       Register tmp,
6413                                                       int offset) {
6414   intptr_t value = *delayed_value_addr;
6415   if (value != 0)
6416     return RegisterOrConstant(value + offset);
6417 
6418   // load indirectly to solve generation ordering problem
6419   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6420 
6421 #ifdef ASSERT
6422   { Label L;
6423     testptr(tmp, tmp);
6424     if (WizardMode) {
6425       const char* buf = NULL;
6426       {
6427         ResourceMark rm;
6428         stringStream ss;
6429         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6430         buf = code_string(ss.as_string());
6431       }
6432       jcc(Assembler::notZero, L);
6433       STOP(buf);
6434     } else {
6435       jccb(Assembler::notZero, L);
6436       hlt();
6437     }
6438     bind(L);
6439   }
6440 #endif
6441 
6442   if (offset != 0)
6443     addptr(tmp, offset);
6444 
6445   return RegisterOrConstant(tmp);
6446 }
6447 
6448 
6449 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6450                                          int extra_slot_offset) {
6451   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6452   int stackElementSize = Interpreter::stackElementSize;
6453   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6454 #ifdef ASSERT
6455   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6456   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6457 #endif
6458   Register             scale_reg    = noreg;
6459   Address::ScaleFactor scale_factor = Address::no_scale;
6460   if (arg_slot.is_constant()) {
6461     offset += arg_slot.as_constant() * stackElementSize;
6462   } else {
6463     scale_reg    = arg_slot.as_register();
6464     scale_factor = Address::times(stackElementSize);
6465   }
6466   offset += wordSize;           // return PC is on stack
6467   return Address(rsp, scale_reg, scale_factor, offset);
6468 }
6469 
6470 
6471 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6472   if (!VerifyOops) return;
6473 
6474   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6475   // Pass register number to verify_oop_subroutine
6476   const char* b = NULL;
6477   {
6478     ResourceMark rm;
6479     stringStream ss;
6480     ss.print("verify_oop_addr: %s", s);
6481     b = code_string(ss.as_string());
6482   }
6483 #ifdef _LP64
6484   push(rscratch1);                    // save r10, trashed by movptr()
6485 #endif
6486   push(rax);                          // save rax,
6487   // addr may contain rsp so we will have to adjust it based on the push
6488   // we just did (and on 64 bit we do two pushes)
6489   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6490   // stores rax into addr which is backwards of what was intended.
6491   if (addr.uses(rsp)) {
6492     lea(rax, addr);
6493     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6494   } else {
6495     pushptr(addr);
6496   }
6497 
6498   ExternalAddress buffer((address) b);
6499   // pass msg argument
6500   // avoid using pushptr, as it modifies scratch registers
6501   // and our contract is not to modify anything
6502   movptr(rax, buffer.addr());
6503   push(rax);
6504 
6505   // call indirectly to solve generation ordering problem
6506   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6507   call(rax);
6508   // Caller pops the arguments (addr, message) and restores rax, r10.
6509 }
6510 
6511 void MacroAssembler::verify_tlab() {
6512 #ifdef ASSERT
6513   if (UseTLAB && VerifyOops) {
6514     Label next, ok;
6515     Register t1 = rsi;
6516     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6517 
6518     push(t1);
6519     NOT_LP64(push(thread_reg));
6520     NOT_LP64(get_thread(thread_reg));
6521 
6522     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6523     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6524     jcc(Assembler::aboveEqual, next);
6525     STOP("assert(top >= start)");
6526     should_not_reach_here();
6527 
6528     bind(next);
6529     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6530     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6531     jcc(Assembler::aboveEqual, ok);
6532     STOP("assert(top <= end)");
6533     should_not_reach_here();
6534 
6535     bind(ok);
6536     NOT_LP64(pop(thread_reg));
6537     pop(t1);
6538   }
6539 #endif
6540 }
6541 
6542 class ControlWord {
6543  public:
6544   int32_t _value;
6545 
6546   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6547   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6548   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6549   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6550   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6551   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6552   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6553   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6554 
6555   void print() const {
6556     // rounding control
6557     const char* rc;
6558     switch (rounding_control()) {
6559       case 0: rc = "round near"; break;
6560       case 1: rc = "round down"; break;
6561       case 2: rc = "round up  "; break;
6562       case 3: rc = "chop      "; break;
6563     };
6564     // precision control
6565     const char* pc;
6566     switch (precision_control()) {
6567       case 0: pc = "24 bits "; break;
6568       case 1: pc = "reserved"; break;
6569       case 2: pc = "53 bits "; break;
6570       case 3: pc = "64 bits "; break;
6571     };
6572     // flags
6573     char f[9];
6574     f[0] = ' ';
6575     f[1] = ' ';
6576     f[2] = (precision   ()) ? 'P' : 'p';
6577     f[3] = (underflow   ()) ? 'U' : 'u';
6578     f[4] = (overflow    ()) ? 'O' : 'o';
6579     f[5] = (zero_divide ()) ? 'Z' : 'z';
6580     f[6] = (denormalized()) ? 'D' : 'd';
6581     f[7] = (invalid     ()) ? 'I' : 'i';
6582     f[8] = '\x0';
6583     // output
6584     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6585   }
6586 
6587 };
6588 
6589 class StatusWord {
6590  public:
6591   int32_t _value;
6592 
6593   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6594   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6595   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6596   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6597   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6598   int  top() const                     { return  (_value >> 11) & 7      ; }
6599   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6600   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6601   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6602   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6603   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6604   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6605   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6606   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6607 
6608   void print() const {
6609     // condition codes
6610     char c[5];
6611     c[0] = (C3()) ? '3' : '-';
6612     c[1] = (C2()) ? '2' : '-';
6613     c[2] = (C1()) ? '1' : '-';
6614     c[3] = (C0()) ? '0' : '-';
6615     c[4] = '\x0';
6616     // flags
6617     char f[9];
6618     f[0] = (error_status()) ? 'E' : '-';
6619     f[1] = (stack_fault ()) ? 'S' : '-';
6620     f[2] = (precision   ()) ? 'P' : '-';
6621     f[3] = (underflow   ()) ? 'U' : '-';
6622     f[4] = (overflow    ()) ? 'O' : '-';
6623     f[5] = (zero_divide ()) ? 'Z' : '-';
6624     f[6] = (denormalized()) ? 'D' : '-';
6625     f[7] = (invalid     ()) ? 'I' : '-';
6626     f[8] = '\x0';
6627     // output
6628     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6629   }
6630 
6631 };
6632 
6633 class TagWord {
6634  public:
6635   int32_t _value;
6636 
6637   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6638 
6639   void print() const {
6640     printf("%04x", _value & 0xFFFF);
6641   }
6642 
6643 };
6644 
6645 class FPU_Register {
6646  public:
6647   int32_t _m0;
6648   int32_t _m1;
6649   int16_t _ex;
6650 
6651   bool is_indefinite() const           {
6652     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6653   }
6654 
6655   void print() const {
6656     char  sign = (_ex < 0) ? '-' : '+';
6657     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6658     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6659   };
6660 
6661 };
6662 
6663 class FPU_State {
6664  public:
6665   enum {
6666     register_size       = 10,
6667     number_of_registers =  8,
6668     register_mask       =  7
6669   };
6670 
6671   ControlWord  _control_word;
6672   StatusWord   _status_word;
6673   TagWord      _tag_word;
6674   int32_t      _error_offset;
6675   int32_t      _error_selector;
6676   int32_t      _data_offset;
6677   int32_t      _data_selector;
6678   int8_t       _register[register_size * number_of_registers];
6679 
6680   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6681   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6682 
6683   const char* tag_as_string(int tag) const {
6684     switch (tag) {
6685       case 0: return "valid";
6686       case 1: return "zero";
6687       case 2: return "special";
6688       case 3: return "empty";
6689     }
6690     ShouldNotReachHere();
6691     return NULL;
6692   }
6693 
6694   void print() const {
6695     // print computation registers
6696     { int t = _status_word.top();
6697       for (int i = 0; i < number_of_registers; i++) {
6698         int j = (i - t) & register_mask;
6699         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6700         st(j)->print();
6701         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6702       }
6703     }
6704     printf("\n");
6705     // print control registers
6706     printf("ctrl = "); _control_word.print(); printf("\n");
6707     printf("stat = "); _status_word .print(); printf("\n");
6708     printf("tags = "); _tag_word    .print(); printf("\n");
6709   }
6710 
6711 };
6712 
6713 class Flag_Register {
6714  public:
6715   int32_t _value;
6716 
6717   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6718   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6719   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6720   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6721   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6722   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6723   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6724 
6725   void print() const {
6726     // flags
6727     char f[8];
6728     f[0] = (overflow       ()) ? 'O' : '-';
6729     f[1] = (direction      ()) ? 'D' : '-';
6730     f[2] = (sign           ()) ? 'S' : '-';
6731     f[3] = (zero           ()) ? 'Z' : '-';
6732     f[4] = (auxiliary_carry()) ? 'A' : '-';
6733     f[5] = (parity         ()) ? 'P' : '-';
6734     f[6] = (carry          ()) ? 'C' : '-';
6735     f[7] = '\x0';
6736     // output
6737     printf("%08x  flags = %s", _value, f);
6738   }
6739 
6740 };
6741 
6742 class IU_Register {
6743  public:
6744   int32_t _value;
6745 
6746   void print() const {
6747     printf("%08x  %11d", _value, _value);
6748   }
6749 
6750 };
6751 
6752 class IU_State {
6753  public:
6754   Flag_Register _eflags;
6755   IU_Register   _rdi;
6756   IU_Register   _rsi;
6757   IU_Register   _rbp;
6758   IU_Register   _rsp;
6759   IU_Register   _rbx;
6760   IU_Register   _rdx;
6761   IU_Register   _rcx;
6762   IU_Register   _rax;
6763 
6764   void print() const {
6765     // computation registers
6766     printf("rax,  = "); _rax.print(); printf("\n");
6767     printf("rbx,  = "); _rbx.print(); printf("\n");
6768     printf("rcx  = "); _rcx.print(); printf("\n");
6769     printf("rdx  = "); _rdx.print(); printf("\n");
6770     printf("rdi  = "); _rdi.print(); printf("\n");
6771     printf("rsi  = "); _rsi.print(); printf("\n");
6772     printf("rbp,  = "); _rbp.print(); printf("\n");
6773     printf("rsp  = "); _rsp.print(); printf("\n");
6774     printf("\n");
6775     // control registers
6776     printf("flgs = "); _eflags.print(); printf("\n");
6777   }
6778 };
6779 
6780 
6781 class CPU_State {
6782  public:
6783   FPU_State _fpu_state;
6784   IU_State  _iu_state;
6785 
6786   void print() const {
6787     printf("--------------------------------------------------\n");
6788     _iu_state .print();
6789     printf("\n");
6790     _fpu_state.print();
6791     printf("--------------------------------------------------\n");
6792   }
6793 
6794 };
6795 
6796 
6797 static void _print_CPU_state(CPU_State* state) {
6798   state->print();
6799 };
6800 
6801 
6802 void MacroAssembler::print_CPU_state() {
6803   push_CPU_state();
6804   push(rsp);                // pass CPU state
6805   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6806   addptr(rsp, wordSize);       // discard argument
6807   pop_CPU_state();
6808 }
6809 
6810 
6811 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6812   static int counter = 0;
6813   FPU_State* fs = &state->_fpu_state;
6814   counter++;
6815   // For leaf calls, only verify that the top few elements remain empty.
6816   // We only need 1 empty at the top for C2 code.
6817   if( stack_depth < 0 ) {
6818     if( fs->tag_for_st(7) != 3 ) {
6819       printf("FPR7 not empty\n");
6820       state->print();
6821       assert(false, "error");
6822       return false;
6823     }
6824     return true;                // All other stack states do not matter
6825   }
6826 
6827   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6828          "bad FPU control word");
6829 
6830   // compute stack depth
6831   int i = 0;
6832   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6833   int d = i;
6834   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6835   // verify findings
6836   if (i != FPU_State::number_of_registers) {
6837     // stack not contiguous
6838     printf("%s: stack not contiguous at ST%d\n", s, i);
6839     state->print();
6840     assert(false, "error");
6841     return false;
6842   }
6843   // check if computed stack depth corresponds to expected stack depth
6844   if (stack_depth < 0) {
6845     // expected stack depth is -stack_depth or less
6846     if (d > -stack_depth) {
6847       // too many elements on the stack
6848       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6849       state->print();
6850       assert(false, "error");
6851       return false;
6852     }
6853   } else {
6854     // expected stack depth is stack_depth
6855     if (d != stack_depth) {
6856       // wrong stack depth
6857       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6858       state->print();
6859       assert(false, "error");
6860       return false;
6861     }
6862   }
6863   // everything is cool
6864   return true;
6865 }
6866 
6867 
6868 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6869   if (!VerifyFPU) return;
6870   push_CPU_state();
6871   push(rsp);                // pass CPU state
6872   ExternalAddress msg((address) s);
6873   // pass message string s
6874   pushptr(msg.addr());
6875   push(stack_depth);        // pass stack depth
6876   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6877   addptr(rsp, 3 * wordSize);   // discard arguments
6878   // check for error
6879   { Label L;
6880     testl(rax, rax);
6881     jcc(Assembler::notZero, L);
6882     int3();                  // break if error condition
6883     bind(L);
6884   }
6885   pop_CPU_state();
6886 }
6887 
6888 void MacroAssembler::restore_cpu_control_state_after_jni() {
6889   // Either restore the MXCSR register after returning from the JNI Call
6890   // or verify that it wasn't changed (with -Xcheck:jni flag).
6891   if (VM_Version::supports_sse()) {
6892     if (RestoreMXCSROnJNICalls) {
6893       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6894     } else if (CheckJNICalls) {
6895       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6896     }
6897   }
6898   if (VM_Version::supports_avx()) {
6899     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6900     vzeroupper();
6901   }
6902 
6903 #ifndef _LP64
6904   // Either restore the x87 floating pointer control word after returning
6905   // from the JNI call or verify that it wasn't changed.
6906   if (CheckJNICalls) {
6907     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6908   }
6909 #endif // _LP64
6910 }
6911 
6912 void MacroAssembler::load_mirror(Register mirror, Register method) {
6913   // get mirror
6914   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6915   movptr(mirror, Address(method, Method::const_offset()));
6916   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6917   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6918   movptr(mirror, Address(mirror, mirror_offset));
6919 }
6920 
6921 void MacroAssembler::load_klass(Register dst, Register src) {
6922 #ifdef _LP64
6923   if (UseCompressedClassPointers) {
6924     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6925     decode_klass_not_null(dst);
6926   } else
6927 #endif
6928     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6929 }
6930 
6931 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6932   load_klass(dst, src);
6933   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6934 }
6935 
6936 void MacroAssembler::store_klass(Register dst, Register src) {
6937 #ifdef _LP64
6938   if (UseCompressedClassPointers) {
6939     encode_klass_not_null(src);
6940     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6941   } else
6942 #endif
6943     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6944 }
6945 
6946 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6947 #ifdef _LP64
6948   // FIXME: Must change all places where we try to load the klass.
6949   if (UseCompressedOops) {
6950     movl(dst, src);
6951     decode_heap_oop(dst);
6952   } else
6953 #endif
6954     movptr(dst, src);
6955 }
6956 
6957 // Doesn't do verfication, generates fixed size code
6958 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6959 #ifdef _LP64
6960   if (UseCompressedOops) {
6961     movl(dst, src);
6962     decode_heap_oop_not_null(dst);
6963   } else
6964 #endif
6965     movptr(dst, src);
6966 }
6967 
6968 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6969 #ifdef _LP64
6970   if (UseCompressedOops) {
6971     assert(!dst.uses(src), "not enough registers");
6972     encode_heap_oop(src);
6973     movl(dst, src);
6974   } else
6975 #endif
6976     movptr(dst, src);
6977 }
6978 
6979 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6980   assert_different_registers(src1, tmp);
6981 #ifdef _LP64
6982   if (UseCompressedOops) {
6983     bool did_push = false;
6984     if (tmp == noreg) {
6985       tmp = rax;
6986       push(tmp);
6987       did_push = true;
6988       assert(!src2.uses(rsp), "can't push");
6989     }
6990     load_heap_oop(tmp, src2);
6991     cmpptr(src1, tmp);
6992     if (did_push)  pop(tmp);
6993   } else
6994 #endif
6995     cmpptr(src1, src2);
6996 }
6997 
6998 // Used for storing NULLs.
6999 void MacroAssembler::store_heap_oop_null(Address dst) {
7000 #ifdef _LP64
7001   if (UseCompressedOops) {
7002     movl(dst, (int32_t)NULL_WORD);
7003   } else {
7004     movslq(dst, (int32_t)NULL_WORD);
7005   }
7006 #else
7007   movl(dst, (int32_t)NULL_WORD);
7008 #endif
7009 }
7010 
7011 #ifdef _LP64
7012 void MacroAssembler::store_klass_gap(Register dst, Register src) {
7013   if (UseCompressedClassPointers) {
7014     // Store to klass gap in destination
7015     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
7016   }
7017 }
7018 
7019 #ifdef ASSERT
7020 void MacroAssembler::verify_heapbase(const char* msg) {
7021   assert (UseCompressedOops, "should be compressed");
7022   assert (Universe::heap() != NULL, "java heap should be initialized");
7023   if (CheckCompressedOops) {
7024     Label ok;
7025     push(rscratch1); // cmpptr trashes rscratch1
7026     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7027     jcc(Assembler::equal, ok);
7028     STOP(msg);
7029     bind(ok);
7030     pop(rscratch1);
7031   }
7032 }
7033 #endif
7034 
7035 // Algorithm must match oop.inline.hpp encode_heap_oop.
7036 void MacroAssembler::encode_heap_oop(Register r) {
7037 #ifdef ASSERT
7038   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
7039 #endif
7040   verify_oop(r, "broken oop in encode_heap_oop");
7041   if (Universe::narrow_oop_base() == NULL) {
7042     if (Universe::narrow_oop_shift() != 0) {
7043       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7044       shrq(r, LogMinObjAlignmentInBytes);
7045     }
7046     return;
7047   }
7048   testq(r, r);
7049   cmovq(Assembler::equal, r, r12_heapbase);
7050   subq(r, r12_heapbase);
7051   shrq(r, LogMinObjAlignmentInBytes);
7052 }
7053 
7054 void MacroAssembler::encode_heap_oop_not_null(Register r) {
7055 #ifdef ASSERT
7056   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
7057   if (CheckCompressedOops) {
7058     Label ok;
7059     testq(r, r);
7060     jcc(Assembler::notEqual, ok);
7061     STOP("null oop passed to encode_heap_oop_not_null");
7062     bind(ok);
7063   }
7064 #endif
7065   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7066   if (Universe::narrow_oop_base() != NULL) {
7067     subq(r, r12_heapbase);
7068   }
7069   if (Universe::narrow_oop_shift() != 0) {
7070     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7071     shrq(r, LogMinObjAlignmentInBytes);
7072   }
7073 }
7074 
7075 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7076 #ifdef ASSERT
7077   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7078   if (CheckCompressedOops) {
7079     Label ok;
7080     testq(src, src);
7081     jcc(Assembler::notEqual, ok);
7082     STOP("null oop passed to encode_heap_oop_not_null2");
7083     bind(ok);
7084   }
7085 #endif
7086   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7087   if (dst != src) {
7088     movq(dst, src);
7089   }
7090   if (Universe::narrow_oop_base() != NULL) {
7091     subq(dst, r12_heapbase);
7092   }
7093   if (Universe::narrow_oop_shift() != 0) {
7094     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7095     shrq(dst, LogMinObjAlignmentInBytes);
7096   }
7097 }
7098 
7099 void  MacroAssembler::decode_heap_oop(Register r) {
7100 #ifdef ASSERT
7101   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7102 #endif
7103   if (Universe::narrow_oop_base() == NULL) {
7104     if (Universe::narrow_oop_shift() != 0) {
7105       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7106       shlq(r, LogMinObjAlignmentInBytes);
7107     }
7108   } else {
7109     Label done;
7110     shlq(r, LogMinObjAlignmentInBytes);
7111     jccb(Assembler::equal, done);
7112     addq(r, r12_heapbase);
7113     bind(done);
7114   }
7115   verify_oop(r, "broken oop in decode_heap_oop");
7116 }
7117 
7118 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7119   // Note: it will change flags
7120   assert (UseCompressedOops, "should only be used for compressed headers");
7121   assert (Universe::heap() != NULL, "java heap should be initialized");
7122   // Cannot assert, unverified entry point counts instructions (see .ad file)
7123   // vtableStubs also counts instructions in pd_code_size_limit.
7124   // Also do not verify_oop as this is called by verify_oop.
7125   if (Universe::narrow_oop_shift() != 0) {
7126     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7127     shlq(r, LogMinObjAlignmentInBytes);
7128     if (Universe::narrow_oop_base() != NULL) {
7129       addq(r, r12_heapbase);
7130     }
7131   } else {
7132     assert (Universe::narrow_oop_base() == NULL, "sanity");
7133   }
7134 }
7135 
7136 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7137   // Note: it will change flags
7138   assert (UseCompressedOops, "should only be used for compressed headers");
7139   assert (Universe::heap() != NULL, "java heap should be initialized");
7140   // Cannot assert, unverified entry point counts instructions (see .ad file)
7141   // vtableStubs also counts instructions in pd_code_size_limit.
7142   // Also do not verify_oop as this is called by verify_oop.
7143   if (Universe::narrow_oop_shift() != 0) {
7144     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7145     if (LogMinObjAlignmentInBytes == Address::times_8) {
7146       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7147     } else {
7148       if (dst != src) {
7149         movq(dst, src);
7150       }
7151       shlq(dst, LogMinObjAlignmentInBytes);
7152       if (Universe::narrow_oop_base() != NULL) {
7153         addq(dst, r12_heapbase);
7154       }
7155     }
7156   } else {
7157     assert (Universe::narrow_oop_base() == NULL, "sanity");
7158     if (dst != src) {
7159       movq(dst, src);
7160     }
7161   }
7162 }
7163 
7164 void MacroAssembler::encode_klass_not_null(Register r) {
7165   if (Universe::narrow_klass_base() != NULL) {
7166     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7167     assert(r != r12_heapbase, "Encoding a klass in r12");
7168     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7169     subq(r, r12_heapbase);
7170   }
7171   if (Universe::narrow_klass_shift() != 0) {
7172     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7173     shrq(r, LogKlassAlignmentInBytes);
7174   }
7175   if (Universe::narrow_klass_base() != NULL) {
7176     reinit_heapbase();
7177   }
7178 }
7179 
7180 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7181   if (dst == src) {
7182     encode_klass_not_null(src);
7183   } else {
7184     if (Universe::narrow_klass_base() != NULL) {
7185       mov64(dst, (int64_t)Universe::narrow_klass_base());
7186       negq(dst);
7187       addq(dst, src);
7188     } else {
7189       movptr(dst, src);
7190     }
7191     if (Universe::narrow_klass_shift() != 0) {
7192       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7193       shrq(dst, LogKlassAlignmentInBytes);
7194     }
7195   }
7196 }
7197 
7198 // Function instr_size_for_decode_klass_not_null() counts the instructions
7199 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7200 // when (Universe::heap() != NULL).  Hence, if the instructions they
7201 // generate change, then this method needs to be updated.
7202 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7203   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7204   if (Universe::narrow_klass_base() != NULL) {
7205     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7206     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7207   } else {
7208     // longest load decode klass function, mov64, leaq
7209     return 16;
7210   }
7211 }
7212 
7213 // !!! If the instructions that get generated here change then function
7214 // instr_size_for_decode_klass_not_null() needs to get updated.
7215 void  MacroAssembler::decode_klass_not_null(Register r) {
7216   // Note: it will change flags
7217   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7218   assert(r != r12_heapbase, "Decoding a klass in r12");
7219   // Cannot assert, unverified entry point counts instructions (see .ad file)
7220   // vtableStubs also counts instructions in pd_code_size_limit.
7221   // Also do not verify_oop as this is called by verify_oop.
7222   if (Universe::narrow_klass_shift() != 0) {
7223     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7224     shlq(r, LogKlassAlignmentInBytes);
7225   }
7226   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7227   if (Universe::narrow_klass_base() != NULL) {
7228     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7229     addq(r, r12_heapbase);
7230     reinit_heapbase();
7231   }
7232 }
7233 
7234 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7235   // Note: it will change flags
7236   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7237   if (dst == src) {
7238     decode_klass_not_null(dst);
7239   } else {
7240     // Cannot assert, unverified entry point counts instructions (see .ad file)
7241     // vtableStubs also counts instructions in pd_code_size_limit.
7242     // Also do not verify_oop as this is called by verify_oop.
7243     mov64(dst, (int64_t)Universe::narrow_klass_base());
7244     if (Universe::narrow_klass_shift() != 0) {
7245       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7246       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7247       leaq(dst, Address(dst, src, Address::times_8, 0));
7248     } else {
7249       addq(dst, src);
7250     }
7251   }
7252 }
7253 
7254 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7255   assert (UseCompressedOops, "should only be used for compressed headers");
7256   assert (Universe::heap() != NULL, "java heap should be initialized");
7257   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7258   int oop_index = oop_recorder()->find_index(obj);
7259   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7260   mov_narrow_oop(dst, oop_index, rspec);
7261 }
7262 
7263 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7264   assert (UseCompressedOops, "should only be used for compressed headers");
7265   assert (Universe::heap() != NULL, "java heap should be initialized");
7266   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7267   int oop_index = oop_recorder()->find_index(obj);
7268   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7269   mov_narrow_oop(dst, oop_index, rspec);
7270 }
7271 
7272 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7273   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7274   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7275   int klass_index = oop_recorder()->find_index(k);
7276   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7277   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7278 }
7279 
7280 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7281   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7282   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7283   int klass_index = oop_recorder()->find_index(k);
7284   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7285   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7286 }
7287 
7288 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7289   assert (UseCompressedOops, "should only be used for compressed headers");
7290   assert (Universe::heap() != NULL, "java heap should be initialized");
7291   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7292   int oop_index = oop_recorder()->find_index(obj);
7293   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7294   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7295 }
7296 
7297 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7298   assert (UseCompressedOops, "should only be used for compressed headers");
7299   assert (Universe::heap() != NULL, "java heap should be initialized");
7300   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7301   int oop_index = oop_recorder()->find_index(obj);
7302   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7303   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7304 }
7305 
7306 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7307   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7308   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7309   int klass_index = oop_recorder()->find_index(k);
7310   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7311   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7312 }
7313 
7314 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7315   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7316   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7317   int klass_index = oop_recorder()->find_index(k);
7318   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7319   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7320 }
7321 
7322 void MacroAssembler::reinit_heapbase() {
7323   if (UseCompressedOops || UseCompressedClassPointers) {
7324     if (Universe::heap() != NULL) {
7325       if (Universe::narrow_oop_base() == NULL) {
7326         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7327       } else {
7328         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7329       }
7330     } else {
7331       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7332     }
7333   }
7334 }
7335 
7336 #endif // _LP64
7337 
7338 
7339 // C2 compiled method's prolog code.
7340 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7341 
7342   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7343   // NativeJump::patch_verified_entry will be able to patch out the entry
7344   // code safely. The push to verify stack depth is ok at 5 bytes,
7345   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7346   // stack bang then we must use the 6 byte frame allocation even if
7347   // we have no frame. :-(
7348   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7349 
7350   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7351   // Remove word for return addr
7352   framesize -= wordSize;
7353   stack_bang_size -= wordSize;
7354 
7355   // Calls to C2R adapters often do not accept exceptional returns.
7356   // We require that their callers must bang for them.  But be careful, because
7357   // some VM calls (such as call site linkage) can use several kilobytes of
7358   // stack.  But the stack safety zone should account for that.
7359   // See bugs 4446381, 4468289, 4497237.
7360   if (stack_bang_size > 0) {
7361     generate_stack_overflow_check(stack_bang_size);
7362 
7363     // We always push rbp, so that on return to interpreter rbp, will be
7364     // restored correctly and we can correct the stack.
7365     push(rbp);
7366     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7367     if (PreserveFramePointer) {
7368       mov(rbp, rsp);
7369     }
7370     // Remove word for ebp
7371     framesize -= wordSize;
7372 
7373     // Create frame
7374     if (framesize) {
7375       subptr(rsp, framesize);
7376     }
7377   } else {
7378     // Create frame (force generation of a 4 byte immediate value)
7379     subptr_imm32(rsp, framesize);
7380 
7381     // Save RBP register now.
7382     framesize -= wordSize;
7383     movptr(Address(rsp, framesize), rbp);
7384     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7385     if (PreserveFramePointer) {
7386       movptr(rbp, rsp);
7387       if (framesize > 0) {
7388         addptr(rbp, framesize);
7389       }
7390     }
7391   }
7392 
7393   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7394     framesize -= wordSize;
7395     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7396   }
7397 
7398 #ifndef _LP64
7399   // If method sets FPU control word do it now
7400   if (fp_mode_24b) {
7401     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7402   }
7403   if (UseSSE >= 2 && VerifyFPU) {
7404     verify_FPU(0, "FPU stack must be clean on entry");
7405   }
7406 #endif
7407 
7408 #ifdef ASSERT
7409   if (VerifyStackAtCalls) {
7410     Label L;
7411     push(rax);
7412     mov(rax, rsp);
7413     andptr(rax, StackAlignmentInBytes-1);
7414     cmpptr(rax, StackAlignmentInBytes-wordSize);
7415     pop(rax);
7416     jcc(Assembler::equal, L);
7417     STOP("Stack is not properly aligned!");
7418     bind(L);
7419   }
7420 #endif
7421 
7422 }
7423 
7424 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7425   // cnt - number of qwords (8-byte words).
7426   // base - start address, qword aligned.
7427   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7428   assert(base==rdi, "base register must be edi for rep stos");
7429   assert(tmp==rax,   "tmp register must be eax for rep stos");
7430   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7431   assert(InitArrayShortSize % BytesPerLong == 0,
7432     "InitArrayShortSize should be the multiple of BytesPerLong");
7433 
7434   Label DONE;
7435 
7436   xorptr(tmp, tmp);
7437 
7438   if (!is_large) {
7439     Label LOOP, LONG;
7440     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7441     jccb(Assembler::greater, LONG);
7442 
7443     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7444 
7445     decrement(cnt);
7446     jccb(Assembler::negative, DONE); // Zero length
7447 
7448     // Use individual pointer-sized stores for small counts:
7449     BIND(LOOP);
7450     movptr(Address(base, cnt, Address::times_ptr), tmp);
7451     decrement(cnt);
7452     jccb(Assembler::greaterEqual, LOOP);
7453     jmpb(DONE);
7454 
7455     BIND(LONG);
7456   }
7457 
7458   // Use longer rep-prefixed ops for non-small counts:
7459   if (UseFastStosb) {
7460     shlptr(cnt, 3); // convert to number of bytes
7461     rep_stosb();
7462   } else {
7463     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7464     rep_stos();
7465   }
7466 
7467   BIND(DONE);
7468 }
7469 
7470 #ifdef COMPILER2
7471 
7472 // IndexOf for constant substrings with size >= 8 chars
7473 // which don't need to be loaded through stack.
7474 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7475                                       Register cnt1, Register cnt2,
7476                                       int int_cnt2,  Register result,
7477                                       XMMRegister vec, Register tmp,
7478                                       int ae) {
7479   ShortBranchVerifier sbv(this);
7480   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7481   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7482 
7483   // This method uses the pcmpestri instruction with bound registers
7484   //   inputs:
7485   //     xmm - substring
7486   //     rax - substring length (elements count)
7487   //     mem - scanned string
7488   //     rdx - string length (elements count)
7489   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7490   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7491   //   outputs:
7492   //     rcx - matched index in string
7493   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7494   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7495   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7496   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7497   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7498 
7499   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7500         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7501         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7502 
7503   // Note, inline_string_indexOf() generates checks:
7504   // if (substr.count > string.count) return -1;
7505   // if (substr.count == 0) return 0;
7506   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7507 
7508   // Load substring.
7509   if (ae == StrIntrinsicNode::UL) {
7510     pmovzxbw(vec, Address(str2, 0));
7511   } else {
7512     movdqu(vec, Address(str2, 0));
7513   }
7514   movl(cnt2, int_cnt2);
7515   movptr(result, str1); // string addr
7516 
7517   if (int_cnt2 > stride) {
7518     jmpb(SCAN_TO_SUBSTR);
7519 
7520     // Reload substr for rescan, this code
7521     // is executed only for large substrings (> 8 chars)
7522     bind(RELOAD_SUBSTR);
7523     if (ae == StrIntrinsicNode::UL) {
7524       pmovzxbw(vec, Address(str2, 0));
7525     } else {
7526       movdqu(vec, Address(str2, 0));
7527     }
7528     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7529 
7530     bind(RELOAD_STR);
7531     // We came here after the beginning of the substring was
7532     // matched but the rest of it was not so we need to search
7533     // again. Start from the next element after the previous match.
7534 
7535     // cnt2 is number of substring reminding elements and
7536     // cnt1 is number of string reminding elements when cmp failed.
7537     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7538     subl(cnt1, cnt2);
7539     addl(cnt1, int_cnt2);
7540     movl(cnt2, int_cnt2); // Now restore cnt2
7541 
7542     decrementl(cnt1);     // Shift to next element
7543     cmpl(cnt1, cnt2);
7544     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7545 
7546     addptr(result, (1<<scale1));
7547 
7548   } // (int_cnt2 > 8)
7549 
7550   // Scan string for start of substr in 16-byte vectors
7551   bind(SCAN_TO_SUBSTR);
7552   pcmpestri(vec, Address(result, 0), mode);
7553   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7554   subl(cnt1, stride);
7555   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7556   cmpl(cnt1, cnt2);
7557   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7558   addptr(result, 16);
7559   jmpb(SCAN_TO_SUBSTR);
7560 
7561   // Found a potential substr
7562   bind(FOUND_CANDIDATE);
7563   // Matched whole vector if first element matched (tmp(rcx) == 0).
7564   if (int_cnt2 == stride) {
7565     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7566   } else { // int_cnt2 > 8
7567     jccb(Assembler::overflow, FOUND_SUBSTR);
7568   }
7569   // After pcmpestri tmp(rcx) contains matched element index
7570   // Compute start addr of substr
7571   lea(result, Address(result, tmp, scale1));
7572 
7573   // Make sure string is still long enough
7574   subl(cnt1, tmp);
7575   cmpl(cnt1, cnt2);
7576   if (int_cnt2 == stride) {
7577     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7578   } else { // int_cnt2 > 8
7579     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7580   }
7581   // Left less then substring.
7582 
7583   bind(RET_NOT_FOUND);
7584   movl(result, -1);
7585   jmp(EXIT);
7586 
7587   if (int_cnt2 > stride) {
7588     // This code is optimized for the case when whole substring
7589     // is matched if its head is matched.
7590     bind(MATCH_SUBSTR_HEAD);
7591     pcmpestri(vec, Address(result, 0), mode);
7592     // Reload only string if does not match
7593     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7594 
7595     Label CONT_SCAN_SUBSTR;
7596     // Compare the rest of substring (> 8 chars).
7597     bind(FOUND_SUBSTR);
7598     // First 8 chars are already matched.
7599     negptr(cnt2);
7600     addptr(cnt2, stride);
7601 
7602     bind(SCAN_SUBSTR);
7603     subl(cnt1, stride);
7604     cmpl(cnt2, -stride); // Do not read beyond substring
7605     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7606     // Back-up strings to avoid reading beyond substring:
7607     // cnt1 = cnt1 - cnt2 + 8
7608     addl(cnt1, cnt2); // cnt2 is negative
7609     addl(cnt1, stride);
7610     movl(cnt2, stride); negptr(cnt2);
7611     bind(CONT_SCAN_SUBSTR);
7612     if (int_cnt2 < (int)G) {
7613       int tail_off1 = int_cnt2<<scale1;
7614       int tail_off2 = int_cnt2<<scale2;
7615       if (ae == StrIntrinsicNode::UL) {
7616         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7617       } else {
7618         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7619       }
7620       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7621     } else {
7622       // calculate index in register to avoid integer overflow (int_cnt2*2)
7623       movl(tmp, int_cnt2);
7624       addptr(tmp, cnt2);
7625       if (ae == StrIntrinsicNode::UL) {
7626         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7627       } else {
7628         movdqu(vec, Address(str2, tmp, scale2, 0));
7629       }
7630       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7631     }
7632     // Need to reload strings pointers if not matched whole vector
7633     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7634     addptr(cnt2, stride);
7635     jcc(Assembler::negative, SCAN_SUBSTR);
7636     // Fall through if found full substring
7637 
7638   } // (int_cnt2 > 8)
7639 
7640   bind(RET_FOUND);
7641   // Found result if we matched full small substring.
7642   // Compute substr offset
7643   subptr(result, str1);
7644   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7645     shrl(result, 1); // index
7646   }
7647   bind(EXIT);
7648 
7649 } // string_indexofC8
7650 
7651 // Small strings are loaded through stack if they cross page boundary.
7652 void MacroAssembler::string_indexof(Register str1, Register str2,
7653                                     Register cnt1, Register cnt2,
7654                                     int int_cnt2,  Register result,
7655                                     XMMRegister vec, Register tmp,
7656                                     int ae) {
7657   ShortBranchVerifier sbv(this);
7658   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7659   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7660 
7661   //
7662   // int_cnt2 is length of small (< 8 chars) constant substring
7663   // or (-1) for non constant substring in which case its length
7664   // is in cnt2 register.
7665   //
7666   // Note, inline_string_indexOf() generates checks:
7667   // if (substr.count > string.count) return -1;
7668   // if (substr.count == 0) return 0;
7669   //
7670   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7671   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7672   // This method uses the pcmpestri instruction with bound registers
7673   //   inputs:
7674   //     xmm - substring
7675   //     rax - substring length (elements count)
7676   //     mem - scanned string
7677   //     rdx - string length (elements count)
7678   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7679   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7680   //   outputs:
7681   //     rcx - matched index in string
7682   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7683   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7684   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7685   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7686 
7687   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7688         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7689         FOUND_CANDIDATE;
7690 
7691   { //========================================================
7692     // We don't know where these strings are located
7693     // and we can't read beyond them. Load them through stack.
7694     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7695 
7696     movptr(tmp, rsp); // save old SP
7697 
7698     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7699       if (int_cnt2 == (1>>scale2)) { // One byte
7700         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7701         load_unsigned_byte(result, Address(str2, 0));
7702         movdl(vec, result); // move 32 bits
7703       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7704         // Not enough header space in 32-bit VM: 12+3 = 15.
7705         movl(result, Address(str2, -1));
7706         shrl(result, 8);
7707         movdl(vec, result); // move 32 bits
7708       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7709         load_unsigned_short(result, Address(str2, 0));
7710         movdl(vec, result); // move 32 bits
7711       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7712         movdl(vec, Address(str2, 0)); // move 32 bits
7713       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7714         movq(vec, Address(str2, 0));  // move 64 bits
7715       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7716         // Array header size is 12 bytes in 32-bit VM
7717         // + 6 bytes for 3 chars == 18 bytes,
7718         // enough space to load vec and shift.
7719         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7720         if (ae == StrIntrinsicNode::UL) {
7721           int tail_off = int_cnt2-8;
7722           pmovzxbw(vec, Address(str2, tail_off));
7723           psrldq(vec, -2*tail_off);
7724         }
7725         else {
7726           int tail_off = int_cnt2*(1<<scale2);
7727           movdqu(vec, Address(str2, tail_off-16));
7728           psrldq(vec, 16-tail_off);
7729         }
7730       }
7731     } else { // not constant substring
7732       cmpl(cnt2, stride);
7733       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7734 
7735       // We can read beyond string if srt+16 does not cross page boundary
7736       // since heaps are aligned and mapped by pages.
7737       assert(os::vm_page_size() < (int)G, "default page should be small");
7738       movl(result, str2); // We need only low 32 bits
7739       andl(result, (os::vm_page_size()-1));
7740       cmpl(result, (os::vm_page_size()-16));
7741       jccb(Assembler::belowEqual, CHECK_STR);
7742 
7743       // Move small strings to stack to allow load 16 bytes into vec.
7744       subptr(rsp, 16);
7745       int stk_offset = wordSize-(1<<scale2);
7746       push(cnt2);
7747 
7748       bind(COPY_SUBSTR);
7749       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7750         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7751         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7752       } else if (ae == StrIntrinsicNode::UU) {
7753         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7754         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7755       }
7756       decrement(cnt2);
7757       jccb(Assembler::notZero, COPY_SUBSTR);
7758 
7759       pop(cnt2);
7760       movptr(str2, rsp);  // New substring address
7761     } // non constant
7762 
7763     bind(CHECK_STR);
7764     cmpl(cnt1, stride);
7765     jccb(Assembler::aboveEqual, BIG_STRINGS);
7766 
7767     // Check cross page boundary.
7768     movl(result, str1); // We need only low 32 bits
7769     andl(result, (os::vm_page_size()-1));
7770     cmpl(result, (os::vm_page_size()-16));
7771     jccb(Assembler::belowEqual, BIG_STRINGS);
7772 
7773     subptr(rsp, 16);
7774     int stk_offset = -(1<<scale1);
7775     if (int_cnt2 < 0) { // not constant
7776       push(cnt2);
7777       stk_offset += wordSize;
7778     }
7779     movl(cnt2, cnt1);
7780 
7781     bind(COPY_STR);
7782     if (ae == StrIntrinsicNode::LL) {
7783       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7784       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7785     } else {
7786       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7787       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7788     }
7789     decrement(cnt2);
7790     jccb(Assembler::notZero, COPY_STR);
7791 
7792     if (int_cnt2 < 0) { // not constant
7793       pop(cnt2);
7794     }
7795     movptr(str1, rsp);  // New string address
7796 
7797     bind(BIG_STRINGS);
7798     // Load substring.
7799     if (int_cnt2 < 0) { // -1
7800       if (ae == StrIntrinsicNode::UL) {
7801         pmovzxbw(vec, Address(str2, 0));
7802       } else {
7803         movdqu(vec, Address(str2, 0));
7804       }
7805       push(cnt2);       // substr count
7806       push(str2);       // substr addr
7807       push(str1);       // string addr
7808     } else {
7809       // Small (< 8 chars) constant substrings are loaded already.
7810       movl(cnt2, int_cnt2);
7811     }
7812     push(tmp);  // original SP
7813 
7814   } // Finished loading
7815 
7816   //========================================================
7817   // Start search
7818   //
7819 
7820   movptr(result, str1); // string addr
7821 
7822   if (int_cnt2  < 0) {  // Only for non constant substring
7823     jmpb(SCAN_TO_SUBSTR);
7824 
7825     // SP saved at sp+0
7826     // String saved at sp+1*wordSize
7827     // Substr saved at sp+2*wordSize
7828     // Substr count saved at sp+3*wordSize
7829 
7830     // Reload substr for rescan, this code
7831     // is executed only for large substrings (> 8 chars)
7832     bind(RELOAD_SUBSTR);
7833     movptr(str2, Address(rsp, 2*wordSize));
7834     movl(cnt2, Address(rsp, 3*wordSize));
7835     if (ae == StrIntrinsicNode::UL) {
7836       pmovzxbw(vec, Address(str2, 0));
7837     } else {
7838       movdqu(vec, Address(str2, 0));
7839     }
7840     // We came here after the beginning of the substring was
7841     // matched but the rest of it was not so we need to search
7842     // again. Start from the next element after the previous match.
7843     subptr(str1, result); // Restore counter
7844     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7845       shrl(str1, 1);
7846     }
7847     addl(cnt1, str1);
7848     decrementl(cnt1);   // Shift to next element
7849     cmpl(cnt1, cnt2);
7850     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7851 
7852     addptr(result, (1<<scale1));
7853   } // non constant
7854 
7855   // Scan string for start of substr in 16-byte vectors
7856   bind(SCAN_TO_SUBSTR);
7857   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7858   pcmpestri(vec, Address(result, 0), mode);
7859   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7860   subl(cnt1, stride);
7861   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7862   cmpl(cnt1, cnt2);
7863   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7864   addptr(result, 16);
7865 
7866   bind(ADJUST_STR);
7867   cmpl(cnt1, stride); // Do not read beyond string
7868   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7869   // Back-up string to avoid reading beyond string.
7870   lea(result, Address(result, cnt1, scale1, -16));
7871   movl(cnt1, stride);
7872   jmpb(SCAN_TO_SUBSTR);
7873 
7874   // Found a potential substr
7875   bind(FOUND_CANDIDATE);
7876   // After pcmpestri tmp(rcx) contains matched element index
7877 
7878   // Make sure string is still long enough
7879   subl(cnt1, tmp);
7880   cmpl(cnt1, cnt2);
7881   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7882   // Left less then substring.
7883 
7884   bind(RET_NOT_FOUND);
7885   movl(result, -1);
7886   jmpb(CLEANUP);
7887 
7888   bind(FOUND_SUBSTR);
7889   // Compute start addr of substr
7890   lea(result, Address(result, tmp, scale1));
7891   if (int_cnt2 > 0) { // Constant substring
7892     // Repeat search for small substring (< 8 chars)
7893     // from new point without reloading substring.
7894     // Have to check that we don't read beyond string.
7895     cmpl(tmp, stride-int_cnt2);
7896     jccb(Assembler::greater, ADJUST_STR);
7897     // Fall through if matched whole substring.
7898   } else { // non constant
7899     assert(int_cnt2 == -1, "should be != 0");
7900 
7901     addl(tmp, cnt2);
7902     // Found result if we matched whole substring.
7903     cmpl(tmp, stride);
7904     jccb(Assembler::lessEqual, RET_FOUND);
7905 
7906     // Repeat search for small substring (<= 8 chars)
7907     // from new point 'str1' without reloading substring.
7908     cmpl(cnt2, stride);
7909     // Have to check that we don't read beyond string.
7910     jccb(Assembler::lessEqual, ADJUST_STR);
7911 
7912     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7913     // Compare the rest of substring (> 8 chars).
7914     movptr(str1, result);
7915 
7916     cmpl(tmp, cnt2);
7917     // First 8 chars are already matched.
7918     jccb(Assembler::equal, CHECK_NEXT);
7919 
7920     bind(SCAN_SUBSTR);
7921     pcmpestri(vec, Address(str1, 0), mode);
7922     // Need to reload strings pointers if not matched whole vector
7923     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7924 
7925     bind(CHECK_NEXT);
7926     subl(cnt2, stride);
7927     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7928     addptr(str1, 16);
7929     if (ae == StrIntrinsicNode::UL) {
7930       addptr(str2, 8);
7931     } else {
7932       addptr(str2, 16);
7933     }
7934     subl(cnt1, stride);
7935     cmpl(cnt2, stride); // Do not read beyond substring
7936     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7937     // Back-up strings to avoid reading beyond substring.
7938 
7939     if (ae == StrIntrinsicNode::UL) {
7940       lea(str2, Address(str2, cnt2, scale2, -8));
7941       lea(str1, Address(str1, cnt2, scale1, -16));
7942     } else {
7943       lea(str2, Address(str2, cnt2, scale2, -16));
7944       lea(str1, Address(str1, cnt2, scale1, -16));
7945     }
7946     subl(cnt1, cnt2);
7947     movl(cnt2, stride);
7948     addl(cnt1, stride);
7949     bind(CONT_SCAN_SUBSTR);
7950     if (ae == StrIntrinsicNode::UL) {
7951       pmovzxbw(vec, Address(str2, 0));
7952     } else {
7953       movdqu(vec, Address(str2, 0));
7954     }
7955     jmp(SCAN_SUBSTR);
7956 
7957     bind(RET_FOUND_LONG);
7958     movptr(str1, Address(rsp, wordSize));
7959   } // non constant
7960 
7961   bind(RET_FOUND);
7962   // Compute substr offset
7963   subptr(result, str1);
7964   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7965     shrl(result, 1); // index
7966   }
7967   bind(CLEANUP);
7968   pop(rsp); // restore SP
7969 
7970 } // string_indexof
7971 
7972 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7973                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7974   ShortBranchVerifier sbv(this);
7975   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7976 
7977   int stride = 8;
7978 
7979   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7980         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7981         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7982         FOUND_SEQ_CHAR, DONE_LABEL;
7983 
7984   movptr(result, str1);
7985   if (UseAVX >= 2) {
7986     cmpl(cnt1, stride);
7987     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7988     cmpl(cnt1, 2*stride);
7989     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7990     movdl(vec1, ch);
7991     vpbroadcastw(vec1, vec1);
7992     vpxor(vec2, vec2);
7993     movl(tmp, cnt1);
7994     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7995     andl(cnt1,0x0000000F);  //tail count (in chars)
7996 
7997     bind(SCAN_TO_16_CHAR_LOOP);
7998     vmovdqu(vec3, Address(result, 0));
7999     vpcmpeqw(vec3, vec3, vec1, 1);
8000     vptest(vec2, vec3);
8001     jcc(Assembler::carryClear, FOUND_CHAR);
8002     addptr(result, 32);
8003     subl(tmp, 2*stride);
8004     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
8005     jmp(SCAN_TO_8_CHAR);
8006     bind(SCAN_TO_8_CHAR_INIT);
8007     movdl(vec1, ch);
8008     pshuflw(vec1, vec1, 0x00);
8009     pshufd(vec1, vec1, 0);
8010     pxor(vec2, vec2);
8011   }
8012   bind(SCAN_TO_8_CHAR);
8013   cmpl(cnt1, stride);
8014   if (UseAVX >= 2) {
8015     jcc(Assembler::less, SCAN_TO_CHAR);
8016   } else {
8017     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8018     movdl(vec1, ch);
8019     pshuflw(vec1, vec1, 0x00);
8020     pshufd(vec1, vec1, 0);
8021     pxor(vec2, vec2);
8022   }
8023   movl(tmp, cnt1);
8024   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
8025   andl(cnt1,0x00000007);  //tail count (in chars)
8026 
8027   bind(SCAN_TO_8_CHAR_LOOP);
8028   movdqu(vec3, Address(result, 0));
8029   pcmpeqw(vec3, vec1);
8030   ptest(vec2, vec3);
8031   jcc(Assembler::carryClear, FOUND_CHAR);
8032   addptr(result, 16);
8033   subl(tmp, stride);
8034   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
8035   bind(SCAN_TO_CHAR);
8036   testl(cnt1, cnt1);
8037   jcc(Assembler::zero, RET_NOT_FOUND);
8038   bind(SCAN_TO_CHAR_LOOP);
8039   load_unsigned_short(tmp, Address(result, 0));
8040   cmpl(ch, tmp);
8041   jccb(Assembler::equal, FOUND_SEQ_CHAR);
8042   addptr(result, 2);
8043   subl(cnt1, 1);
8044   jccb(Assembler::zero, RET_NOT_FOUND);
8045   jmp(SCAN_TO_CHAR_LOOP);
8046 
8047   bind(RET_NOT_FOUND);
8048   movl(result, -1);
8049   jmpb(DONE_LABEL);
8050 
8051   bind(FOUND_CHAR);
8052   if (UseAVX >= 2) {
8053     vpmovmskb(tmp, vec3);
8054   } else {
8055     pmovmskb(tmp, vec3);
8056   }
8057   bsfl(ch, tmp);
8058   addl(result, ch);
8059 
8060   bind(FOUND_SEQ_CHAR);
8061   subptr(result, str1);
8062   shrl(result, 1);
8063 
8064   bind(DONE_LABEL);
8065 } // string_indexof_char
8066 
8067 // helper function for string_compare
8068 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
8069                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
8070                                         Address::ScaleFactor scale2, Register index, int ae) {
8071   if (ae == StrIntrinsicNode::LL) {
8072     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
8073     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
8074   } else if (ae == StrIntrinsicNode::UU) {
8075     load_unsigned_short(elem1, Address(str1, index, scale, 0));
8076     load_unsigned_short(elem2, Address(str2, index, scale, 0));
8077   } else {
8078     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
8079     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
8080   }
8081 }
8082 
8083 // Compare strings, used for char[] and byte[].
8084 void MacroAssembler::string_compare(Register str1, Register str2,
8085                                     Register cnt1, Register cnt2, Register result,
8086                                     XMMRegister vec1, int ae) {
8087   ShortBranchVerifier sbv(this);
8088   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
8089   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
8090   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8091   int stride2x2 = 0x40;
8092   Address::ScaleFactor scale = Address::no_scale;
8093   Address::ScaleFactor scale1 = Address::no_scale;
8094   Address::ScaleFactor scale2 = Address::no_scale;
8095 
8096   if (ae != StrIntrinsicNode::LL) {
8097     stride2x2 = 0x20;
8098   }
8099 
8100   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8101     shrl(cnt2, 1);
8102   }
8103   // Compute the minimum of the string lengths and the
8104   // difference of the string lengths (stack).
8105   // Do the conditional move stuff
8106   movl(result, cnt1);
8107   subl(cnt1, cnt2);
8108   push(cnt1);
8109   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
8110 
8111   // Is the minimum length zero?
8112   testl(cnt2, cnt2);
8113   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8114   if (ae == StrIntrinsicNode::LL) {
8115     // Load first bytes
8116     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
8117     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
8118   } else if (ae == StrIntrinsicNode::UU) {
8119     // Load first characters
8120     load_unsigned_short(result, Address(str1, 0));
8121     load_unsigned_short(cnt1, Address(str2, 0));
8122   } else {
8123     load_unsigned_byte(result, Address(str1, 0));
8124     load_unsigned_short(cnt1, Address(str2, 0));
8125   }
8126   subl(result, cnt1);
8127   jcc(Assembler::notZero,  POP_LABEL);
8128 
8129   if (ae == StrIntrinsicNode::UU) {
8130     // Divide length by 2 to get number of chars
8131     shrl(cnt2, 1);
8132   }
8133   cmpl(cnt2, 1);
8134   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8135 
8136   // Check if the strings start at the same location and setup scale and stride
8137   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8138     cmpptr(str1, str2);
8139     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8140     if (ae == StrIntrinsicNode::LL) {
8141       scale = Address::times_1;
8142       stride = 16;
8143     } else {
8144       scale = Address::times_2;
8145       stride = 8;
8146     }
8147   } else {
8148     scale1 = Address::times_1;
8149     scale2 = Address::times_2;
8150     // scale not used
8151     stride = 8;
8152   }
8153 
8154   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8155     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8156     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8157     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
8158     Label COMPARE_TAIL_LONG;
8159     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
8160 
8161     int pcmpmask = 0x19;
8162     if (ae == StrIntrinsicNode::LL) {
8163       pcmpmask &= ~0x01;
8164     }
8165 
8166     // Setup to compare 16-chars (32-bytes) vectors,
8167     // start from first character again because it has aligned address.
8168     if (ae == StrIntrinsicNode::LL) {
8169       stride2 = 32;
8170     } else {
8171       stride2 = 16;
8172     }
8173     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8174       adr_stride = stride << scale;
8175     } else {
8176       adr_stride1 = 8;  //stride << scale1;
8177       adr_stride2 = 16; //stride << scale2;
8178     }
8179 
8180     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8181     // rax and rdx are used by pcmpestri as elements counters
8182     movl(result, cnt2);
8183     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8184     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8185 
8186     // fast path : compare first 2 8-char vectors.
8187     bind(COMPARE_16_CHARS);
8188     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8189       movdqu(vec1, Address(str1, 0));
8190     } else {
8191       pmovzxbw(vec1, Address(str1, 0));
8192     }
8193     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8194     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8195 
8196     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8197       movdqu(vec1, Address(str1, adr_stride));
8198       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8199     } else {
8200       pmovzxbw(vec1, Address(str1, adr_stride1));
8201       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8202     }
8203     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8204     addl(cnt1, stride);
8205 
8206     // Compare the characters at index in cnt1
8207     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8208     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8209     subl(result, cnt2);
8210     jmp(POP_LABEL);
8211 
8212     // Setup the registers to start vector comparison loop
8213     bind(COMPARE_WIDE_VECTORS);
8214     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8215       lea(str1, Address(str1, result, scale));
8216       lea(str2, Address(str2, result, scale));
8217     } else {
8218       lea(str1, Address(str1, result, scale1));
8219       lea(str2, Address(str2, result, scale2));
8220     }
8221     subl(result, stride2);
8222     subl(cnt2, stride2);
8223     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8224     negptr(result);
8225 
8226     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8227     bind(COMPARE_WIDE_VECTORS_LOOP);
8228 
8229 #ifdef _LP64
8230     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8231       cmpl(cnt2, stride2x2);
8232       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8233       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8234       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8235 
8236       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8237       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8238         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8239         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8240       } else {
8241         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8242         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8243       }
8244       kortestql(k7, k7);
8245       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8246       addptr(result, stride2x2);  // update since we already compared at this addr
8247       subl(cnt2, stride2x2);      // and sub the size too
8248       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8249 
8250       vpxor(vec1, vec1);
8251       jmpb(COMPARE_WIDE_TAIL);
8252     }//if (VM_Version::supports_avx512vlbw())
8253 #endif // _LP64
8254 
8255 
8256     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8257     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8258       vmovdqu(vec1, Address(str1, result, scale));
8259       vpxor(vec1, Address(str2, result, scale));
8260     } else {
8261       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8262       vpxor(vec1, Address(str2, result, scale2));
8263     }
8264     vptest(vec1, vec1);
8265     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8266     addptr(result, stride2);
8267     subl(cnt2, stride2);
8268     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8269     // clean upper bits of YMM registers
8270     vpxor(vec1, vec1);
8271 
8272     // compare wide vectors tail
8273     bind(COMPARE_WIDE_TAIL);
8274     testptr(result, result);
8275     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8276 
8277     movl(result, stride2);
8278     movl(cnt2, result);
8279     negptr(result);
8280     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8281 
8282     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8283     bind(VECTOR_NOT_EQUAL);
8284     // clean upper bits of YMM registers
8285     vpxor(vec1, vec1);
8286     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8287       lea(str1, Address(str1, result, scale));
8288       lea(str2, Address(str2, result, scale));
8289     } else {
8290       lea(str1, Address(str1, result, scale1));
8291       lea(str2, Address(str2, result, scale2));
8292     }
8293     jmp(COMPARE_16_CHARS);
8294 
8295     // Compare tail chars, length between 1 to 15 chars
8296     bind(COMPARE_TAIL_LONG);
8297     movl(cnt2, result);
8298     cmpl(cnt2, stride);
8299     jcc(Assembler::less, COMPARE_SMALL_STR);
8300 
8301     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8302       movdqu(vec1, Address(str1, 0));
8303     } else {
8304       pmovzxbw(vec1, Address(str1, 0));
8305     }
8306     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8307     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8308     subptr(cnt2, stride);
8309     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8310     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8311       lea(str1, Address(str1, result, scale));
8312       lea(str2, Address(str2, result, scale));
8313     } else {
8314       lea(str1, Address(str1, result, scale1));
8315       lea(str2, Address(str2, result, scale2));
8316     }
8317     negptr(cnt2);
8318     jmpb(WHILE_HEAD_LABEL);
8319 
8320     bind(COMPARE_SMALL_STR);
8321   } else if (UseSSE42Intrinsics) {
8322     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8323     int pcmpmask = 0x19;
8324     // Setup to compare 8-char (16-byte) vectors,
8325     // start from first character again because it has aligned address.
8326     movl(result, cnt2);
8327     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8328     if (ae == StrIntrinsicNode::LL) {
8329       pcmpmask &= ~0x01;
8330     }
8331     jcc(Assembler::zero, COMPARE_TAIL);
8332     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8333       lea(str1, Address(str1, result, scale));
8334       lea(str2, Address(str2, result, scale));
8335     } else {
8336       lea(str1, Address(str1, result, scale1));
8337       lea(str2, Address(str2, result, scale2));
8338     }
8339     negptr(result);
8340 
8341     // pcmpestri
8342     //   inputs:
8343     //     vec1- substring
8344     //     rax - negative string length (elements count)
8345     //     mem - scanned string
8346     //     rdx - string length (elements count)
8347     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8348     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8349     //   outputs:
8350     //     rcx - first mismatched element index
8351     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8352 
8353     bind(COMPARE_WIDE_VECTORS);
8354     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8355       movdqu(vec1, Address(str1, result, scale));
8356       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8357     } else {
8358       pmovzxbw(vec1, Address(str1, result, scale1));
8359       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8360     }
8361     // After pcmpestri cnt1(rcx) contains mismatched element index
8362 
8363     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8364     addptr(result, stride);
8365     subptr(cnt2, stride);
8366     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8367 
8368     // compare wide vectors tail
8369     testptr(result, result);
8370     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8371 
8372     movl(cnt2, stride);
8373     movl(result, stride);
8374     negptr(result);
8375     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8376       movdqu(vec1, Address(str1, result, scale));
8377       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8378     } else {
8379       pmovzxbw(vec1, Address(str1, result, scale1));
8380       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8381     }
8382     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8383 
8384     // Mismatched characters in the vectors
8385     bind(VECTOR_NOT_EQUAL);
8386     addptr(cnt1, result);
8387     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8388     subl(result, cnt2);
8389     jmpb(POP_LABEL);
8390 
8391     bind(COMPARE_TAIL); // limit is zero
8392     movl(cnt2, result);
8393     // Fallthru to tail compare
8394   }
8395   // Shift str2 and str1 to the end of the arrays, negate min
8396   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8397     lea(str1, Address(str1, cnt2, scale));
8398     lea(str2, Address(str2, cnt2, scale));
8399   } else {
8400     lea(str1, Address(str1, cnt2, scale1));
8401     lea(str2, Address(str2, cnt2, scale2));
8402   }
8403   decrementl(cnt2);  // first character was compared already
8404   negptr(cnt2);
8405 
8406   // Compare the rest of the elements
8407   bind(WHILE_HEAD_LABEL);
8408   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8409   subl(result, cnt1);
8410   jccb(Assembler::notZero, POP_LABEL);
8411   increment(cnt2);
8412   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8413 
8414   // Strings are equal up to min length.  Return the length difference.
8415   bind(LENGTH_DIFF_LABEL);
8416   pop(result);
8417   if (ae == StrIntrinsicNode::UU) {
8418     // Divide diff by 2 to get number of chars
8419     sarl(result, 1);
8420   }
8421   jmpb(DONE_LABEL);
8422 
8423 #ifdef _LP64
8424   if (VM_Version::supports_avx512vlbw()) {
8425 
8426     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8427 
8428     kmovql(cnt1, k7);
8429     notq(cnt1);
8430     bsfq(cnt2, cnt1);
8431     if (ae != StrIntrinsicNode::LL) {
8432       // Divide diff by 2 to get number of chars
8433       sarl(cnt2, 1);
8434     }
8435     addq(result, cnt2);
8436     if (ae == StrIntrinsicNode::LL) {
8437       load_unsigned_byte(cnt1, Address(str2, result));
8438       load_unsigned_byte(result, Address(str1, result));
8439     } else if (ae == StrIntrinsicNode::UU) {
8440       load_unsigned_short(cnt1, Address(str2, result, scale));
8441       load_unsigned_short(result, Address(str1, result, scale));
8442     } else {
8443       load_unsigned_short(cnt1, Address(str2, result, scale2));
8444       load_unsigned_byte(result, Address(str1, result, scale1));
8445     }
8446     subl(result, cnt1);
8447     jmpb(POP_LABEL);
8448   }//if (VM_Version::supports_avx512vlbw())
8449 #endif // _LP64
8450 
8451   // Discard the stored length difference
8452   bind(POP_LABEL);
8453   pop(cnt1);
8454 
8455   // That's it
8456   bind(DONE_LABEL);
8457   if(ae == StrIntrinsicNode::UL) {
8458     negl(result);
8459   }
8460 
8461 }
8462 
8463 // Search for Non-ASCII character (Negative byte value) in a byte array,
8464 // return true if it has any and false otherwise.
8465 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8466 //   @HotSpotIntrinsicCandidate
8467 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8468 //     for (int i = off; i < off + len; i++) {
8469 //       if (ba[i] < 0) {
8470 //         return true;
8471 //       }
8472 //     }
8473 //     return false;
8474 //   }
8475 void MacroAssembler::has_negatives(Register ary1, Register len,
8476   Register result, Register tmp1,
8477   XMMRegister vec1, XMMRegister vec2) {
8478   // rsi: byte array
8479   // rcx: len
8480   // rax: result
8481   ShortBranchVerifier sbv(this);
8482   assert_different_registers(ary1, len, result, tmp1);
8483   assert_different_registers(vec1, vec2);
8484   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8485 
8486   // len == 0
8487   testl(len, len);
8488   jcc(Assembler::zero, FALSE_LABEL);
8489 
8490   if ((UseAVX > 2) && // AVX512
8491     VM_Version::supports_avx512vlbw() &&
8492     VM_Version::supports_bmi2()) {
8493 
8494     set_vector_masking();  // opening of the stub context for programming mask registers
8495 
8496     Label test_64_loop, test_tail;
8497     Register tmp3_aliased = len;
8498 
8499     movl(tmp1, len);
8500     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8501 
8502     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8503     andl(len, ~(64 - 1));    // vector count (in chars)
8504     jccb(Assembler::zero, test_tail);
8505 
8506     lea(ary1, Address(ary1, len, Address::times_1));
8507     negptr(len);
8508 
8509     bind(test_64_loop);
8510     // Check whether our 64 elements of size byte contain negatives
8511     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8512     kortestql(k2, k2);
8513     jcc(Assembler::notZero, TRUE_LABEL);
8514 
8515     addptr(len, 64);
8516     jccb(Assembler::notZero, test_64_loop);
8517 
8518 
8519     bind(test_tail);
8520     // bail out when there is nothing to be done
8521     testl(tmp1, -1);
8522     jcc(Assembler::zero, FALSE_LABEL);
8523 
8524     // Save k1
8525     kmovql(k3, k1);
8526 
8527     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8528 #ifdef _LP64
8529     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8530     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8531     notq(tmp3_aliased);
8532     kmovql(k1, tmp3_aliased);
8533 #else
8534     Label k_init;
8535     jmp(k_init);
8536 
8537     // We could not read 64-bits from a general purpose register thus we move
8538     // data required to compose 64 1's to the instruction stream
8539     // We emit 64 byte wide series of elements from 0..63 which later on would
8540     // be used as a compare targets with tail count contained in tmp1 register.
8541     // Result would be a k1 register having tmp1 consecutive number or 1
8542     // counting from least significant bit.
8543     address tmp = pc();
8544     emit_int64(0x0706050403020100);
8545     emit_int64(0x0F0E0D0C0B0A0908);
8546     emit_int64(0x1716151413121110);
8547     emit_int64(0x1F1E1D1C1B1A1918);
8548     emit_int64(0x2726252423222120);
8549     emit_int64(0x2F2E2D2C2B2A2928);
8550     emit_int64(0x3736353433323130);
8551     emit_int64(0x3F3E3D3C3B3A3938);
8552 
8553     bind(k_init);
8554     lea(len, InternalAddress(tmp));
8555     // create mask to test for negative byte inside a vector
8556     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8557     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8558 
8559 #endif
8560     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8561     ktestq(k2, k1);
8562     // Restore k1
8563     kmovql(k1, k3);
8564     jcc(Assembler::notZero, TRUE_LABEL);
8565 
8566     jmp(FALSE_LABEL);
8567 
8568     clear_vector_masking();   // closing of the stub context for programming mask registers
8569   } else {
8570     movl(result, len); // copy
8571 
8572     if (UseAVX == 2 && UseSSE >= 2) {
8573       // With AVX2, use 32-byte vector compare
8574       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8575 
8576       // Compare 32-byte vectors
8577       andl(result, 0x0000001f);  //   tail count (in bytes)
8578       andl(len, 0xffffffe0);   // vector count (in bytes)
8579       jccb(Assembler::zero, COMPARE_TAIL);
8580 
8581       lea(ary1, Address(ary1, len, Address::times_1));
8582       negptr(len);
8583 
8584       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8585       movdl(vec2, tmp1);
8586       vpbroadcastd(vec2, vec2);
8587 
8588       bind(COMPARE_WIDE_VECTORS);
8589       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8590       vptest(vec1, vec2);
8591       jccb(Assembler::notZero, TRUE_LABEL);
8592       addptr(len, 32);
8593       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8594 
8595       testl(result, result);
8596       jccb(Assembler::zero, FALSE_LABEL);
8597 
8598       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8599       vptest(vec1, vec2);
8600       jccb(Assembler::notZero, TRUE_LABEL);
8601       jmpb(FALSE_LABEL);
8602 
8603       bind(COMPARE_TAIL); // len is zero
8604       movl(len, result);
8605       // Fallthru to tail compare
8606     } else if (UseSSE42Intrinsics) {
8607       // With SSE4.2, use double quad vector compare
8608       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8609 
8610       // Compare 16-byte vectors
8611       andl(result, 0x0000000f);  //   tail count (in bytes)
8612       andl(len, 0xfffffff0);   // vector count (in bytes)
8613       jccb(Assembler::zero, COMPARE_TAIL);
8614 
8615       lea(ary1, Address(ary1, len, Address::times_1));
8616       negptr(len);
8617 
8618       movl(tmp1, 0x80808080);
8619       movdl(vec2, tmp1);
8620       pshufd(vec2, vec2, 0);
8621 
8622       bind(COMPARE_WIDE_VECTORS);
8623       movdqu(vec1, Address(ary1, len, Address::times_1));
8624       ptest(vec1, vec2);
8625       jccb(Assembler::notZero, TRUE_LABEL);
8626       addptr(len, 16);
8627       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8628 
8629       testl(result, result);
8630       jccb(Assembler::zero, FALSE_LABEL);
8631 
8632       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8633       ptest(vec1, vec2);
8634       jccb(Assembler::notZero, TRUE_LABEL);
8635       jmpb(FALSE_LABEL);
8636 
8637       bind(COMPARE_TAIL); // len is zero
8638       movl(len, result);
8639       // Fallthru to tail compare
8640     }
8641   }
8642   // Compare 4-byte vectors
8643   andl(len, 0xfffffffc); // vector count (in bytes)
8644   jccb(Assembler::zero, COMPARE_CHAR);
8645 
8646   lea(ary1, Address(ary1, len, Address::times_1));
8647   negptr(len);
8648 
8649   bind(COMPARE_VECTORS);
8650   movl(tmp1, Address(ary1, len, Address::times_1));
8651   andl(tmp1, 0x80808080);
8652   jccb(Assembler::notZero, TRUE_LABEL);
8653   addptr(len, 4);
8654   jcc(Assembler::notZero, COMPARE_VECTORS);
8655 
8656   // Compare trailing char (final 2 bytes), if any
8657   bind(COMPARE_CHAR);
8658   testl(result, 0x2);   // tail  char
8659   jccb(Assembler::zero, COMPARE_BYTE);
8660   load_unsigned_short(tmp1, Address(ary1, 0));
8661   andl(tmp1, 0x00008080);
8662   jccb(Assembler::notZero, TRUE_LABEL);
8663   subptr(result, 2);
8664   lea(ary1, Address(ary1, 2));
8665 
8666   bind(COMPARE_BYTE);
8667   testl(result, 0x1);   // tail  byte
8668   jccb(Assembler::zero, FALSE_LABEL);
8669   load_unsigned_byte(tmp1, Address(ary1, 0));
8670   andl(tmp1, 0x00000080);
8671   jccb(Assembler::notEqual, TRUE_LABEL);
8672   jmpb(FALSE_LABEL);
8673 
8674   bind(TRUE_LABEL);
8675   movl(result, 1);   // return true
8676   jmpb(DONE);
8677 
8678   bind(FALSE_LABEL);
8679   xorl(result, result); // return false
8680 
8681   // That's it
8682   bind(DONE);
8683   if (UseAVX >= 2 && UseSSE >= 2) {
8684     // clean upper bits of YMM registers
8685     vpxor(vec1, vec1);
8686     vpxor(vec2, vec2);
8687   }
8688 }
8689 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8690 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8691                                    Register limit, Register result, Register chr,
8692                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8693   ShortBranchVerifier sbv(this);
8694   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8695 
8696   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8697   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8698 
8699   if (is_array_equ) {
8700     // Check the input args
8701     cmpptr(ary1, ary2);
8702     oopDesc::bs()->asm_acmp_barrier(this, ary1, ary2);
8703     jcc(Assembler::equal, TRUE_LABEL);
8704 
8705     // Need additional checks for arrays_equals.
8706     testptr(ary1, ary1);
8707     jcc(Assembler::zero, FALSE_LABEL);
8708     testptr(ary2, ary2);
8709     jcc(Assembler::zero, FALSE_LABEL);
8710 
8711     // Check the lengths
8712     movl(limit, Address(ary1, length_offset));
8713     cmpl(limit, Address(ary2, length_offset));
8714     jcc(Assembler::notEqual, FALSE_LABEL);
8715   }
8716 
8717   // count == 0
8718   testl(limit, limit);
8719   jcc(Assembler::zero, TRUE_LABEL);
8720 
8721   if (is_array_equ) {
8722     // Load array address
8723     lea(ary1, Address(ary1, base_offset));
8724     lea(ary2, Address(ary2, base_offset));
8725   }
8726 
8727   if (is_array_equ && is_char) {
8728     // arrays_equals when used for char[].
8729     shll(limit, 1);      // byte count != 0
8730   }
8731   movl(result, limit); // copy
8732 
8733   if (UseAVX >= 2) {
8734     // With AVX2, use 32-byte vector compare
8735     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8736 
8737     // Compare 32-byte vectors
8738     andl(result, 0x0000001f);  //   tail count (in bytes)
8739     andl(limit, 0xffffffe0);   // vector count (in bytes)
8740     jcc(Assembler::zero, COMPARE_TAIL);
8741 
8742     lea(ary1, Address(ary1, limit, Address::times_1));
8743     lea(ary2, Address(ary2, limit, Address::times_1));
8744     negptr(limit);
8745 
8746     bind(COMPARE_WIDE_VECTORS);
8747 
8748 #ifdef _LP64
8749     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8750       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8751 
8752       cmpl(limit, -64);
8753       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8754 
8755       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8756 
8757       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8758       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8759       kortestql(k7, k7);
8760       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8761       addptr(limit, 64);  // update since we already compared at this addr
8762       cmpl(limit, -64);
8763       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8764 
8765       // At this point we may still need to compare -limit+result bytes.
8766       // We could execute the next two instruction and just continue via non-wide path:
8767       //  cmpl(limit, 0);
8768       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8769       // But since we stopped at the points ary{1,2}+limit which are
8770       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8771       // (|limit| <= 32 and result < 32),
8772       // we may just compare the last 64 bytes.
8773       //
8774       addptr(result, -64);   // it is safe, bc we just came from this area
8775       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8776       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8777       kortestql(k7, k7);
8778       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8779 
8780       jmp(TRUE_LABEL);
8781 
8782       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8783 
8784     }//if (VM_Version::supports_avx512vlbw())
8785 #endif //_LP64
8786 
8787     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8788     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8789     vpxor(vec1, vec2);
8790 
8791     vptest(vec1, vec1);
8792     jcc(Assembler::notZero, FALSE_LABEL);
8793     addptr(limit, 32);
8794     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8795 
8796     testl(result, result);
8797     jcc(Assembler::zero, TRUE_LABEL);
8798 
8799     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8800     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8801     vpxor(vec1, vec2);
8802 
8803     vptest(vec1, vec1);
8804     jccb(Assembler::notZero, FALSE_LABEL);
8805     jmpb(TRUE_LABEL);
8806 
8807     bind(COMPARE_TAIL); // limit is zero
8808     movl(limit, result);
8809     // Fallthru to tail compare
8810   } else if (UseSSE42Intrinsics) {
8811     // With SSE4.2, use double quad vector compare
8812     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8813 
8814     // Compare 16-byte vectors
8815     andl(result, 0x0000000f);  //   tail count (in bytes)
8816     andl(limit, 0xfffffff0);   // vector count (in bytes)
8817     jcc(Assembler::zero, COMPARE_TAIL);
8818 
8819     lea(ary1, Address(ary1, limit, Address::times_1));
8820     lea(ary2, Address(ary2, limit, Address::times_1));
8821     negptr(limit);
8822 
8823     bind(COMPARE_WIDE_VECTORS);
8824     movdqu(vec1, Address(ary1, limit, Address::times_1));
8825     movdqu(vec2, Address(ary2, limit, Address::times_1));
8826     pxor(vec1, vec2);
8827 
8828     ptest(vec1, vec1);
8829     jcc(Assembler::notZero, FALSE_LABEL);
8830     addptr(limit, 16);
8831     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8832 
8833     testl(result, result);
8834     jcc(Assembler::zero, TRUE_LABEL);
8835 
8836     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8837     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8838     pxor(vec1, vec2);
8839 
8840     ptest(vec1, vec1);
8841     jccb(Assembler::notZero, FALSE_LABEL);
8842     jmpb(TRUE_LABEL);
8843 
8844     bind(COMPARE_TAIL); // limit is zero
8845     movl(limit, result);
8846     // Fallthru to tail compare
8847   }
8848 
8849   // Compare 4-byte vectors
8850   andl(limit, 0xfffffffc); // vector count (in bytes)
8851   jccb(Assembler::zero, COMPARE_CHAR);
8852 
8853   lea(ary1, Address(ary1, limit, Address::times_1));
8854   lea(ary2, Address(ary2, limit, Address::times_1));
8855   negptr(limit);
8856 
8857   bind(COMPARE_VECTORS);
8858   movl(chr, Address(ary1, limit, Address::times_1));
8859   cmpl(chr, Address(ary2, limit, Address::times_1));
8860   jccb(Assembler::notEqual, FALSE_LABEL);
8861   addptr(limit, 4);
8862   jcc(Assembler::notZero, COMPARE_VECTORS);
8863 
8864   // Compare trailing char (final 2 bytes), if any
8865   bind(COMPARE_CHAR);
8866   testl(result, 0x2);   // tail  char
8867   jccb(Assembler::zero, COMPARE_BYTE);
8868   load_unsigned_short(chr, Address(ary1, 0));
8869   load_unsigned_short(limit, Address(ary2, 0));
8870   cmpl(chr, limit);
8871   jccb(Assembler::notEqual, FALSE_LABEL);
8872 
8873   if (is_array_equ && is_char) {
8874     bind(COMPARE_BYTE);
8875   } else {
8876     lea(ary1, Address(ary1, 2));
8877     lea(ary2, Address(ary2, 2));
8878 
8879     bind(COMPARE_BYTE);
8880     testl(result, 0x1);   // tail  byte
8881     jccb(Assembler::zero, TRUE_LABEL);
8882     load_unsigned_byte(chr, Address(ary1, 0));
8883     load_unsigned_byte(limit, Address(ary2, 0));
8884     cmpl(chr, limit);
8885     jccb(Assembler::notEqual, FALSE_LABEL);
8886   }
8887   bind(TRUE_LABEL);
8888   movl(result, 1);   // return true
8889   jmpb(DONE);
8890 
8891   bind(FALSE_LABEL);
8892   xorl(result, result); // return false
8893 
8894   // That's it
8895   bind(DONE);
8896   if (UseAVX >= 2) {
8897     // clean upper bits of YMM registers
8898     vpxor(vec1, vec1);
8899     vpxor(vec2, vec2);
8900   }
8901 }
8902 
8903 #endif
8904 
8905 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8906                                    Register to, Register value, Register count,
8907                                    Register rtmp, XMMRegister xtmp) {
8908   ShortBranchVerifier sbv(this);
8909   assert_different_registers(to, value, count, rtmp);
8910   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8911   Label L_fill_2_bytes, L_fill_4_bytes;
8912 
8913   int shift = -1;
8914   switch (t) {
8915     case T_BYTE:
8916       shift = 2;
8917       break;
8918     case T_SHORT:
8919       shift = 1;
8920       break;
8921     case T_INT:
8922       shift = 0;
8923       break;
8924     default: ShouldNotReachHere();
8925   }
8926 
8927   if (t == T_BYTE) {
8928     andl(value, 0xff);
8929     movl(rtmp, value);
8930     shll(rtmp, 8);
8931     orl(value, rtmp);
8932   }
8933   if (t == T_SHORT) {
8934     andl(value, 0xffff);
8935   }
8936   if (t == T_BYTE || t == T_SHORT) {
8937     movl(rtmp, value);
8938     shll(rtmp, 16);
8939     orl(value, rtmp);
8940   }
8941 
8942   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8943   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8944   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8945     // align source address at 4 bytes address boundary
8946     if (t == T_BYTE) {
8947       // One byte misalignment happens only for byte arrays
8948       testptr(to, 1);
8949       jccb(Assembler::zero, L_skip_align1);
8950       movb(Address(to, 0), value);
8951       increment(to);
8952       decrement(count);
8953       BIND(L_skip_align1);
8954     }
8955     // Two bytes misalignment happens only for byte and short (char) arrays
8956     testptr(to, 2);
8957     jccb(Assembler::zero, L_skip_align2);
8958     movw(Address(to, 0), value);
8959     addptr(to, 2);
8960     subl(count, 1<<(shift-1));
8961     BIND(L_skip_align2);
8962   }
8963   if (UseSSE < 2) {
8964     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8965     // Fill 32-byte chunks
8966     subl(count, 8 << shift);
8967     jcc(Assembler::less, L_check_fill_8_bytes);
8968     align(16);
8969 
8970     BIND(L_fill_32_bytes_loop);
8971 
8972     for (int i = 0; i < 32; i += 4) {
8973       movl(Address(to, i), value);
8974     }
8975 
8976     addptr(to, 32);
8977     subl(count, 8 << shift);
8978     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8979     BIND(L_check_fill_8_bytes);
8980     addl(count, 8 << shift);
8981     jccb(Assembler::zero, L_exit);
8982     jmpb(L_fill_8_bytes);
8983 
8984     //
8985     // length is too short, just fill qwords
8986     //
8987     BIND(L_fill_8_bytes_loop);
8988     movl(Address(to, 0), value);
8989     movl(Address(to, 4), value);
8990     addptr(to, 8);
8991     BIND(L_fill_8_bytes);
8992     subl(count, 1 << (shift + 1));
8993     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8994     // fall through to fill 4 bytes
8995   } else {
8996     Label L_fill_32_bytes;
8997     if (!UseUnalignedLoadStores) {
8998       // align to 8 bytes, we know we are 4 byte aligned to start
8999       testptr(to, 4);
9000       jccb(Assembler::zero, L_fill_32_bytes);
9001       movl(Address(to, 0), value);
9002       addptr(to, 4);
9003       subl(count, 1<<shift);
9004     }
9005     BIND(L_fill_32_bytes);
9006     {
9007       assert( UseSSE >= 2, "supported cpu only" );
9008       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9009       if (UseAVX > 2) {
9010         movl(rtmp, 0xffff);
9011         kmovwl(k1, rtmp);
9012       }
9013       movdl(xtmp, value);
9014       if (UseAVX > 2 && UseUnalignedLoadStores) {
9015         // Fill 64-byte chunks
9016         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9017         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
9018 
9019         subl(count, 16 << shift);
9020         jcc(Assembler::less, L_check_fill_32_bytes);
9021         align(16);
9022 
9023         BIND(L_fill_64_bytes_loop);
9024         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
9025         addptr(to, 64);
9026         subl(count, 16 << shift);
9027         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9028 
9029         BIND(L_check_fill_32_bytes);
9030         addl(count, 8 << shift);
9031         jccb(Assembler::less, L_check_fill_8_bytes);
9032         vmovdqu(Address(to, 0), xtmp);
9033         addptr(to, 32);
9034         subl(count, 8 << shift);
9035 
9036         BIND(L_check_fill_8_bytes);
9037       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
9038         // Fill 64-byte chunks
9039         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9040         vpbroadcastd(xtmp, xtmp);
9041 
9042         subl(count, 16 << shift);
9043         jcc(Assembler::less, L_check_fill_32_bytes);
9044         align(16);
9045 
9046         BIND(L_fill_64_bytes_loop);
9047         vmovdqu(Address(to, 0), xtmp);
9048         vmovdqu(Address(to, 32), xtmp);
9049         addptr(to, 64);
9050         subl(count, 16 << shift);
9051         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9052 
9053         BIND(L_check_fill_32_bytes);
9054         addl(count, 8 << shift);
9055         jccb(Assembler::less, L_check_fill_8_bytes);
9056         vmovdqu(Address(to, 0), xtmp);
9057         addptr(to, 32);
9058         subl(count, 8 << shift);
9059 
9060         BIND(L_check_fill_8_bytes);
9061         // clean upper bits of YMM registers
9062         movdl(xtmp, value);
9063         pshufd(xtmp, xtmp, 0);
9064       } else {
9065         // Fill 32-byte chunks
9066         pshufd(xtmp, xtmp, 0);
9067 
9068         subl(count, 8 << shift);
9069         jcc(Assembler::less, L_check_fill_8_bytes);
9070         align(16);
9071 
9072         BIND(L_fill_32_bytes_loop);
9073 
9074         if (UseUnalignedLoadStores) {
9075           movdqu(Address(to, 0), xtmp);
9076           movdqu(Address(to, 16), xtmp);
9077         } else {
9078           movq(Address(to, 0), xtmp);
9079           movq(Address(to, 8), xtmp);
9080           movq(Address(to, 16), xtmp);
9081           movq(Address(to, 24), xtmp);
9082         }
9083 
9084         addptr(to, 32);
9085         subl(count, 8 << shift);
9086         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9087 
9088         BIND(L_check_fill_8_bytes);
9089       }
9090       addl(count, 8 << shift);
9091       jccb(Assembler::zero, L_exit);
9092       jmpb(L_fill_8_bytes);
9093 
9094       //
9095       // length is too short, just fill qwords
9096       //
9097       BIND(L_fill_8_bytes_loop);
9098       movq(Address(to, 0), xtmp);
9099       addptr(to, 8);
9100       BIND(L_fill_8_bytes);
9101       subl(count, 1 << (shift + 1));
9102       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9103     }
9104   }
9105   // fill trailing 4 bytes
9106   BIND(L_fill_4_bytes);
9107   testl(count, 1<<shift);
9108   jccb(Assembler::zero, L_fill_2_bytes);
9109   movl(Address(to, 0), value);
9110   if (t == T_BYTE || t == T_SHORT) {
9111     addptr(to, 4);
9112     BIND(L_fill_2_bytes);
9113     // fill trailing 2 bytes
9114     testl(count, 1<<(shift-1));
9115     jccb(Assembler::zero, L_fill_byte);
9116     movw(Address(to, 0), value);
9117     if (t == T_BYTE) {
9118       addptr(to, 2);
9119       BIND(L_fill_byte);
9120       // fill trailing byte
9121       testl(count, 1);
9122       jccb(Assembler::zero, L_exit);
9123       movb(Address(to, 0), value);
9124     } else {
9125       BIND(L_fill_byte);
9126     }
9127   } else {
9128     BIND(L_fill_2_bytes);
9129   }
9130   BIND(L_exit);
9131 }
9132 
9133 // encode char[] to byte[] in ISO_8859_1
9134    //@HotSpotIntrinsicCandidate
9135    //private static int implEncodeISOArray(byte[] sa, int sp,
9136    //byte[] da, int dp, int len) {
9137    //  int i = 0;
9138    //  for (; i < len; i++) {
9139    //    char c = StringUTF16.getChar(sa, sp++);
9140    //    if (c > '\u00FF')
9141    //      break;
9142    //    da[dp++] = (byte)c;
9143    //  }
9144    //  return i;
9145    //}
9146 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
9147   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9148   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9149   Register tmp5, Register result) {
9150 
9151   // rsi: src
9152   // rdi: dst
9153   // rdx: len
9154   // rcx: tmp5
9155   // rax: result
9156   ShortBranchVerifier sbv(this);
9157   assert_different_registers(src, dst, len, tmp5, result);
9158   Label L_done, L_copy_1_char, L_copy_1_char_exit;
9159 
9160   // set result
9161   xorl(result, result);
9162   // check for zero length
9163   testl(len, len);
9164   jcc(Assembler::zero, L_done);
9165 
9166   movl(result, len);
9167 
9168   // Setup pointers
9169   lea(src, Address(src, len, Address::times_2)); // char[]
9170   lea(dst, Address(dst, len, Address::times_1)); // byte[]
9171   negptr(len);
9172 
9173   if (UseSSE42Intrinsics || UseAVX >= 2) {
9174     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
9175     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
9176 
9177     if (UseAVX >= 2) {
9178       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
9179       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9180       movdl(tmp1Reg, tmp5);
9181       vpbroadcastd(tmp1Reg, tmp1Reg);
9182       jmp(L_chars_32_check);
9183 
9184       bind(L_copy_32_chars);
9185       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
9186       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
9187       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9188       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9189       jccb(Assembler::notZero, L_copy_32_chars_exit);
9190       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9191       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
9192       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
9193 
9194       bind(L_chars_32_check);
9195       addptr(len, 32);
9196       jcc(Assembler::lessEqual, L_copy_32_chars);
9197 
9198       bind(L_copy_32_chars_exit);
9199       subptr(len, 16);
9200       jccb(Assembler::greater, L_copy_16_chars_exit);
9201 
9202     } else if (UseSSE42Intrinsics) {
9203       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9204       movdl(tmp1Reg, tmp5);
9205       pshufd(tmp1Reg, tmp1Reg, 0);
9206       jmpb(L_chars_16_check);
9207     }
9208 
9209     bind(L_copy_16_chars);
9210     if (UseAVX >= 2) {
9211       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9212       vptest(tmp2Reg, tmp1Reg);
9213       jcc(Assembler::notZero, L_copy_16_chars_exit);
9214       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9215       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9216     } else {
9217       if (UseAVX > 0) {
9218         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9219         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9220         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9221       } else {
9222         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9223         por(tmp2Reg, tmp3Reg);
9224         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9225         por(tmp2Reg, tmp4Reg);
9226       }
9227       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9228       jccb(Assembler::notZero, L_copy_16_chars_exit);
9229       packuswb(tmp3Reg, tmp4Reg);
9230     }
9231     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9232 
9233     bind(L_chars_16_check);
9234     addptr(len, 16);
9235     jcc(Assembler::lessEqual, L_copy_16_chars);
9236 
9237     bind(L_copy_16_chars_exit);
9238     if (UseAVX >= 2) {
9239       // clean upper bits of YMM registers
9240       vpxor(tmp2Reg, tmp2Reg);
9241       vpxor(tmp3Reg, tmp3Reg);
9242       vpxor(tmp4Reg, tmp4Reg);
9243       movdl(tmp1Reg, tmp5);
9244       pshufd(tmp1Reg, tmp1Reg, 0);
9245     }
9246     subptr(len, 8);
9247     jccb(Assembler::greater, L_copy_8_chars_exit);
9248 
9249     bind(L_copy_8_chars);
9250     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9251     ptest(tmp3Reg, tmp1Reg);
9252     jccb(Assembler::notZero, L_copy_8_chars_exit);
9253     packuswb(tmp3Reg, tmp1Reg);
9254     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9255     addptr(len, 8);
9256     jccb(Assembler::lessEqual, L_copy_8_chars);
9257 
9258     bind(L_copy_8_chars_exit);
9259     subptr(len, 8);
9260     jccb(Assembler::zero, L_done);
9261   }
9262 
9263   bind(L_copy_1_char);
9264   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9265   testl(tmp5, 0xff00);      // check if Unicode char
9266   jccb(Assembler::notZero, L_copy_1_char_exit);
9267   movb(Address(dst, len, Address::times_1, 0), tmp5);
9268   addptr(len, 1);
9269   jccb(Assembler::less, L_copy_1_char);
9270 
9271   bind(L_copy_1_char_exit);
9272   addptr(result, len); // len is negative count of not processed elements
9273 
9274   bind(L_done);
9275 }
9276 
9277 #ifdef _LP64
9278 /**
9279  * Helper for multiply_to_len().
9280  */
9281 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9282   addq(dest_lo, src1);
9283   adcq(dest_hi, 0);
9284   addq(dest_lo, src2);
9285   adcq(dest_hi, 0);
9286 }
9287 
9288 /**
9289  * Multiply 64 bit by 64 bit first loop.
9290  */
9291 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9292                                            Register y, Register y_idx, Register z,
9293                                            Register carry, Register product,
9294                                            Register idx, Register kdx) {
9295   //
9296   //  jlong carry, x[], y[], z[];
9297   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9298   //    huge_128 product = y[idx] * x[xstart] + carry;
9299   //    z[kdx] = (jlong)product;
9300   //    carry  = (jlong)(product >>> 64);
9301   //  }
9302   //  z[xstart] = carry;
9303   //
9304 
9305   Label L_first_loop, L_first_loop_exit;
9306   Label L_one_x, L_one_y, L_multiply;
9307 
9308   decrementl(xstart);
9309   jcc(Assembler::negative, L_one_x);
9310 
9311   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9312   rorq(x_xstart, 32); // convert big-endian to little-endian
9313 
9314   bind(L_first_loop);
9315   decrementl(idx);
9316   jcc(Assembler::negative, L_first_loop_exit);
9317   decrementl(idx);
9318   jcc(Assembler::negative, L_one_y);
9319   movq(y_idx, Address(y, idx, Address::times_4,  0));
9320   rorq(y_idx, 32); // convert big-endian to little-endian
9321   bind(L_multiply);
9322   movq(product, x_xstart);
9323   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9324   addq(product, carry);
9325   adcq(rdx, 0);
9326   subl(kdx, 2);
9327   movl(Address(z, kdx, Address::times_4,  4), product);
9328   shrq(product, 32);
9329   movl(Address(z, kdx, Address::times_4,  0), product);
9330   movq(carry, rdx);
9331   jmp(L_first_loop);
9332 
9333   bind(L_one_y);
9334   movl(y_idx, Address(y,  0));
9335   jmp(L_multiply);
9336 
9337   bind(L_one_x);
9338   movl(x_xstart, Address(x,  0));
9339   jmp(L_first_loop);
9340 
9341   bind(L_first_loop_exit);
9342 }
9343 
9344 /**
9345  * Multiply 64 bit by 64 bit and add 128 bit.
9346  */
9347 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9348                                             Register yz_idx, Register idx,
9349                                             Register carry, Register product, int offset) {
9350   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9351   //     z[kdx] = (jlong)product;
9352 
9353   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9354   rorq(yz_idx, 32); // convert big-endian to little-endian
9355   movq(product, x_xstart);
9356   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9357   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9358   rorq(yz_idx, 32); // convert big-endian to little-endian
9359 
9360   add2_with_carry(rdx, product, carry, yz_idx);
9361 
9362   movl(Address(z, idx, Address::times_4,  offset+4), product);
9363   shrq(product, 32);
9364   movl(Address(z, idx, Address::times_4,  offset), product);
9365 
9366 }
9367 
9368 /**
9369  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9370  */
9371 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9372                                              Register yz_idx, Register idx, Register jdx,
9373                                              Register carry, Register product,
9374                                              Register carry2) {
9375   //   jlong carry, x[], y[], z[];
9376   //   int kdx = ystart+1;
9377   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9378   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9379   //     z[kdx+idx+1] = (jlong)product;
9380   //     jlong carry2  = (jlong)(product >>> 64);
9381   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9382   //     z[kdx+idx] = (jlong)product;
9383   //     carry  = (jlong)(product >>> 64);
9384   //   }
9385   //   idx += 2;
9386   //   if (idx > 0) {
9387   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9388   //     z[kdx+idx] = (jlong)product;
9389   //     carry  = (jlong)(product >>> 64);
9390   //   }
9391   //
9392 
9393   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9394 
9395   movl(jdx, idx);
9396   andl(jdx, 0xFFFFFFFC);
9397   shrl(jdx, 2);
9398 
9399   bind(L_third_loop);
9400   subl(jdx, 1);
9401   jcc(Assembler::negative, L_third_loop_exit);
9402   subl(idx, 4);
9403 
9404   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9405   movq(carry2, rdx);
9406 
9407   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9408   movq(carry, rdx);
9409   jmp(L_third_loop);
9410 
9411   bind (L_third_loop_exit);
9412 
9413   andl (idx, 0x3);
9414   jcc(Assembler::zero, L_post_third_loop_done);
9415 
9416   Label L_check_1;
9417   subl(idx, 2);
9418   jcc(Assembler::negative, L_check_1);
9419 
9420   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9421   movq(carry, rdx);
9422 
9423   bind (L_check_1);
9424   addl (idx, 0x2);
9425   andl (idx, 0x1);
9426   subl(idx, 1);
9427   jcc(Assembler::negative, L_post_third_loop_done);
9428 
9429   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9430   movq(product, x_xstart);
9431   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9432   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9433 
9434   add2_with_carry(rdx, product, yz_idx, carry);
9435 
9436   movl(Address(z, idx, Address::times_4,  0), product);
9437   shrq(product, 32);
9438 
9439   shlq(rdx, 32);
9440   orq(product, rdx);
9441   movq(carry, product);
9442 
9443   bind(L_post_third_loop_done);
9444 }
9445 
9446 /**
9447  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9448  *
9449  */
9450 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9451                                                   Register carry, Register carry2,
9452                                                   Register idx, Register jdx,
9453                                                   Register yz_idx1, Register yz_idx2,
9454                                                   Register tmp, Register tmp3, Register tmp4) {
9455   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9456 
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 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9461   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9462   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9463   //     carry  = (jlong)(tmp4 >>> 64);
9464   //     z[kdx+idx+1] = (jlong)tmp3;
9465   //     z[kdx+idx] = (jlong)tmp4;
9466   //   }
9467   //   idx += 2;
9468   //   if (idx > 0) {
9469   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9470   //     z[kdx+idx] = (jlong)yz_idx1;
9471   //     carry  = (jlong)(yz_idx1 >>> 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   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9487   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9488   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9489   rorxq(yz_idx2, yz_idx2, 32);
9490 
9491   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9492   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9493 
9494   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9495   rorxq(yz_idx1, yz_idx1, 32);
9496   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9497   rorxq(yz_idx2, yz_idx2, 32);
9498 
9499   if (VM_Version::supports_adx()) {
9500     adcxq(tmp3, carry);
9501     adoxq(tmp3, yz_idx1);
9502 
9503     adcxq(tmp4, tmp);
9504     adoxq(tmp4, yz_idx2);
9505 
9506     movl(carry, 0); // does not affect flags
9507     adcxq(carry2, carry);
9508     adoxq(carry2, carry);
9509   } else {
9510     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9511     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9512   }
9513   movq(carry, carry2);
9514 
9515   movl(Address(z, idx, Address::times_4, 12), tmp3);
9516   shrq(tmp3, 32);
9517   movl(Address(z, idx, Address::times_4,  8), tmp3);
9518 
9519   movl(Address(z, idx, Address::times_4,  4), tmp4);
9520   shrq(tmp4, 32);
9521   movl(Address(z, idx, Address::times_4,  0), tmp4);
9522 
9523   jmp(L_third_loop);
9524 
9525   bind (L_third_loop_exit);
9526 
9527   andl (idx, 0x3);
9528   jcc(Assembler::zero, L_post_third_loop_done);
9529 
9530   Label L_check_1;
9531   subl(idx, 2);
9532   jcc(Assembler::negative, L_check_1);
9533 
9534   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9535   rorxq(yz_idx1, yz_idx1, 32);
9536   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9537   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9538   rorxq(yz_idx2, yz_idx2, 32);
9539 
9540   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9541 
9542   movl(Address(z, idx, Address::times_4,  4), tmp3);
9543   shrq(tmp3, 32);
9544   movl(Address(z, idx, Address::times_4,  0), tmp3);
9545   movq(carry, tmp4);
9546 
9547   bind (L_check_1);
9548   addl (idx, 0x2);
9549   andl (idx, 0x1);
9550   subl(idx, 1);
9551   jcc(Assembler::negative, L_post_third_loop_done);
9552   movl(tmp4, Address(y, idx, Address::times_4,  0));
9553   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9554   movl(tmp4, Address(z, idx, Address::times_4,  0));
9555 
9556   add2_with_carry(carry2, tmp3, tmp4, carry);
9557 
9558   movl(Address(z, idx, Address::times_4,  0), tmp3);
9559   shrq(tmp3, 32);
9560 
9561   shlq(carry2, 32);
9562   orq(tmp3, carry2);
9563   movq(carry, tmp3);
9564 
9565   bind(L_post_third_loop_done);
9566 }
9567 
9568 /**
9569  * Code for BigInteger::multiplyToLen() instrinsic.
9570  *
9571  * rdi: x
9572  * rax: xlen
9573  * rsi: y
9574  * rcx: ylen
9575  * r8:  z
9576  * r11: zlen
9577  * r12: tmp1
9578  * r13: tmp2
9579  * r14: tmp3
9580  * r15: tmp4
9581  * rbx: tmp5
9582  *
9583  */
9584 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9585                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9586   ShortBranchVerifier sbv(this);
9587   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9588 
9589   push(tmp1);
9590   push(tmp2);
9591   push(tmp3);
9592   push(tmp4);
9593   push(tmp5);
9594 
9595   push(xlen);
9596   push(zlen);
9597 
9598   const Register idx = tmp1;
9599   const Register kdx = tmp2;
9600   const Register xstart = tmp3;
9601 
9602   const Register y_idx = tmp4;
9603   const Register carry = tmp5;
9604   const Register product  = xlen;
9605   const Register x_xstart = zlen;  // reuse register
9606 
9607   // First Loop.
9608   //
9609   //  final static long LONG_MASK = 0xffffffffL;
9610   //  int xstart = xlen - 1;
9611   //  int ystart = ylen - 1;
9612   //  long carry = 0;
9613   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9614   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9615   //    z[kdx] = (int)product;
9616   //    carry = product >>> 32;
9617   //  }
9618   //  z[xstart] = (int)carry;
9619   //
9620 
9621   movl(idx, ylen);      // idx = ylen;
9622   movl(kdx, zlen);      // kdx = xlen+ylen;
9623   xorq(carry, carry);   // carry = 0;
9624 
9625   Label L_done;
9626 
9627   movl(xstart, xlen);
9628   decrementl(xstart);
9629   jcc(Assembler::negative, L_done);
9630 
9631   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9632 
9633   Label L_second_loop;
9634   testl(kdx, kdx);
9635   jcc(Assembler::zero, L_second_loop);
9636 
9637   Label L_carry;
9638   subl(kdx, 1);
9639   jcc(Assembler::zero, L_carry);
9640 
9641   movl(Address(z, kdx, Address::times_4,  0), carry);
9642   shrq(carry, 32);
9643   subl(kdx, 1);
9644 
9645   bind(L_carry);
9646   movl(Address(z, kdx, Address::times_4,  0), carry);
9647 
9648   // Second and third (nested) loops.
9649   //
9650   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9651   //   carry = 0;
9652   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9653   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9654   //                    (z[k] & LONG_MASK) + carry;
9655   //     z[k] = (int)product;
9656   //     carry = product >>> 32;
9657   //   }
9658   //   z[i] = (int)carry;
9659   // }
9660   //
9661   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9662 
9663   const Register jdx = tmp1;
9664 
9665   bind(L_second_loop);
9666   xorl(carry, carry);    // carry = 0;
9667   movl(jdx, ylen);       // j = ystart+1
9668 
9669   subl(xstart, 1);       // i = xstart-1;
9670   jcc(Assembler::negative, L_done);
9671 
9672   push (z);
9673 
9674   Label L_last_x;
9675   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9676   subl(xstart, 1);       // i = xstart-1;
9677   jcc(Assembler::negative, L_last_x);
9678 
9679   if (UseBMI2Instructions) {
9680     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9681     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9682   } else {
9683     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9684     rorq(x_xstart, 32);  // convert big-endian to little-endian
9685   }
9686 
9687   Label L_third_loop_prologue;
9688   bind(L_third_loop_prologue);
9689 
9690   push (x);
9691   push (xstart);
9692   push (ylen);
9693 
9694 
9695   if (UseBMI2Instructions) {
9696     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9697   } else { // !UseBMI2Instructions
9698     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9699   }
9700 
9701   pop(ylen);
9702   pop(xlen);
9703   pop(x);
9704   pop(z);
9705 
9706   movl(tmp3, xlen);
9707   addl(tmp3, 1);
9708   movl(Address(z, tmp3, Address::times_4,  0), carry);
9709   subl(tmp3, 1);
9710   jccb(Assembler::negative, L_done);
9711 
9712   shrq(carry, 32);
9713   movl(Address(z, tmp3, Address::times_4,  0), carry);
9714   jmp(L_second_loop);
9715 
9716   // Next infrequent code is moved outside loops.
9717   bind(L_last_x);
9718   if (UseBMI2Instructions) {
9719     movl(rdx, Address(x,  0));
9720   } else {
9721     movl(x_xstart, Address(x,  0));
9722   }
9723   jmp(L_third_loop_prologue);
9724 
9725   bind(L_done);
9726 
9727   pop(zlen);
9728   pop(xlen);
9729 
9730   pop(tmp5);
9731   pop(tmp4);
9732   pop(tmp3);
9733   pop(tmp2);
9734   pop(tmp1);
9735 }
9736 
9737 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9738   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9739   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9740   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9741   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9742   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9743   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9744   Label SAME_TILL_END, DONE;
9745   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9746 
9747   //scale is in rcx in both Win64 and Unix
9748   ShortBranchVerifier sbv(this);
9749 
9750   shlq(length);
9751   xorq(result, result);
9752 
9753   if ((UseAVX > 2) &&
9754       VM_Version::supports_avx512vlbw()) {
9755     set_vector_masking();  // opening of the stub context for programming mask registers
9756     cmpq(length, 64);
9757     jcc(Assembler::less, VECTOR32_TAIL);
9758     movq(tmp1, length);
9759     andq(tmp1, 0x3F);      // tail count
9760     andq(length, ~(0x3F)); //vector count
9761 
9762     bind(VECTOR64_LOOP);
9763     // AVX512 code to compare 64 byte vectors.
9764     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9765     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9766     kortestql(k7, k7);
9767     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9768     addq(result, 64);
9769     subq(length, 64);
9770     jccb(Assembler::notZero, VECTOR64_LOOP);
9771 
9772     //bind(VECTOR64_TAIL);
9773     testq(tmp1, tmp1);
9774     jcc(Assembler::zero, SAME_TILL_END);
9775 
9776     bind(VECTOR64_TAIL);
9777     // AVX512 code to compare upto 63 byte vectors.
9778     // Save k1
9779     kmovql(k3, k1);
9780     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9781     shlxq(tmp2, tmp2, tmp1);
9782     notq(tmp2);
9783     kmovql(k1, tmp2);
9784 
9785     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9786     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9787 
9788     ktestql(k7, k1);
9789     // Restore k1
9790     kmovql(k1, k3);
9791     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9792 
9793     bind(VECTOR64_NOT_EQUAL);
9794     kmovql(tmp1, k7);
9795     notq(tmp1);
9796     tzcntq(tmp1, tmp1);
9797     addq(result, tmp1);
9798     shrq(result);
9799     jmp(DONE);
9800     bind(VECTOR32_TAIL);
9801     clear_vector_masking();   // closing of the stub context for programming mask registers
9802   }
9803 
9804   cmpq(length, 8);
9805   jcc(Assembler::equal, VECTOR8_LOOP);
9806   jcc(Assembler::less, VECTOR4_TAIL);
9807 
9808   if (UseAVX >= 2) {
9809 
9810     cmpq(length, 16);
9811     jcc(Assembler::equal, VECTOR16_LOOP);
9812     jcc(Assembler::less, VECTOR8_LOOP);
9813 
9814     cmpq(length, 32);
9815     jccb(Assembler::less, VECTOR16_TAIL);
9816 
9817     subq(length, 32);
9818     bind(VECTOR32_LOOP);
9819     vmovdqu(rymm0, Address(obja, result));
9820     vmovdqu(rymm1, Address(objb, result));
9821     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9822     vptest(rymm2, rymm2);
9823     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9824     addq(result, 32);
9825     subq(length, 32);
9826     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9827     addq(length, 32);
9828     jcc(Assembler::equal, SAME_TILL_END);
9829     //falling through if less than 32 bytes left //close the branch here.
9830 
9831     bind(VECTOR16_TAIL);
9832     cmpq(length, 16);
9833     jccb(Assembler::less, VECTOR8_TAIL);
9834     bind(VECTOR16_LOOP);
9835     movdqu(rymm0, Address(obja, result));
9836     movdqu(rymm1, Address(objb, result));
9837     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9838     ptest(rymm2, rymm2);
9839     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9840     addq(result, 16);
9841     subq(length, 16);
9842     jcc(Assembler::equal, SAME_TILL_END);
9843     //falling through if less than 16 bytes left
9844   } else {//regular intrinsics
9845 
9846     cmpq(length, 16);
9847     jccb(Assembler::less, VECTOR8_TAIL);
9848 
9849     subq(length, 16);
9850     bind(VECTOR16_LOOP);
9851     movdqu(rymm0, Address(obja, result));
9852     movdqu(rymm1, Address(objb, result));
9853     pxor(rymm0, rymm1);
9854     ptest(rymm0, rymm0);
9855     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9856     addq(result, 16);
9857     subq(length, 16);
9858     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9859     addq(length, 16);
9860     jcc(Assembler::equal, SAME_TILL_END);
9861     //falling through if less than 16 bytes left
9862   }
9863 
9864   bind(VECTOR8_TAIL);
9865   cmpq(length, 8);
9866   jccb(Assembler::less, VECTOR4_TAIL);
9867   bind(VECTOR8_LOOP);
9868   movq(tmp1, Address(obja, result));
9869   movq(tmp2, Address(objb, result));
9870   xorq(tmp1, tmp2);
9871   testq(tmp1, tmp1);
9872   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9873   addq(result, 8);
9874   subq(length, 8);
9875   jcc(Assembler::equal, SAME_TILL_END);
9876   //falling through if less than 8 bytes left
9877 
9878   bind(VECTOR4_TAIL);
9879   cmpq(length, 4);
9880   jccb(Assembler::less, BYTES_TAIL);
9881   bind(VECTOR4_LOOP);
9882   movl(tmp1, Address(obja, result));
9883   xorl(tmp1, Address(objb, result));
9884   testl(tmp1, tmp1);
9885   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9886   addq(result, 4);
9887   subq(length, 4);
9888   jcc(Assembler::equal, SAME_TILL_END);
9889   //falling through if less than 4 bytes left
9890 
9891   bind(BYTES_TAIL);
9892   bind(BYTES_LOOP);
9893   load_unsigned_byte(tmp1, Address(obja, result));
9894   load_unsigned_byte(tmp2, Address(objb, result));
9895   xorl(tmp1, tmp2);
9896   testl(tmp1, tmp1);
9897   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9898   decq(length);
9899   jccb(Assembler::zero, SAME_TILL_END);
9900   incq(result);
9901   load_unsigned_byte(tmp1, Address(obja, result));
9902   load_unsigned_byte(tmp2, Address(objb, result));
9903   xorl(tmp1, tmp2);
9904   testl(tmp1, tmp1);
9905   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9906   decq(length);
9907   jccb(Assembler::zero, SAME_TILL_END);
9908   incq(result);
9909   load_unsigned_byte(tmp1, Address(obja, result));
9910   load_unsigned_byte(tmp2, Address(objb, result));
9911   xorl(tmp1, tmp2);
9912   testl(tmp1, tmp1);
9913   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9914   jmpb(SAME_TILL_END);
9915 
9916   if (UseAVX >= 2) {
9917     bind(VECTOR32_NOT_EQUAL);
9918     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9919     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9920     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9921     vpmovmskb(tmp1, rymm0);
9922     bsfq(tmp1, tmp1);
9923     addq(result, tmp1);
9924     shrq(result);
9925     jmpb(DONE);
9926   }
9927 
9928   bind(VECTOR16_NOT_EQUAL);
9929   if (UseAVX >= 2) {
9930     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9931     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9932     pxor(rymm0, rymm2);
9933   } else {
9934     pcmpeqb(rymm2, rymm2);
9935     pxor(rymm0, rymm1);
9936     pcmpeqb(rymm0, rymm1);
9937     pxor(rymm0, rymm2);
9938   }
9939   pmovmskb(tmp1, rymm0);
9940   bsfq(tmp1, tmp1);
9941   addq(result, tmp1);
9942   shrq(result);
9943   jmpb(DONE);
9944 
9945   bind(VECTOR8_NOT_EQUAL);
9946   bind(VECTOR4_NOT_EQUAL);
9947   bsfq(tmp1, tmp1);
9948   shrq(tmp1, 3);
9949   addq(result, tmp1);
9950   bind(BYTES_NOT_EQUAL);
9951   shrq(result);
9952   jmpb(DONE);
9953 
9954   bind(SAME_TILL_END);
9955   mov64(result, -1);
9956 
9957   bind(DONE);
9958 }
9959 
9960 //Helper functions for square_to_len()
9961 
9962 /**
9963  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9964  * Preserves x and z and modifies rest of the registers.
9965  */
9966 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9967   // Perform square and right shift by 1
9968   // Handle odd xlen case first, then for even xlen do the following
9969   // jlong carry = 0;
9970   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9971   //     huge_128 product = x[j:j+1] * x[j:j+1];
9972   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9973   //     z[i+2:i+3] = (jlong)(product >>> 1);
9974   //     carry = (jlong)product;
9975   // }
9976 
9977   xorq(tmp5, tmp5);     // carry
9978   xorq(rdxReg, rdxReg);
9979   xorl(tmp1, tmp1);     // index for x
9980   xorl(tmp4, tmp4);     // index for z
9981 
9982   Label L_first_loop, L_first_loop_exit;
9983 
9984   testl(xlen, 1);
9985   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9986 
9987   // Square and right shift by 1 the odd element using 32 bit multiply
9988   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9989   imulq(raxReg, raxReg);
9990   shrq(raxReg, 1);
9991   adcq(tmp5, 0);
9992   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9993   incrementl(tmp1);
9994   addl(tmp4, 2);
9995 
9996   // Square and  right shift by 1 the rest using 64 bit multiply
9997   bind(L_first_loop);
9998   cmpptr(tmp1, xlen);
9999   jccb(Assembler::equal, L_first_loop_exit);
10000 
10001   // Square
10002   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
10003   rorq(raxReg, 32);    // convert big-endian to little-endian
10004   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
10005 
10006   // Right shift by 1 and save carry
10007   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
10008   rcrq(rdxReg, 1);
10009   rcrq(raxReg, 1);
10010   adcq(tmp5, 0);
10011 
10012   // Store result in z
10013   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
10014   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
10015 
10016   // Update indices for x and z
10017   addl(tmp1, 2);
10018   addl(tmp4, 4);
10019   jmp(L_first_loop);
10020 
10021   bind(L_first_loop_exit);
10022 }
10023 
10024 
10025 /**
10026  * Perform the following multiply add operation using BMI2 instructions
10027  * carry:sum = sum + op1*op2 + carry
10028  * op2 should be in rdx
10029  * op2 is preserved, all other registers are modified
10030  */
10031 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
10032   // assert op2 is rdx
10033   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
10034   addq(sum, carry);
10035   adcq(tmp2, 0);
10036   addq(sum, op1);
10037   adcq(tmp2, 0);
10038   movq(carry, tmp2);
10039 }
10040 
10041 /**
10042  * Perform the following multiply add operation:
10043  * carry:sum = sum + op1*op2 + carry
10044  * Preserves op1, op2 and modifies rest of registers
10045  */
10046 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
10047   // rdx:rax = op1 * op2
10048   movq(raxReg, op2);
10049   mulq(op1);
10050 
10051   //  rdx:rax = sum + carry + rdx:rax
10052   addq(sum, carry);
10053   adcq(rdxReg, 0);
10054   addq(sum, raxReg);
10055   adcq(rdxReg, 0);
10056 
10057   // carry:sum = rdx:sum
10058   movq(carry, rdxReg);
10059 }
10060 
10061 /**
10062  * Add 64 bit long carry into z[] with carry propogation.
10063  * Preserves z and carry register values and modifies rest of registers.
10064  *
10065  */
10066 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
10067   Label L_fourth_loop, L_fourth_loop_exit;
10068 
10069   movl(tmp1, 1);
10070   subl(zlen, 2);
10071   addq(Address(z, zlen, Address::times_4, 0), carry);
10072 
10073   bind(L_fourth_loop);
10074   jccb(Assembler::carryClear, L_fourth_loop_exit);
10075   subl(zlen, 2);
10076   jccb(Assembler::negative, L_fourth_loop_exit);
10077   addq(Address(z, zlen, Address::times_4, 0), tmp1);
10078   jmp(L_fourth_loop);
10079   bind(L_fourth_loop_exit);
10080 }
10081 
10082 /**
10083  * Shift z[] left by 1 bit.
10084  * Preserves x, len, z and zlen registers and modifies rest of the registers.
10085  *
10086  */
10087 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
10088 
10089   Label L_fifth_loop, L_fifth_loop_exit;
10090 
10091   // Fifth loop
10092   // Perform primitiveLeftShift(z, zlen, 1)
10093 
10094   const Register prev_carry = tmp1;
10095   const Register new_carry = tmp4;
10096   const Register value = tmp2;
10097   const Register zidx = tmp3;
10098 
10099   // int zidx, carry;
10100   // long value;
10101   // carry = 0;
10102   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
10103   //    (carry:value)  = (z[i] << 1) | carry ;
10104   //    z[i] = value;
10105   // }
10106 
10107   movl(zidx, zlen);
10108   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
10109 
10110   bind(L_fifth_loop);
10111   decl(zidx);  // Use decl to preserve carry flag
10112   decl(zidx);
10113   jccb(Assembler::negative, L_fifth_loop_exit);
10114 
10115   if (UseBMI2Instructions) {
10116      movq(value, Address(z, zidx, Address::times_4, 0));
10117      rclq(value, 1);
10118      rorxq(value, value, 32);
10119      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10120   }
10121   else {
10122     // clear new_carry
10123     xorl(new_carry, new_carry);
10124 
10125     // Shift z[i] by 1, or in previous carry and save new carry
10126     movq(value, Address(z, zidx, Address::times_4, 0));
10127     shlq(value, 1);
10128     adcl(new_carry, 0);
10129 
10130     orq(value, prev_carry);
10131     rorq(value, 0x20);
10132     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10133 
10134     // Set previous carry = new carry
10135     movl(prev_carry, new_carry);
10136   }
10137   jmp(L_fifth_loop);
10138 
10139   bind(L_fifth_loop_exit);
10140 }
10141 
10142 
10143 /**
10144  * Code for BigInteger::squareToLen() intrinsic
10145  *
10146  * rdi: x
10147  * rsi: len
10148  * r8:  z
10149  * rcx: zlen
10150  * r12: tmp1
10151  * r13: tmp2
10152  * r14: tmp3
10153  * r15: tmp4
10154  * rbx: tmp5
10155  *
10156  */
10157 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) {
10158 
10159   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;
10160   push(tmp1);
10161   push(tmp2);
10162   push(tmp3);
10163   push(tmp4);
10164   push(tmp5);
10165 
10166   // First loop
10167   // Store the squares, right shifted one bit (i.e., divided by 2).
10168   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
10169 
10170   // Add in off-diagonal sums.
10171   //
10172   // Second, third (nested) and fourth loops.
10173   // zlen +=2;
10174   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
10175   //    carry = 0;
10176   //    long op2 = x[xidx:xidx+1];
10177   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
10178   //       k -= 2;
10179   //       long op1 = x[j:j+1];
10180   //       long sum = z[k:k+1];
10181   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
10182   //       z[k:k+1] = sum;
10183   //    }
10184   //    add_one_64(z, k, carry, tmp_regs);
10185   // }
10186 
10187   const Register carry = tmp5;
10188   const Register sum = tmp3;
10189   const Register op1 = tmp4;
10190   Register op2 = tmp2;
10191 
10192   push(zlen);
10193   push(len);
10194   addl(zlen,2);
10195   bind(L_second_loop);
10196   xorq(carry, carry);
10197   subl(zlen, 4);
10198   subl(len, 2);
10199   push(zlen);
10200   push(len);
10201   cmpl(len, 0);
10202   jccb(Assembler::lessEqual, L_second_loop_exit);
10203 
10204   // Multiply an array by one 64 bit long.
10205   if (UseBMI2Instructions) {
10206     op2 = rdxReg;
10207     movq(op2, Address(x, len, Address::times_4,  0));
10208     rorxq(op2, op2, 32);
10209   }
10210   else {
10211     movq(op2, Address(x, len, Address::times_4,  0));
10212     rorq(op2, 32);
10213   }
10214 
10215   bind(L_third_loop);
10216   decrementl(len);
10217   jccb(Assembler::negative, L_third_loop_exit);
10218   decrementl(len);
10219   jccb(Assembler::negative, L_last_x);
10220 
10221   movq(op1, Address(x, len, Address::times_4,  0));
10222   rorq(op1, 32);
10223 
10224   bind(L_multiply);
10225   subl(zlen, 2);
10226   movq(sum, Address(z, zlen, Address::times_4,  0));
10227 
10228   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10229   if (UseBMI2Instructions) {
10230     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10231   }
10232   else {
10233     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10234   }
10235 
10236   movq(Address(z, zlen, Address::times_4, 0), sum);
10237 
10238   jmp(L_third_loop);
10239   bind(L_third_loop_exit);
10240 
10241   // Fourth loop
10242   // Add 64 bit long carry into z with carry propogation.
10243   // Uses offsetted zlen.
10244   add_one_64(z, zlen, carry, tmp1);
10245 
10246   pop(len);
10247   pop(zlen);
10248   jmp(L_second_loop);
10249 
10250   // Next infrequent code is moved outside loops.
10251   bind(L_last_x);
10252   movl(op1, Address(x, 0));
10253   jmp(L_multiply);
10254 
10255   bind(L_second_loop_exit);
10256   pop(len);
10257   pop(zlen);
10258   pop(len);
10259   pop(zlen);
10260 
10261   // Fifth loop
10262   // Shift z left 1 bit.
10263   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10264 
10265   // z[zlen-1] |= x[len-1] & 1;
10266   movl(tmp3, Address(x, len, Address::times_4, -4));
10267   andl(tmp3, 1);
10268   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10269 
10270   pop(tmp5);
10271   pop(tmp4);
10272   pop(tmp3);
10273   pop(tmp2);
10274   pop(tmp1);
10275 }
10276 
10277 /**
10278  * Helper function for mul_add()
10279  * Multiply the in[] by int k and add to out[] starting at offset offs using
10280  * 128 bit by 32 bit multiply and return the carry in tmp5.
10281  * Only quad int aligned length of in[] is operated on in this function.
10282  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10283  * This function preserves out, in and k registers.
10284  * len and offset point to the appropriate index in "in" & "out" correspondingly
10285  * tmp5 has the carry.
10286  * other registers are temporary and are modified.
10287  *
10288  */
10289 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10290   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10291   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10292 
10293   Label L_first_loop, L_first_loop_exit;
10294 
10295   movl(tmp1, len);
10296   shrl(tmp1, 2);
10297 
10298   bind(L_first_loop);
10299   subl(tmp1, 1);
10300   jccb(Assembler::negative, L_first_loop_exit);
10301 
10302   subl(len, 4);
10303   subl(offset, 4);
10304 
10305   Register op2 = tmp2;
10306   const Register sum = tmp3;
10307   const Register op1 = tmp4;
10308   const Register carry = tmp5;
10309 
10310   if (UseBMI2Instructions) {
10311     op2 = rdxReg;
10312   }
10313 
10314   movq(op1, Address(in, len, Address::times_4,  8));
10315   rorq(op1, 32);
10316   movq(sum, Address(out, offset, Address::times_4,  8));
10317   rorq(sum, 32);
10318   if (UseBMI2Instructions) {
10319     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10320   }
10321   else {
10322     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10323   }
10324   // Store back in big endian from little endian
10325   rorq(sum, 0x20);
10326   movq(Address(out, offset, Address::times_4,  8), sum);
10327 
10328   movq(op1, Address(in, len, Address::times_4,  0));
10329   rorq(op1, 32);
10330   movq(sum, Address(out, offset, Address::times_4,  0));
10331   rorq(sum, 32);
10332   if (UseBMI2Instructions) {
10333     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10334   }
10335   else {
10336     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10337   }
10338   // Store back in big endian from little endian
10339   rorq(sum, 0x20);
10340   movq(Address(out, offset, Address::times_4,  0), sum);
10341 
10342   jmp(L_first_loop);
10343   bind(L_first_loop_exit);
10344 }
10345 
10346 /**
10347  * Code for BigInteger::mulAdd() intrinsic
10348  *
10349  * rdi: out
10350  * rsi: in
10351  * r11: offs (out.length - offset)
10352  * rcx: len
10353  * r8:  k
10354  * r12: tmp1
10355  * r13: tmp2
10356  * r14: tmp3
10357  * r15: tmp4
10358  * rbx: tmp5
10359  * Multiply the in[] by word k and add to out[], return the carry in rax
10360  */
10361 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10362    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10363    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10364 
10365   Label L_carry, L_last_in, L_done;
10366 
10367 // carry = 0;
10368 // for (int j=len-1; j >= 0; j--) {
10369 //    long product = (in[j] & LONG_MASK) * kLong +
10370 //                   (out[offs] & LONG_MASK) + carry;
10371 //    out[offs--] = (int)product;
10372 //    carry = product >>> 32;
10373 // }
10374 //
10375   push(tmp1);
10376   push(tmp2);
10377   push(tmp3);
10378   push(tmp4);
10379   push(tmp5);
10380 
10381   Register op2 = tmp2;
10382   const Register sum = tmp3;
10383   const Register op1 = tmp4;
10384   const Register carry =  tmp5;
10385 
10386   if (UseBMI2Instructions) {
10387     op2 = rdxReg;
10388     movl(op2, k);
10389   }
10390   else {
10391     movl(op2, k);
10392   }
10393 
10394   xorq(carry, carry);
10395 
10396   //First loop
10397 
10398   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10399   //The carry is in tmp5
10400   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10401 
10402   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10403   decrementl(len);
10404   jccb(Assembler::negative, L_carry);
10405   decrementl(len);
10406   jccb(Assembler::negative, L_last_in);
10407 
10408   movq(op1, Address(in, len, Address::times_4,  0));
10409   rorq(op1, 32);
10410 
10411   subl(offs, 2);
10412   movq(sum, Address(out, offs, Address::times_4,  0));
10413   rorq(sum, 32);
10414 
10415   if (UseBMI2Instructions) {
10416     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10417   }
10418   else {
10419     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10420   }
10421 
10422   // Store back in big endian from little endian
10423   rorq(sum, 0x20);
10424   movq(Address(out, offs, Address::times_4,  0), sum);
10425 
10426   testl(len, len);
10427   jccb(Assembler::zero, L_carry);
10428 
10429   //Multiply the last in[] entry, if any
10430   bind(L_last_in);
10431   movl(op1, Address(in, 0));
10432   movl(sum, Address(out, offs, Address::times_4,  -4));
10433 
10434   movl(raxReg, k);
10435   mull(op1); //tmp4 * eax -> edx:eax
10436   addl(sum, carry);
10437   adcl(rdxReg, 0);
10438   addl(sum, raxReg);
10439   adcl(rdxReg, 0);
10440   movl(carry, rdxReg);
10441 
10442   movl(Address(out, offs, Address::times_4,  -4), sum);
10443 
10444   bind(L_carry);
10445   //return tmp5/carry as carry in rax
10446   movl(rax, carry);
10447 
10448   bind(L_done);
10449   pop(tmp5);
10450   pop(tmp4);
10451   pop(tmp3);
10452   pop(tmp2);
10453   pop(tmp1);
10454 }
10455 #endif
10456 
10457 /**
10458  * Emits code to update CRC-32 with a byte value according to constants in table
10459  *
10460  * @param [in,out]crc   Register containing the crc.
10461  * @param [in]val       Register containing the byte to fold into the CRC.
10462  * @param [in]table     Register containing the table of crc constants.
10463  *
10464  * uint32_t crc;
10465  * val = crc_table[(val ^ crc) & 0xFF];
10466  * crc = val ^ (crc >> 8);
10467  *
10468  */
10469 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10470   xorl(val, crc);
10471   andl(val, 0xFF);
10472   shrl(crc, 8); // unsigned shift
10473   xorl(crc, Address(table, val, Address::times_4, 0));
10474 }
10475 
10476 /**
10477  * Fold 128-bit data chunk
10478  */
10479 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10480   if (UseAVX > 0) {
10481     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10482     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10483     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10484     pxor(xcrc, xtmp);
10485   } else {
10486     movdqa(xtmp, xcrc);
10487     pclmulhdq(xtmp, xK);   // [123:64]
10488     pclmulldq(xcrc, xK);   // [63:0]
10489     pxor(xcrc, xtmp);
10490     movdqu(xtmp, Address(buf, offset));
10491     pxor(xcrc, xtmp);
10492   }
10493 }
10494 
10495 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10496   if (UseAVX > 0) {
10497     vpclmulhdq(xtmp, xK, xcrc);
10498     vpclmulldq(xcrc, xK, xcrc);
10499     pxor(xcrc, xbuf);
10500     pxor(xcrc, xtmp);
10501   } else {
10502     movdqa(xtmp, xcrc);
10503     pclmulhdq(xtmp, xK);
10504     pclmulldq(xcrc, xK);
10505     pxor(xcrc, xbuf);
10506     pxor(xcrc, xtmp);
10507   }
10508 }
10509 
10510 /**
10511  * 8-bit folds to compute 32-bit CRC
10512  *
10513  * uint64_t xcrc;
10514  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10515  */
10516 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10517   movdl(tmp, xcrc);
10518   andl(tmp, 0xFF);
10519   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10520   psrldq(xcrc, 1); // unsigned shift one byte
10521   pxor(xcrc, xtmp);
10522 }
10523 
10524 /**
10525  * uint32_t crc;
10526  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10527  */
10528 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10529   movl(tmp, crc);
10530   andl(tmp, 0xFF);
10531   shrl(crc, 8);
10532   xorl(crc, Address(table, tmp, Address::times_4, 0));
10533 }
10534 
10535 /**
10536  * @param crc   register containing existing CRC (32-bit)
10537  * @param buf   register pointing to input byte buffer (byte*)
10538  * @param len   register containing number of bytes
10539  * @param table register that will contain address of CRC table
10540  * @param tmp   scratch register
10541  */
10542 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10543   assert_different_registers(crc, buf, len, table, tmp, rax);
10544 
10545   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10546   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10547 
10548   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10549   // context for the registers used, where all instructions below are using 128-bit mode
10550   // On EVEX without VL and BW, these instructions will all be AVX.
10551   if (VM_Version::supports_avx512vlbw()) {
10552     movl(tmp, 0xffff);
10553     kmovwl(k1, tmp);
10554   }
10555 
10556   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10557   notl(crc); // ~crc
10558   cmpl(len, 16);
10559   jcc(Assembler::less, L_tail);
10560 
10561   // Align buffer to 16 bytes
10562   movl(tmp, buf);
10563   andl(tmp, 0xF);
10564   jccb(Assembler::zero, L_aligned);
10565   subl(tmp,  16);
10566   addl(len, tmp);
10567 
10568   align(4);
10569   BIND(L_align_loop);
10570   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10571   update_byte_crc32(crc, rax, table);
10572   increment(buf);
10573   incrementl(tmp);
10574   jccb(Assembler::less, L_align_loop);
10575 
10576   BIND(L_aligned);
10577   movl(tmp, len); // save
10578   shrl(len, 4);
10579   jcc(Assembler::zero, L_tail_restore);
10580 
10581   // Fold crc into first bytes of vector
10582   movdqa(xmm1, Address(buf, 0));
10583   movdl(rax, xmm1);
10584   xorl(crc, rax);
10585   if (VM_Version::supports_sse4_1()) {
10586     pinsrd(xmm1, crc, 0);
10587   } else {
10588     pinsrw(xmm1, crc, 0);
10589     shrl(crc, 16);
10590     pinsrw(xmm1, crc, 1);
10591   }
10592   addptr(buf, 16);
10593   subl(len, 4); // len > 0
10594   jcc(Assembler::less, L_fold_tail);
10595 
10596   movdqa(xmm2, Address(buf,  0));
10597   movdqa(xmm3, Address(buf, 16));
10598   movdqa(xmm4, Address(buf, 32));
10599   addptr(buf, 48);
10600   subl(len, 3);
10601   jcc(Assembler::lessEqual, L_fold_512b);
10602 
10603   // Fold total 512 bits of polynomial on each iteration,
10604   // 128 bits per each of 4 parallel streams.
10605   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10606 
10607   align(32);
10608   BIND(L_fold_512b_loop);
10609   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10610   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10611   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10612   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10613   addptr(buf, 64);
10614   subl(len, 4);
10615   jcc(Assembler::greater, L_fold_512b_loop);
10616 
10617   // Fold 512 bits to 128 bits.
10618   BIND(L_fold_512b);
10619   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10620   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10621   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10622   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10623 
10624   // Fold the rest of 128 bits data chunks
10625   BIND(L_fold_tail);
10626   addl(len, 3);
10627   jccb(Assembler::lessEqual, L_fold_128b);
10628   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10629 
10630   BIND(L_fold_tail_loop);
10631   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10632   addptr(buf, 16);
10633   decrementl(len);
10634   jccb(Assembler::greater, L_fold_tail_loop);
10635 
10636   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10637   BIND(L_fold_128b);
10638   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10639   if (UseAVX > 0) {
10640     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10641     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10642     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10643   } else {
10644     movdqa(xmm2, xmm0);
10645     pclmulqdq(xmm2, xmm1, 0x1);
10646     movdqa(xmm3, xmm0);
10647     pand(xmm3, xmm2);
10648     pclmulqdq(xmm0, xmm3, 0x1);
10649   }
10650   psrldq(xmm1, 8);
10651   psrldq(xmm2, 4);
10652   pxor(xmm0, xmm1);
10653   pxor(xmm0, xmm2);
10654 
10655   // 8 8-bit folds to compute 32-bit CRC.
10656   for (int j = 0; j < 4; j++) {
10657     fold_8bit_crc32(xmm0, table, xmm1, rax);
10658   }
10659   movdl(crc, xmm0); // mov 32 bits to general register
10660   for (int j = 0; j < 4; j++) {
10661     fold_8bit_crc32(crc, table, rax);
10662   }
10663 
10664   BIND(L_tail_restore);
10665   movl(len, tmp); // restore
10666   BIND(L_tail);
10667   andl(len, 0xf);
10668   jccb(Assembler::zero, L_exit);
10669 
10670   // Fold the rest of bytes
10671   align(4);
10672   BIND(L_tail_loop);
10673   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10674   update_byte_crc32(crc, rax, table);
10675   increment(buf);
10676   decrementl(len);
10677   jccb(Assembler::greater, L_tail_loop);
10678 
10679   BIND(L_exit);
10680   notl(crc); // ~c
10681 }
10682 
10683 #ifdef _LP64
10684 // S. Gueron / Information Processing Letters 112 (2012) 184
10685 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10686 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10687 // Output: the 64-bit carry-less product of B * CONST
10688 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10689                                      Register tmp1, Register tmp2, Register tmp3) {
10690   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10691   if (n > 0) {
10692     addq(tmp3, n * 256 * 8);
10693   }
10694   //    Q1 = TABLEExt[n][B & 0xFF];
10695   movl(tmp1, in);
10696   andl(tmp1, 0x000000FF);
10697   shll(tmp1, 3);
10698   addq(tmp1, tmp3);
10699   movq(tmp1, Address(tmp1, 0));
10700 
10701   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10702   movl(tmp2, in);
10703   shrl(tmp2, 8);
10704   andl(tmp2, 0x000000FF);
10705   shll(tmp2, 3);
10706   addq(tmp2, tmp3);
10707   movq(tmp2, Address(tmp2, 0));
10708 
10709   shlq(tmp2, 8);
10710   xorq(tmp1, tmp2);
10711 
10712   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10713   movl(tmp2, in);
10714   shrl(tmp2, 16);
10715   andl(tmp2, 0x000000FF);
10716   shll(tmp2, 3);
10717   addq(tmp2, tmp3);
10718   movq(tmp2, Address(tmp2, 0));
10719 
10720   shlq(tmp2, 16);
10721   xorq(tmp1, tmp2);
10722 
10723   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10724   shrl(in, 24);
10725   andl(in, 0x000000FF);
10726   shll(in, 3);
10727   addq(in, tmp3);
10728   movq(in, Address(in, 0));
10729 
10730   shlq(in, 24);
10731   xorq(in, tmp1);
10732   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10733 }
10734 
10735 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10736                                       Register in_out,
10737                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10738                                       XMMRegister w_xtmp2,
10739                                       Register tmp1,
10740                                       Register n_tmp2, Register n_tmp3) {
10741   if (is_pclmulqdq_supported) {
10742     movdl(w_xtmp1, in_out); // modified blindly
10743 
10744     movl(tmp1, const_or_pre_comp_const_index);
10745     movdl(w_xtmp2, tmp1);
10746     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10747 
10748     movdq(in_out, w_xtmp1);
10749   } else {
10750     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10751   }
10752 }
10753 
10754 // Recombination Alternative 2: No bit-reflections
10755 // T1 = (CRC_A * U1) << 1
10756 // T2 = (CRC_B * U2) << 1
10757 // C1 = T1 >> 32
10758 // C2 = T2 >> 32
10759 // T1 = T1 & 0xFFFFFFFF
10760 // T2 = T2 & 0xFFFFFFFF
10761 // T1 = CRC32(0, T1)
10762 // T2 = CRC32(0, T2)
10763 // C1 = C1 ^ T1
10764 // C2 = C2 ^ T2
10765 // CRC = C1 ^ C2 ^ CRC_C
10766 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,
10767                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10768                                      Register tmp1, Register tmp2,
10769                                      Register n_tmp3) {
10770   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10771   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10772   shlq(in_out, 1);
10773   movl(tmp1, in_out);
10774   shrq(in_out, 32);
10775   xorl(tmp2, tmp2);
10776   crc32(tmp2, tmp1, 4);
10777   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10778   shlq(in1, 1);
10779   movl(tmp1, in1);
10780   shrq(in1, 32);
10781   xorl(tmp2, tmp2);
10782   crc32(tmp2, tmp1, 4);
10783   xorl(in1, tmp2);
10784   xorl(in_out, in1);
10785   xorl(in_out, in2);
10786 }
10787 
10788 // Set N to predefined value
10789 // Subtract from a lenght of a buffer
10790 // execute in a loop:
10791 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10792 // for i = 1 to N do
10793 //  CRC_A = CRC32(CRC_A, A[i])
10794 //  CRC_B = CRC32(CRC_B, B[i])
10795 //  CRC_C = CRC32(CRC_C, C[i])
10796 // end for
10797 // Recombine
10798 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,
10799                                        Register in_out1, Register in_out2, Register in_out3,
10800                                        Register tmp1, Register tmp2, Register tmp3,
10801                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10802                                        Register tmp4, Register tmp5,
10803                                        Register n_tmp6) {
10804   Label L_processPartitions;
10805   Label L_processPartition;
10806   Label L_exit;
10807 
10808   bind(L_processPartitions);
10809   cmpl(in_out1, 3 * size);
10810   jcc(Assembler::less, L_exit);
10811     xorl(tmp1, tmp1);
10812     xorl(tmp2, tmp2);
10813     movq(tmp3, in_out2);
10814     addq(tmp3, size);
10815 
10816     bind(L_processPartition);
10817       crc32(in_out3, Address(in_out2, 0), 8);
10818       crc32(tmp1, Address(in_out2, size), 8);
10819       crc32(tmp2, Address(in_out2, size * 2), 8);
10820       addq(in_out2, 8);
10821       cmpq(in_out2, tmp3);
10822       jcc(Assembler::less, L_processPartition);
10823     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10824             w_xtmp1, w_xtmp2, w_xtmp3,
10825             tmp4, tmp5,
10826             n_tmp6);
10827     addq(in_out2, 2 * size);
10828     subl(in_out1, 3 * size);
10829     jmp(L_processPartitions);
10830 
10831   bind(L_exit);
10832 }
10833 #else
10834 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10835                                      Register tmp1, Register tmp2, Register tmp3,
10836                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10837   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10838   if (n > 0) {
10839     addl(tmp3, n * 256 * 8);
10840   }
10841   //    Q1 = TABLEExt[n][B & 0xFF];
10842   movl(tmp1, in_out);
10843   andl(tmp1, 0x000000FF);
10844   shll(tmp1, 3);
10845   addl(tmp1, tmp3);
10846   movq(xtmp1, Address(tmp1, 0));
10847 
10848   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10849   movl(tmp2, in_out);
10850   shrl(tmp2, 8);
10851   andl(tmp2, 0x000000FF);
10852   shll(tmp2, 3);
10853   addl(tmp2, tmp3);
10854   movq(xtmp2, Address(tmp2, 0));
10855 
10856   psllq(xtmp2, 8);
10857   pxor(xtmp1, xtmp2);
10858 
10859   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10860   movl(tmp2, in_out);
10861   shrl(tmp2, 16);
10862   andl(tmp2, 0x000000FF);
10863   shll(tmp2, 3);
10864   addl(tmp2, tmp3);
10865   movq(xtmp2, Address(tmp2, 0));
10866 
10867   psllq(xtmp2, 16);
10868   pxor(xtmp1, xtmp2);
10869 
10870   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10871   shrl(in_out, 24);
10872   andl(in_out, 0x000000FF);
10873   shll(in_out, 3);
10874   addl(in_out, tmp3);
10875   movq(xtmp2, Address(in_out, 0));
10876 
10877   psllq(xtmp2, 24);
10878   pxor(xtmp1, xtmp2); // Result in CXMM
10879   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10880 }
10881 
10882 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10883                                       Register in_out,
10884                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10885                                       XMMRegister w_xtmp2,
10886                                       Register tmp1,
10887                                       Register n_tmp2, Register n_tmp3) {
10888   if (is_pclmulqdq_supported) {
10889     movdl(w_xtmp1, in_out);
10890 
10891     movl(tmp1, const_or_pre_comp_const_index);
10892     movdl(w_xtmp2, tmp1);
10893     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10894     // Keep result in XMM since GPR is 32 bit in length
10895   } else {
10896     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10897   }
10898 }
10899 
10900 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,
10901                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10902                                      Register tmp1, Register tmp2,
10903                                      Register n_tmp3) {
10904   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10905   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10906 
10907   psllq(w_xtmp1, 1);
10908   movdl(tmp1, w_xtmp1);
10909   psrlq(w_xtmp1, 32);
10910   movdl(in_out, w_xtmp1);
10911 
10912   xorl(tmp2, tmp2);
10913   crc32(tmp2, tmp1, 4);
10914   xorl(in_out, tmp2);
10915 
10916   psllq(w_xtmp2, 1);
10917   movdl(tmp1, w_xtmp2);
10918   psrlq(w_xtmp2, 32);
10919   movdl(in1, w_xtmp2);
10920 
10921   xorl(tmp2, tmp2);
10922   crc32(tmp2, tmp1, 4);
10923   xorl(in1, tmp2);
10924   xorl(in_out, in1);
10925   xorl(in_out, in2);
10926 }
10927 
10928 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,
10929                                        Register in_out1, Register in_out2, Register in_out3,
10930                                        Register tmp1, Register tmp2, Register tmp3,
10931                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10932                                        Register tmp4, Register tmp5,
10933                                        Register n_tmp6) {
10934   Label L_processPartitions;
10935   Label L_processPartition;
10936   Label L_exit;
10937 
10938   bind(L_processPartitions);
10939   cmpl(in_out1, 3 * size);
10940   jcc(Assembler::less, L_exit);
10941     xorl(tmp1, tmp1);
10942     xorl(tmp2, tmp2);
10943     movl(tmp3, in_out2);
10944     addl(tmp3, size);
10945 
10946     bind(L_processPartition);
10947       crc32(in_out3, Address(in_out2, 0), 4);
10948       crc32(tmp1, Address(in_out2, size), 4);
10949       crc32(tmp2, Address(in_out2, size*2), 4);
10950       crc32(in_out3, Address(in_out2, 0+4), 4);
10951       crc32(tmp1, Address(in_out2, size+4), 4);
10952       crc32(tmp2, Address(in_out2, size*2+4), 4);
10953       addl(in_out2, 8);
10954       cmpl(in_out2, tmp3);
10955       jcc(Assembler::less, L_processPartition);
10956 
10957         push(tmp3);
10958         push(in_out1);
10959         push(in_out2);
10960         tmp4 = tmp3;
10961         tmp5 = in_out1;
10962         n_tmp6 = in_out2;
10963 
10964       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10965             w_xtmp1, w_xtmp2, w_xtmp3,
10966             tmp4, tmp5,
10967             n_tmp6);
10968 
10969         pop(in_out2);
10970         pop(in_out1);
10971         pop(tmp3);
10972 
10973     addl(in_out2, 2 * size);
10974     subl(in_out1, 3 * size);
10975     jmp(L_processPartitions);
10976 
10977   bind(L_exit);
10978 }
10979 #endif //LP64
10980 
10981 #ifdef _LP64
10982 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10983 // Input: A buffer I of L bytes.
10984 // Output: the CRC32C value of the buffer.
10985 // Notations:
10986 // Write L = 24N + r, with N = floor (L/24).
10987 // r = L mod 24 (0 <= r < 24).
10988 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10989 // N quadwords, and R consists of r bytes.
10990 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10991 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10992 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10993 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10994 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10995                                           Register tmp1, Register tmp2, Register tmp3,
10996                                           Register tmp4, Register tmp5, Register tmp6,
10997                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10998                                           bool is_pclmulqdq_supported) {
10999   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11000   Label L_wordByWord;
11001   Label L_byteByByteProlog;
11002   Label L_byteByByte;
11003   Label L_exit;
11004 
11005   if (is_pclmulqdq_supported ) {
11006     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11007     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
11008 
11009     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11010     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11011 
11012     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11013     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11014     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
11015   } else {
11016     const_or_pre_comp_const_index[0] = 1;
11017     const_or_pre_comp_const_index[1] = 0;
11018 
11019     const_or_pre_comp_const_index[2] = 3;
11020     const_or_pre_comp_const_index[3] = 2;
11021 
11022     const_or_pre_comp_const_index[4] = 5;
11023     const_or_pre_comp_const_index[5] = 4;
11024    }
11025   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11026                     in2, in1, in_out,
11027                     tmp1, tmp2, tmp3,
11028                     w_xtmp1, w_xtmp2, w_xtmp3,
11029                     tmp4, tmp5,
11030                     tmp6);
11031   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11032                     in2, in1, in_out,
11033                     tmp1, tmp2, tmp3,
11034                     w_xtmp1, w_xtmp2, w_xtmp3,
11035                     tmp4, tmp5,
11036                     tmp6);
11037   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11038                     in2, in1, in_out,
11039                     tmp1, tmp2, tmp3,
11040                     w_xtmp1, w_xtmp2, w_xtmp3,
11041                     tmp4, tmp5,
11042                     tmp6);
11043   movl(tmp1, in2);
11044   andl(tmp1, 0x00000007);
11045   negl(tmp1);
11046   addl(tmp1, in2);
11047   addq(tmp1, in1);
11048 
11049   BIND(L_wordByWord);
11050   cmpq(in1, tmp1);
11051   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11052     crc32(in_out, Address(in1, 0), 4);
11053     addq(in1, 4);
11054     jmp(L_wordByWord);
11055 
11056   BIND(L_byteByByteProlog);
11057   andl(in2, 0x00000007);
11058   movl(tmp2, 1);
11059 
11060   BIND(L_byteByByte);
11061   cmpl(tmp2, in2);
11062   jccb(Assembler::greater, L_exit);
11063     crc32(in_out, Address(in1, 0), 1);
11064     incq(in1);
11065     incl(tmp2);
11066     jmp(L_byteByByte);
11067 
11068   BIND(L_exit);
11069 }
11070 #else
11071 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11072                                           Register tmp1, Register  tmp2, Register tmp3,
11073                                           Register tmp4, Register  tmp5, Register tmp6,
11074                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11075                                           bool is_pclmulqdq_supported) {
11076   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11077   Label L_wordByWord;
11078   Label L_byteByByteProlog;
11079   Label L_byteByByte;
11080   Label L_exit;
11081 
11082   if (is_pclmulqdq_supported) {
11083     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11084     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
11085 
11086     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11087     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11088 
11089     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11090     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11091   } else {
11092     const_or_pre_comp_const_index[0] = 1;
11093     const_or_pre_comp_const_index[1] = 0;
11094 
11095     const_or_pre_comp_const_index[2] = 3;
11096     const_or_pre_comp_const_index[3] = 2;
11097 
11098     const_or_pre_comp_const_index[4] = 5;
11099     const_or_pre_comp_const_index[5] = 4;
11100   }
11101   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11102                     in2, in1, in_out,
11103                     tmp1, tmp2, tmp3,
11104                     w_xtmp1, w_xtmp2, w_xtmp3,
11105                     tmp4, tmp5,
11106                     tmp6);
11107   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], 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_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], 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   movl(tmp1, in2);
11120   andl(tmp1, 0x00000007);
11121   negl(tmp1);
11122   addl(tmp1, in2);
11123   addl(tmp1, in1);
11124 
11125   BIND(L_wordByWord);
11126   cmpl(in1, tmp1);
11127   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11128     crc32(in_out, Address(in1,0), 4);
11129     addl(in1, 4);
11130     jmp(L_wordByWord);
11131 
11132   BIND(L_byteByByteProlog);
11133   andl(in2, 0x00000007);
11134   movl(tmp2, 1);
11135 
11136   BIND(L_byteByByte);
11137   cmpl(tmp2, in2);
11138   jccb(Assembler::greater, L_exit);
11139     movb(tmp1, Address(in1, 0));
11140     crc32(in_out, tmp1, 1);
11141     incl(in1);
11142     incl(tmp2);
11143     jmp(L_byteByByte);
11144 
11145   BIND(L_exit);
11146 }
11147 #endif // LP64
11148 #undef BIND
11149 #undef BLOCK_COMMENT
11150 
11151 // Compress char[] array to byte[].
11152 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
11153 //   @HotSpotIntrinsicCandidate
11154 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
11155 //     for (int i = 0; i < len; i++) {
11156 //       int c = src[srcOff++];
11157 //       if (c >>> 8 != 0) {
11158 //         return 0;
11159 //       }
11160 //       dst[dstOff++] = (byte)c;
11161 //     }
11162 //     return len;
11163 //   }
11164 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
11165   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
11166   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
11167   Register tmp5, Register result) {
11168   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
11169 
11170   // rsi: src
11171   // rdi: dst
11172   // rdx: len
11173   // rcx: tmp5
11174   // rax: result
11175 
11176   // rsi holds start addr of source char[] to be compressed
11177   // rdi holds start addr of destination byte[]
11178   // rdx holds length
11179 
11180   assert(len != result, "");
11181 
11182   // save length for return
11183   push(len);
11184 
11185   if ((UseAVX > 2) && // AVX512
11186     VM_Version::supports_avx512vlbw() &&
11187     VM_Version::supports_bmi2()) {
11188 
11189     set_vector_masking();  // opening of the stub context for programming mask registers
11190 
11191     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
11192 
11193     // alignement
11194     Label post_alignement;
11195 
11196     // if length of the string is less than 16, handle it in an old fashioned
11197     // way
11198     testl(len, -32);
11199     jcc(Assembler::zero, below_threshold);
11200 
11201     // First check whether a character is compressable ( <= 0xFF).
11202     // Create mask to test for Unicode chars inside zmm vector
11203     movl(result, 0x00FF);
11204     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
11205 
11206     // Save k1
11207     kmovql(k3, k1);
11208 
11209     testl(len, -64);
11210     jcc(Assembler::zero, post_alignement);
11211 
11212     movl(tmp5, dst);
11213     andl(tmp5, (32 - 1));
11214     negl(tmp5);
11215     andl(tmp5, (32 - 1));
11216 
11217     // bail out when there is nothing to be done
11218     testl(tmp5, 0xFFFFFFFF);
11219     jcc(Assembler::zero, post_alignement);
11220 
11221     // ~(~0 << len), where len is the # of remaining elements to process
11222     movl(result, 0xFFFFFFFF);
11223     shlxl(result, result, tmp5);
11224     notl(result);
11225     kmovdl(k1, result);
11226 
11227     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11228     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11229     ktestd(k2, k1);
11230     jcc(Assembler::carryClear, restore_k1_return_zero);
11231 
11232     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11233 
11234     addptr(src, tmp5);
11235     addptr(src, tmp5);
11236     addptr(dst, tmp5);
11237     subl(len, tmp5);
11238 
11239     bind(post_alignement);
11240     // end of alignement
11241 
11242     movl(tmp5, len);
11243     andl(tmp5, (32 - 1));    // tail count (in chars)
11244     andl(len, ~(32 - 1));    // vector count (in chars)
11245     jcc(Assembler::zero, copy_loop_tail);
11246 
11247     lea(src, Address(src, len, Address::times_2));
11248     lea(dst, Address(dst, len, Address::times_1));
11249     negptr(len);
11250 
11251     bind(copy_32_loop);
11252     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11253     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11254     kortestdl(k2, k2);
11255     jcc(Assembler::carryClear, restore_k1_return_zero);
11256 
11257     // All elements in current processed chunk are valid candidates for
11258     // compression. Write a truncated byte elements to the memory.
11259     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11260     addptr(len, 32);
11261     jcc(Assembler::notZero, copy_32_loop);
11262 
11263     bind(copy_loop_tail);
11264     // bail out when there is nothing to be done
11265     testl(tmp5, 0xFFFFFFFF);
11266     // Restore k1
11267     kmovql(k1, k3);
11268     jcc(Assembler::zero, return_length);
11269 
11270     movl(len, tmp5);
11271 
11272     // ~(~0 << len), where len is the # of remaining elements to process
11273     movl(result, 0xFFFFFFFF);
11274     shlxl(result, result, len);
11275     notl(result);
11276 
11277     kmovdl(k1, result);
11278 
11279     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11280     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11281     ktestd(k2, k1);
11282     jcc(Assembler::carryClear, restore_k1_return_zero);
11283 
11284     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11285     // Restore k1
11286     kmovql(k1, k3);
11287     jmp(return_length);
11288 
11289     bind(restore_k1_return_zero);
11290     // Restore k1
11291     kmovql(k1, k3);
11292     jmp(return_zero);
11293 
11294     clear_vector_masking();   // closing of the stub context for programming mask registers
11295   }
11296   if (UseSSE42Intrinsics) {
11297     Label copy_32_loop, copy_16, copy_tail;
11298 
11299     bind(below_threshold);
11300 
11301     movl(result, len);
11302 
11303     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11304 
11305     // vectored compression
11306     andl(len, 0xfffffff0);    // vector count (in chars)
11307     andl(result, 0x0000000f);    // tail count (in chars)
11308     testl(len, len);
11309     jccb(Assembler::zero, copy_16);
11310 
11311     // compress 16 chars per iter
11312     movdl(tmp1Reg, tmp5);
11313     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11314     pxor(tmp4Reg, tmp4Reg);
11315 
11316     lea(src, Address(src, len, Address::times_2));
11317     lea(dst, Address(dst, len, Address::times_1));
11318     negptr(len);
11319 
11320     bind(copy_32_loop);
11321     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11322     por(tmp4Reg, tmp2Reg);
11323     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11324     por(tmp4Reg, tmp3Reg);
11325     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11326     jcc(Assembler::notZero, return_zero);
11327     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11328     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11329     addptr(len, 16);
11330     jcc(Assembler::notZero, copy_32_loop);
11331 
11332     // compress next vector of 8 chars (if any)
11333     bind(copy_16);
11334     movl(len, result);
11335     andl(len, 0xfffffff8);    // vector count (in chars)
11336     andl(result, 0x00000007);    // tail count (in chars)
11337     testl(len, len);
11338     jccb(Assembler::zero, copy_tail);
11339 
11340     movdl(tmp1Reg, tmp5);
11341     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11342     pxor(tmp3Reg, tmp3Reg);
11343 
11344     movdqu(tmp2Reg, Address(src, 0));
11345     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11346     jccb(Assembler::notZero, return_zero);
11347     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11348     movq(Address(dst, 0), tmp2Reg);
11349     addptr(src, 16);
11350     addptr(dst, 8);
11351 
11352     bind(copy_tail);
11353     movl(len, result);
11354   }
11355   // compress 1 char per iter
11356   testl(len, len);
11357   jccb(Assembler::zero, return_length);
11358   lea(src, Address(src, len, Address::times_2));
11359   lea(dst, Address(dst, len, Address::times_1));
11360   negptr(len);
11361 
11362   bind(copy_chars_loop);
11363   load_unsigned_short(result, Address(src, len, Address::times_2));
11364   testl(result, 0xff00);      // check if Unicode char
11365   jccb(Assembler::notZero, return_zero);
11366   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11367   increment(len);
11368   jcc(Assembler::notZero, copy_chars_loop);
11369 
11370   // if compression succeeded, return length
11371   bind(return_length);
11372   pop(result);
11373   jmpb(done);
11374 
11375   // if compression failed, return 0
11376   bind(return_zero);
11377   xorl(result, result);
11378   addptr(rsp, wordSize);
11379 
11380   bind(done);
11381 }
11382 
11383 // Inflate byte[] array to char[].
11384 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11385 //   @HotSpotIntrinsicCandidate
11386 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11387 //     for (int i = 0; i < len; i++) {
11388 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11389 //     }
11390 //   }
11391 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11392   XMMRegister tmp1, Register tmp2) {
11393   Label copy_chars_loop, done, below_threshold;
11394   // rsi: src
11395   // rdi: dst
11396   // rdx: len
11397   // rcx: tmp2
11398 
11399   // rsi holds start addr of source byte[] to be inflated
11400   // rdi holds start addr of destination char[]
11401   // rdx holds length
11402   assert_different_registers(src, dst, len, tmp2);
11403 
11404   if ((UseAVX > 2) && // AVX512
11405     VM_Version::supports_avx512vlbw() &&
11406     VM_Version::supports_bmi2()) {
11407 
11408     set_vector_masking();  // opening of the stub context for programming mask registers
11409 
11410     Label copy_32_loop, copy_tail;
11411     Register tmp3_aliased = len;
11412 
11413     // if length of the string is less than 16, handle it in an old fashioned
11414     // way
11415     testl(len, -16);
11416     jcc(Assembler::zero, below_threshold);
11417 
11418     // In order to use only one arithmetic operation for the main loop we use
11419     // this pre-calculation
11420     movl(tmp2, len);
11421     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11422     andl(len, -32);     // vector count
11423     jccb(Assembler::zero, copy_tail);
11424 
11425     lea(src, Address(src, len, Address::times_1));
11426     lea(dst, Address(dst, len, Address::times_2));
11427     negptr(len);
11428 
11429 
11430     // inflate 32 chars per iter
11431     bind(copy_32_loop);
11432     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11433     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11434     addptr(len, 32);
11435     jcc(Assembler::notZero, copy_32_loop);
11436 
11437     bind(copy_tail);
11438     // bail out when there is nothing to be done
11439     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11440     jcc(Assembler::zero, done);
11441 
11442     // Save k1
11443     kmovql(k2, k1);
11444 
11445     // ~(~0 << length), where length is the # of remaining elements to process
11446     movl(tmp3_aliased, -1);
11447     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11448     notl(tmp3_aliased);
11449     kmovdl(k1, tmp3_aliased);
11450     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11451     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11452 
11453     // Restore k1
11454     kmovql(k1, k2);
11455     jmp(done);
11456 
11457     clear_vector_masking();   // closing of the stub context for programming mask registers
11458   }
11459   if (UseSSE42Intrinsics) {
11460     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11461 
11462     movl(tmp2, len);
11463 
11464     if (UseAVX > 1) {
11465       andl(tmp2, (16 - 1));
11466       andl(len, -16);
11467       jccb(Assembler::zero, copy_new_tail);
11468     } else {
11469       andl(tmp2, 0x00000007);   // tail count (in chars)
11470       andl(len, 0xfffffff8);    // vector count (in chars)
11471       jccb(Assembler::zero, copy_tail);
11472     }
11473 
11474     // vectored inflation
11475     lea(src, Address(src, len, Address::times_1));
11476     lea(dst, Address(dst, len, Address::times_2));
11477     negptr(len);
11478 
11479     if (UseAVX > 1) {
11480       bind(copy_16_loop);
11481       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11482       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11483       addptr(len, 16);
11484       jcc(Assembler::notZero, copy_16_loop);
11485 
11486       bind(below_threshold);
11487       bind(copy_new_tail);
11488       if ((UseAVX > 2) &&
11489         VM_Version::supports_avx512vlbw() &&
11490         VM_Version::supports_bmi2()) {
11491         movl(tmp2, len);
11492       } else {
11493         movl(len, tmp2);
11494       }
11495       andl(tmp2, 0x00000007);
11496       andl(len, 0xFFFFFFF8);
11497       jccb(Assembler::zero, copy_tail);
11498 
11499       pmovzxbw(tmp1, Address(src, 0));
11500       movdqu(Address(dst, 0), tmp1);
11501       addptr(src, 8);
11502       addptr(dst, 2 * 8);
11503 
11504       jmp(copy_tail, true);
11505     }
11506 
11507     // inflate 8 chars per iter
11508     bind(copy_8_loop);
11509     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11510     movdqu(Address(dst, len, Address::times_2), tmp1);
11511     addptr(len, 8);
11512     jcc(Assembler::notZero, copy_8_loop);
11513 
11514     bind(copy_tail);
11515     movl(len, tmp2);
11516 
11517     cmpl(len, 4);
11518     jccb(Assembler::less, copy_bytes);
11519 
11520     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11521     pmovzxbw(tmp1, tmp1);
11522     movq(Address(dst, 0), tmp1);
11523     subptr(len, 4);
11524     addptr(src, 4);
11525     addptr(dst, 8);
11526 
11527     bind(copy_bytes);
11528   }
11529   testl(len, len);
11530   jccb(Assembler::zero, done);
11531   lea(src, Address(src, len, Address::times_1));
11532   lea(dst, Address(dst, len, Address::times_2));
11533   negptr(len);
11534 
11535   // inflate 1 char per iter
11536   bind(copy_chars_loop);
11537   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11538   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11539   increment(len);
11540   jcc(Assembler::notZero, copy_chars_loop);
11541 
11542   bind(done);
11543 }
11544 
11545 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11546   switch (cond) {
11547     // Note some conditions are synonyms for others
11548     case Assembler::zero:         return Assembler::notZero;
11549     case Assembler::notZero:      return Assembler::zero;
11550     case Assembler::less:         return Assembler::greaterEqual;
11551     case Assembler::lessEqual:    return Assembler::greater;
11552     case Assembler::greater:      return Assembler::lessEqual;
11553     case Assembler::greaterEqual: return Assembler::less;
11554     case Assembler::below:        return Assembler::aboveEqual;
11555     case Assembler::belowEqual:   return Assembler::above;
11556     case Assembler::above:        return Assembler::belowEqual;
11557     case Assembler::aboveEqual:   return Assembler::below;
11558     case Assembler::overflow:     return Assembler::noOverflow;
11559     case Assembler::noOverflow:   return Assembler::overflow;
11560     case Assembler::negative:     return Assembler::positive;
11561     case Assembler::positive:     return Assembler::negative;
11562     case Assembler::parity:       return Assembler::noParity;
11563     case Assembler::noParity:     return Assembler::parity;
11564   }
11565   ShouldNotReachHere(); return Assembler::overflow;
11566 }
11567 
11568 SkipIfEqual::SkipIfEqual(
11569     MacroAssembler* masm, const bool* flag_addr, bool value) {
11570   _masm = masm;
11571   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11572   _masm->jcc(Assembler::equal, _label);
11573 }
11574 
11575 SkipIfEqual::~SkipIfEqual() {
11576   _masm->bind(_label);
11577 }
11578 
11579 // 32-bit Windows has its own fast-path implementation
11580 // of get_thread
11581 #if !defined(WIN32) || defined(_LP64)
11582 
11583 // This is simply a call to Thread::current()
11584 void MacroAssembler::get_thread(Register thread) {
11585   if (thread != rax) {
11586     push(rax);
11587   }
11588   LP64_ONLY(push(rdi);)
11589   LP64_ONLY(push(rsi);)
11590   push(rdx);
11591   push(rcx);
11592 #ifdef _LP64
11593   push(r8);
11594   push(r9);
11595   push(r10);
11596   push(r11);
11597 #endif
11598 
11599   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11600 
11601 #ifdef _LP64
11602   pop(r11);
11603   pop(r10);
11604   pop(r9);
11605   pop(r8);
11606 #endif
11607   pop(rcx);
11608   pop(rdx);
11609   LP64_ONLY(pop(rsi);)
11610   LP64_ONLY(pop(rdi);)
11611   if (thread != rax) {
11612     mov(thread, rax);
11613     pop(rax);
11614   }
11615 }
11616 
11617 #endif
11618 
11619 void MacroAssembler::save_vector_registers() {
11620   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11621   if (UseAVX > 2) {
11622     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11623   }
11624 
11625   if (UseSSE == 1)  {
11626     subptr(rsp, sizeof(jdouble)*8);
11627     for (int n = 0; n < 8; n++) {
11628       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11629     }
11630   } else if (UseSSE >= 2)  {
11631     if (UseAVX > 2) {
11632       push(rbx);
11633       movl(rbx, 0xffff);
11634       kmovwl(k1, rbx);
11635       pop(rbx);
11636     }
11637 #ifdef COMPILER2
11638     if (MaxVectorSize > 16) {
11639       if(UseAVX > 2) {
11640         // Save upper half of ZMM registers
11641         subptr(rsp, 32*num_xmm_regs);
11642         for (int n = 0; n < num_xmm_regs; n++) {
11643           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11644         }
11645       }
11646       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11647       // Save upper half of YMM registers
11648       subptr(rsp, 16*num_xmm_regs);
11649       for (int n = 0; n < num_xmm_regs; n++) {
11650         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11651       }
11652     }
11653 #endif
11654     // Save whole 128bit (16 bytes) XMM registers
11655     subptr(rsp, 16*num_xmm_regs);
11656 #ifdef _LP64
11657     if (VM_Version::supports_evex()) {
11658       for (int n = 0; n < num_xmm_regs; n++) {
11659         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11660       }
11661     } else {
11662       for (int n = 0; n < num_xmm_regs; n++) {
11663         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11664       }
11665     }
11666 #else
11667     for (int n = 0; n < num_xmm_regs; n++) {
11668       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11669     }
11670 #endif
11671   }
11672 }
11673 
11674 void MacroAssembler::restore_vector_registers() {
11675   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11676   if (UseAVX > 2) {
11677     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11678   }
11679   if (UseSSE == 1)  {
11680     for (int n = 0; n < 8; n++) {
11681       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11682     }
11683     addptr(rsp, sizeof(jdouble)*8);
11684   } else if (UseSSE >= 2)  {
11685     // Restore whole 128bit (16 bytes) XMM registers
11686 #ifdef _LP64
11687   if (VM_Version::supports_evex()) {
11688     for (int n = 0; n < num_xmm_regs; n++) {
11689       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11690     }
11691   } else {
11692     for (int n = 0; n < num_xmm_regs; n++) {
11693       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11694     }
11695   }
11696 #else
11697   for (int n = 0; n < num_xmm_regs; n++) {
11698     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11699   }
11700 #endif
11701     addptr(rsp, 16*num_xmm_regs);
11702 
11703 #ifdef COMPILER2
11704     if (MaxVectorSize > 16) {
11705       // Restore upper half of YMM registers.
11706       for (int n = 0; n < num_xmm_regs; n++) {
11707         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11708       }
11709       addptr(rsp, 16*num_xmm_regs);
11710       if(UseAVX > 2) {
11711         for (int n = 0; n < num_xmm_regs; n++) {
11712           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11713         }
11714         addptr(rsp, 32*num_xmm_regs);
11715       }
11716     }
11717 #endif
11718   }
11719 }