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/jvm.h"
  36 #include "prims/methodHandles.hpp"
  37 #include "runtime/biasedLocking.hpp"
  38 #include "runtime/interfaceSupport.hpp"
  39 #include "runtime/objectMonitor.hpp"
  40 #include "runtime/os.hpp"
  41 #include "runtime/safepoint.hpp"
  42 #include "runtime/safepointMechanism.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "runtime/stubRoutines.hpp"
  45 #include "runtime/thread.hpp"
  46 #include "utilities/macros.hpp"
  47 #if INCLUDE_ALL_GCS
  48 #include "gc/g1/g1CollectedHeap.inline.hpp"
  49 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  50 #include "gc/g1/heapRegion.hpp"
  51 #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   vzeroupper();
 770 }
 771 
 772 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 773                                          Register last_java_fp,
 774                                          address  last_java_pc) {
 775   vzeroupper();
 776   // determine last_java_sp register
 777   if (!last_java_sp->is_valid()) {
 778     last_java_sp = rsp;
 779   }
 780 
 781   // last_java_fp is optional
 782   if (last_java_fp->is_valid()) {
 783     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 784            last_java_fp);
 785   }
 786 
 787   // last_java_pc is optional
 788   if (last_java_pc != NULL) {
 789     Address java_pc(r15_thread,
 790                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 791     lea(rscratch1, InternalAddress(last_java_pc));
 792     movptr(java_pc, rscratch1);
 793   }
 794 
 795   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 796 }
 797 
 798 static void pass_arg0(MacroAssembler* masm, Register arg) {
 799   if (c_rarg0 != arg ) {
 800     masm->mov(c_rarg0, arg);
 801   }
 802 }
 803 
 804 static void pass_arg1(MacroAssembler* masm, Register arg) {
 805   if (c_rarg1 != arg ) {
 806     masm->mov(c_rarg1, arg);
 807   }
 808 }
 809 
 810 static void pass_arg2(MacroAssembler* masm, Register arg) {
 811   if (c_rarg2 != arg ) {
 812     masm->mov(c_rarg2, arg);
 813   }
 814 }
 815 
 816 static void pass_arg3(MacroAssembler* masm, Register arg) {
 817   if (c_rarg3 != arg ) {
 818     masm->mov(c_rarg3, arg);
 819   }
 820 }
 821 
 822 void MacroAssembler::stop(const char* msg) {
 823   address rip = pc();
 824   pusha(); // get regs on stack
 825   lea(c_rarg0, ExternalAddress((address) msg));
 826   lea(c_rarg1, InternalAddress(rip));
 827   movq(c_rarg2, rsp); // pass pointer to regs array
 828   andq(rsp, -16); // align stack as required by ABI
 829   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 830   hlt();
 831 }
 832 
 833 void MacroAssembler::warn(const char* msg) {
 834   push(rbp);
 835   movq(rbp, rsp);
 836   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 837   push_CPU_state();   // keeps alignment at 16 bytes
 838   lea(c_rarg0, ExternalAddress((address) msg));
 839   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 840   pop_CPU_state();
 841   mov(rsp, rbp);
 842   pop(rbp);
 843 }
 844 
 845 void MacroAssembler::print_state() {
 846   address rip = pc();
 847   pusha();            // get regs on stack
 848   push(rbp);
 849   movq(rbp, rsp);
 850   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 851   push_CPU_state();   // keeps alignment at 16 bytes
 852 
 853   lea(c_rarg0, InternalAddress(rip));
 854   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 855   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 856 
 857   pop_CPU_state();
 858   mov(rsp, rbp);
 859   pop(rbp);
 860   popa();
 861 }
 862 
 863 #ifndef PRODUCT
 864 extern "C" void findpc(intptr_t x);
 865 #endif
 866 
 867 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 868   // In order to get locks to work, we need to fake a in_VM state
 869   if (ShowMessageBoxOnError) {
 870     JavaThread* thread = JavaThread::current();
 871     JavaThreadState saved_state = thread->thread_state();
 872     thread->set_thread_state(_thread_in_vm);
 873 #ifndef PRODUCT
 874     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 875       ttyLocker ttyl;
 876       BytecodeCounter::print();
 877     }
 878 #endif
 879     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 880     // XXX correct this offset for amd64
 881     // This is the value of eip which points to where verify_oop will return.
 882     if (os::message_box(msg, "Execution stopped, print registers?")) {
 883       print_state64(pc, regs);
 884       BREAKPOINT;
 885       assert(false, "start up GDB");
 886     }
 887     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 888   } else {
 889     ttyLocker ttyl;
 890     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 891                     msg);
 892     assert(false, "DEBUG MESSAGE: %s", msg);
 893   }
 894 }
 895 
 896 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 897   ttyLocker ttyl;
 898   FlagSetting fs(Debugging, true);
 899   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 900 #ifndef PRODUCT
 901   tty->cr();
 902   findpc(pc);
 903   tty->cr();
 904 #endif
 905 #define PRINT_REG(rax, value) \
 906   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 907   PRINT_REG(rax, regs[15]);
 908   PRINT_REG(rbx, regs[12]);
 909   PRINT_REG(rcx, regs[14]);
 910   PRINT_REG(rdx, regs[13]);
 911   PRINT_REG(rdi, regs[8]);
 912   PRINT_REG(rsi, regs[9]);
 913   PRINT_REG(rbp, regs[10]);
 914   PRINT_REG(rsp, regs[11]);
 915   PRINT_REG(r8 , regs[7]);
 916   PRINT_REG(r9 , regs[6]);
 917   PRINT_REG(r10, regs[5]);
 918   PRINT_REG(r11, regs[4]);
 919   PRINT_REG(r12, regs[3]);
 920   PRINT_REG(r13, regs[2]);
 921   PRINT_REG(r14, regs[1]);
 922   PRINT_REG(r15, regs[0]);
 923 #undef PRINT_REG
 924   // Print some words near top of staack.
 925   int64_t* rsp = (int64_t*) regs[11];
 926   int64_t* dump_sp = rsp;
 927   for (int col1 = 0; col1 < 8; col1++) {
 928     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 929     os::print_location(tty, *dump_sp++);
 930   }
 931   for (int row = 0; row < 25; row++) {
 932     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 933     for (int col = 0; col < 4; col++) {
 934       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 935     }
 936     tty->cr();
 937   }
 938   // Print some instructions around pc:
 939   Disassembler::decode((address)pc-64, (address)pc);
 940   tty->print_cr("--------");
 941   Disassembler::decode((address)pc, (address)pc+32);
 942 }
 943 
 944 #endif // _LP64
 945 
 946 // Now versions that are common to 32/64 bit
 947 
 948 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 949   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 950 }
 951 
 952 void MacroAssembler::addptr(Register dst, Register src) {
 953   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 954 }
 955 
 956 void MacroAssembler::addptr(Address dst, Register src) {
 957   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 958 }
 959 
 960 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 961   if (reachable(src)) {
 962     Assembler::addsd(dst, as_Address(src));
 963   } else {
 964     lea(rscratch1, src);
 965     Assembler::addsd(dst, Address(rscratch1, 0));
 966   }
 967 }
 968 
 969 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 970   if (reachable(src)) {
 971     addss(dst, as_Address(src));
 972   } else {
 973     lea(rscratch1, src);
 974     addss(dst, Address(rscratch1, 0));
 975   }
 976 }
 977 
 978 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 979   if (reachable(src)) {
 980     Assembler::addpd(dst, as_Address(src));
 981   } else {
 982     lea(rscratch1, src);
 983     Assembler::addpd(dst, Address(rscratch1, 0));
 984   }
 985 }
 986 
 987 void MacroAssembler::align(int modulus) {
 988   align(modulus, offset());
 989 }
 990 
 991 void MacroAssembler::align(int modulus, int target) {
 992   if (target % modulus != 0) {
 993     nop(modulus - (target % modulus));
 994   }
 995 }
 996 
 997 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 998   // Used in sign-masking with aligned address.
 999   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1000   if (reachable(src)) {
1001     Assembler::andpd(dst, as_Address(src));
1002   } else {
1003     lea(rscratch1, src);
1004     Assembler::andpd(dst, Address(rscratch1, 0));
1005   }
1006 }
1007 
1008 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1009   // Used in sign-masking with aligned address.
1010   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1011   if (reachable(src)) {
1012     Assembler::andps(dst, as_Address(src));
1013   } else {
1014     lea(rscratch1, src);
1015     Assembler::andps(dst, Address(rscratch1, 0));
1016   }
1017 }
1018 
1019 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1020   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1021 }
1022 
1023 void MacroAssembler::atomic_incl(Address counter_addr) {
1024   if (os::is_MP())
1025     lock();
1026   incrementl(counter_addr);
1027 }
1028 
1029 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1030   if (reachable(counter_addr)) {
1031     atomic_incl(as_Address(counter_addr));
1032   } else {
1033     lea(scr, counter_addr);
1034     atomic_incl(Address(scr, 0));
1035   }
1036 }
1037 
1038 #ifdef _LP64
1039 void MacroAssembler::atomic_incq(Address counter_addr) {
1040   if (os::is_MP())
1041     lock();
1042   incrementq(counter_addr);
1043 }
1044 
1045 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1046   if (reachable(counter_addr)) {
1047     atomic_incq(as_Address(counter_addr));
1048   } else {
1049     lea(scr, counter_addr);
1050     atomic_incq(Address(scr, 0));
1051   }
1052 }
1053 #endif
1054 
1055 // Writes to stack successive pages until offset reached to check for
1056 // stack overflow + shadow pages.  This clobbers tmp.
1057 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1058   movptr(tmp, rsp);
1059   // Bang stack for total size given plus shadow page size.
1060   // Bang one page at a time because large size can bang beyond yellow and
1061   // red zones.
1062   Label loop;
1063   bind(loop);
1064   movl(Address(tmp, (-os::vm_page_size())), size );
1065   subptr(tmp, os::vm_page_size());
1066   subl(size, os::vm_page_size());
1067   jcc(Assembler::greater, loop);
1068 
1069   // Bang down shadow pages too.
1070   // At this point, (tmp-0) is the last address touched, so don't
1071   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1072   // was post-decremented.)  Skip this address by starting at i=1, and
1073   // touch a few more pages below.  N.B.  It is important to touch all
1074   // the way down including all pages in the shadow zone.
1075   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1076     // this could be any sized move but this is can be a debugging crumb
1077     // so the bigger the better.
1078     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1079   }
1080 }
1081 
1082 void MacroAssembler::reserved_stack_check() {
1083     // testing if reserved zone needs to be enabled
1084     Label no_reserved_zone_enabling;
1085     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1086     NOT_LP64(get_thread(rsi);)
1087 
1088     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1089     jcc(Assembler::below, no_reserved_zone_enabling);
1090 
1091     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1092     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1093     should_not_reach_here();
1094 
1095     bind(no_reserved_zone_enabling);
1096 }
1097 
1098 int MacroAssembler::biased_locking_enter(Register lock_reg,
1099                                          Register obj_reg,
1100                                          Register swap_reg,
1101                                          Register tmp_reg,
1102                                          bool swap_reg_contains_mark,
1103                                          Label& done,
1104                                          Label* slow_case,
1105                                          BiasedLockingCounters* counters) {
1106   assert(UseBiasedLocking, "why call this otherwise?");
1107   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1108   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1109   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1110   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1111   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1112   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
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(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(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   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1299   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1300   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1301   jcc(Assembler::equal, done);
1302 }
1303 
1304 #ifdef COMPILER2
1305 
1306 #if INCLUDE_RTM_OPT
1307 
1308 // Update rtm_counters based on abort status
1309 // input: abort_status
1310 //        rtm_counters (RTMLockingCounters*)
1311 // flags are killed
1312 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1313 
1314   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1315   if (PrintPreciseRTMLockingStatistics) {
1316     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1317       Label check_abort;
1318       testl(abort_status, (1<<i));
1319       jccb(Assembler::equal, check_abort);
1320       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1321       bind(check_abort);
1322     }
1323   }
1324 }
1325 
1326 // Branch if (random & (count-1) != 0), count is 2^n
1327 // tmp, scr and flags are killed
1328 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1329   assert(tmp == rax, "");
1330   assert(scr == rdx, "");
1331   rdtsc(); // modifies EDX:EAX
1332   andptr(tmp, count-1);
1333   jccb(Assembler::notZero, brLabel);
1334 }
1335 
1336 // Perform abort ratio calculation, set no_rtm bit if high ratio
1337 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1338 // tmpReg, rtm_counters_Reg and flags are killed
1339 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1340                                                  Register rtm_counters_Reg,
1341                                                  RTMLockingCounters* rtm_counters,
1342                                                  Metadata* method_data) {
1343   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1344 
1345   if (RTMLockingCalculationDelay > 0) {
1346     // Delay calculation
1347     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1348     testptr(tmpReg, tmpReg);
1349     jccb(Assembler::equal, L_done);
1350   }
1351   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1352   //   Aborted transactions = abort_count * 100
1353   //   All transactions = total_count *  RTMTotalCountIncrRate
1354   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1355 
1356   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1357   cmpptr(tmpReg, RTMAbortThreshold);
1358   jccb(Assembler::below, L_check_always_rtm2);
1359   imulptr(tmpReg, tmpReg, 100);
1360 
1361   Register scrReg = rtm_counters_Reg;
1362   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1363   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1364   imulptr(scrReg, scrReg, RTMAbortRatio);
1365   cmpptr(tmpReg, scrReg);
1366   jccb(Assembler::below, L_check_always_rtm1);
1367   if (method_data != NULL) {
1368     // set rtm_state to "no rtm" in MDO
1369     mov_metadata(tmpReg, method_data);
1370     if (os::is_MP()) {
1371       lock();
1372     }
1373     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1374   }
1375   jmpb(L_done);
1376   bind(L_check_always_rtm1);
1377   // Reload RTMLockingCounters* address
1378   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1379   bind(L_check_always_rtm2);
1380   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1381   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1382   jccb(Assembler::below, L_done);
1383   if (method_data != NULL) {
1384     // set rtm_state to "always rtm" in MDO
1385     mov_metadata(tmpReg, method_data);
1386     if (os::is_MP()) {
1387       lock();
1388     }
1389     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1390   }
1391   bind(L_done);
1392 }
1393 
1394 // Update counters and perform abort ratio calculation
1395 // input:  abort_status_Reg
1396 // rtm_counters_Reg, flags are killed
1397 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1398                                    Register rtm_counters_Reg,
1399                                    RTMLockingCounters* rtm_counters,
1400                                    Metadata* method_data,
1401                                    bool profile_rtm) {
1402 
1403   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1404   // update rtm counters based on rax value at abort
1405   // reads abort_status_Reg, updates flags
1406   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1407   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1408   if (profile_rtm) {
1409     // Save abort status because abort_status_Reg is used by following code.
1410     if (RTMRetryCount > 0) {
1411       push(abort_status_Reg);
1412     }
1413     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1414     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1415     // restore abort status
1416     if (RTMRetryCount > 0) {
1417       pop(abort_status_Reg);
1418     }
1419   }
1420 }
1421 
1422 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1423 // inputs: retry_count_Reg
1424 //       : abort_status_Reg
1425 // output: retry_count_Reg decremented by 1
1426 // flags are killed
1427 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1428   Label doneRetry;
1429   assert(abort_status_Reg == rax, "");
1430   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1431   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1432   // if reason is in 0x6 and retry count != 0 then retry
1433   andptr(abort_status_Reg, 0x6);
1434   jccb(Assembler::zero, doneRetry);
1435   testl(retry_count_Reg, retry_count_Reg);
1436   jccb(Assembler::zero, doneRetry);
1437   pause();
1438   decrementl(retry_count_Reg);
1439   jmp(retryLabel);
1440   bind(doneRetry);
1441 }
1442 
1443 // Spin and retry if lock is busy,
1444 // inputs: box_Reg (monitor address)
1445 //       : retry_count_Reg
1446 // output: retry_count_Reg decremented by 1
1447 //       : clear z flag if retry count exceeded
1448 // tmp_Reg, scr_Reg, flags are killed
1449 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1450                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1451   Label SpinLoop, SpinExit, doneRetry;
1452   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1453 
1454   testl(retry_count_Reg, retry_count_Reg);
1455   jccb(Assembler::zero, doneRetry);
1456   decrementl(retry_count_Reg);
1457   movptr(scr_Reg, RTMSpinLoopCount);
1458 
1459   bind(SpinLoop);
1460   pause();
1461   decrementl(scr_Reg);
1462   jccb(Assembler::lessEqual, SpinExit);
1463   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1464   testptr(tmp_Reg, tmp_Reg);
1465   jccb(Assembler::notZero, SpinLoop);
1466 
1467   bind(SpinExit);
1468   jmp(retryLabel);
1469   bind(doneRetry);
1470   incrementl(retry_count_Reg); // clear z flag
1471 }
1472 
1473 // Use RTM for normal stack locks
1474 // Input: objReg (object to lock)
1475 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1476                                        Register retry_on_abort_count_Reg,
1477                                        RTMLockingCounters* stack_rtm_counters,
1478                                        Metadata* method_data, bool profile_rtm,
1479                                        Label& DONE_LABEL, Label& IsInflated) {
1480   assert(UseRTMForStackLocks, "why call this otherwise?");
1481   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1482   assert(tmpReg == rax, "");
1483   assert(scrReg == rdx, "");
1484   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1485 
1486   if (RTMRetryCount > 0) {
1487     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1488     bind(L_rtm_retry);
1489   }
1490   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1491   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1492   jcc(Assembler::notZero, IsInflated);
1493 
1494   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1495     Label L_noincrement;
1496     if (RTMTotalCountIncrRate > 1) {
1497       // tmpReg, scrReg and flags are killed
1498       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1499     }
1500     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1501     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1502     bind(L_noincrement);
1503   }
1504   xbegin(L_on_abort);
1505   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1506   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1507   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1508   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1509 
1510   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1511   if (UseRTMXendForLockBusy) {
1512     xend();
1513     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1514     jmp(L_decrement_retry);
1515   }
1516   else {
1517     xabort(0);
1518   }
1519   bind(L_on_abort);
1520   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1521     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1522   }
1523   bind(L_decrement_retry);
1524   if (RTMRetryCount > 0) {
1525     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1526     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1527   }
1528 }
1529 
1530 // Use RTM for inflating locks
1531 // inputs: objReg (object to lock)
1532 //         boxReg (on-stack box address (displaced header location) - KILLED)
1533 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1534 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1535                                           Register scrReg, Register retry_on_busy_count_Reg,
1536                                           Register retry_on_abort_count_Reg,
1537                                           RTMLockingCounters* rtm_counters,
1538                                           Metadata* method_data, bool profile_rtm,
1539                                           Label& DONE_LABEL) {
1540   assert(UseRTMLocking, "why call this otherwise?");
1541   assert(tmpReg == rax, "");
1542   assert(scrReg == rdx, "");
1543   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1544   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1545 
1546   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1547   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1548   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1549 
1550   if (RTMRetryCount > 0) {
1551     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1552     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1553     bind(L_rtm_retry);
1554   }
1555   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1556     Label L_noincrement;
1557     if (RTMTotalCountIncrRate > 1) {
1558       // tmpReg, scrReg and flags are killed
1559       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1560     }
1561     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1562     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1563     bind(L_noincrement);
1564   }
1565   xbegin(L_on_abort);
1566   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1567   movptr(tmpReg, Address(tmpReg, owner_offset));
1568   testptr(tmpReg, tmpReg);
1569   jcc(Assembler::zero, DONE_LABEL);
1570   if (UseRTMXendForLockBusy) {
1571     xend();
1572     jmp(L_decrement_retry);
1573   }
1574   else {
1575     xabort(0);
1576   }
1577   bind(L_on_abort);
1578   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1579   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1580     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1581   }
1582   if (RTMRetryCount > 0) {
1583     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1584     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1585   }
1586 
1587   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1588   testptr(tmpReg, tmpReg) ;
1589   jccb(Assembler::notZero, L_decrement_retry) ;
1590 
1591   // Appears unlocked - try to swing _owner from null to non-null.
1592   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1593 #ifdef _LP64
1594   Register threadReg = r15_thread;
1595 #else
1596   get_thread(scrReg);
1597   Register threadReg = scrReg;
1598 #endif
1599   if (os::is_MP()) {
1600     lock();
1601   }
1602   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1603 
1604   if (RTMRetryCount > 0) {
1605     // success done else retry
1606     jccb(Assembler::equal, DONE_LABEL) ;
1607     bind(L_decrement_retry);
1608     // Spin and retry if lock is busy.
1609     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1610   }
1611   else {
1612     bind(L_decrement_retry);
1613   }
1614 }
1615 
1616 #endif //  INCLUDE_RTM_OPT
1617 
1618 // Fast_Lock and Fast_Unlock used by C2
1619 
1620 // Because the transitions from emitted code to the runtime
1621 // monitorenter/exit helper stubs are so slow it's critical that
1622 // we inline both the stack-locking fast-path and the inflated fast path.
1623 //
1624 // See also: cmpFastLock and cmpFastUnlock.
1625 //
1626 // What follows is a specialized inline transliteration of the code
1627 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1628 // another option would be to emit TrySlowEnter and TrySlowExit methods
1629 // at startup-time.  These methods would accept arguments as
1630 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1631 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1632 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1633 // In practice, however, the # of lock sites is bounded and is usually small.
1634 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1635 // if the processor uses simple bimodal branch predictors keyed by EIP
1636 // Since the helper routines would be called from multiple synchronization
1637 // sites.
1638 //
1639 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1640 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1641 // to those specialized methods.  That'd give us a mostly platform-independent
1642 // implementation that the JITs could optimize and inline at their pleasure.
1643 // Done correctly, the only time we'd need to cross to native could would be
1644 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1645 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1646 // (b) explicit barriers or fence operations.
1647 //
1648 // TODO:
1649 //
1650 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1651 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1652 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1653 //    the lock operators would typically be faster than reifying Self.
1654 //
1655 // *  Ideally I'd define the primitives as:
1656 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1657 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1658 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1659 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1660 //    Furthermore the register assignments are overconstrained, possibly resulting in
1661 //    sub-optimal code near the synchronization site.
1662 //
1663 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1664 //    Alternately, use a better sp-proximity test.
1665 //
1666 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1667 //    Either one is sufficient to uniquely identify a thread.
1668 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1669 //
1670 // *  Intrinsify notify() and notifyAll() for the common cases where the
1671 //    object is locked by the calling thread but the waitlist is empty.
1672 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1673 //
1674 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1675 //    But beware of excessive branch density on AMD Opterons.
1676 //
1677 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1678 //    or failure of the fast-path.  If the fast-path fails then we pass
1679 //    control to the slow-path, typically in C.  In Fast_Lock and
1680 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1681 //    will emit a conditional branch immediately after the node.
1682 //    So we have branches to branches and lots of ICC.ZF games.
1683 //    Instead, it might be better to have C2 pass a "FailureLabel"
1684 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1685 //    will drop through the node.  ICC.ZF is undefined at exit.
1686 //    In the case of failure, the node will branch directly to the
1687 //    FailureLabel
1688 
1689 
1690 // obj: object to lock
1691 // box: on-stack box address (displaced header location) - KILLED
1692 // rax,: tmp -- KILLED
1693 // scr: tmp -- KILLED
1694 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1695                                Register scrReg, Register cx1Reg, Register cx2Reg,
1696                                BiasedLockingCounters* counters,
1697                                RTMLockingCounters* rtm_counters,
1698                                RTMLockingCounters* stack_rtm_counters,
1699                                Metadata* method_data,
1700                                bool use_rtm, bool profile_rtm) {
1701   // Ensure the register assignments are disjoint
1702   assert(tmpReg == rax, "");
1703 
1704   if (use_rtm) {
1705     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1706   } else {
1707     assert(cx1Reg == noreg, "");
1708     assert(cx2Reg == noreg, "");
1709     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1710   }
1711 
1712   if (counters != NULL) {
1713     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1714   }
1715   if (EmitSync & 1) {
1716       // set box->dhw = markOopDesc::unused_mark()
1717       // Force all sync thru slow-path: slow_enter() and slow_exit()
1718       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1719       cmpptr (rsp, (int32_t)NULL_WORD);
1720   } else {
1721     // Possible cases that we'll encounter in fast_lock
1722     // ------------------------------------------------
1723     // * Inflated
1724     //    -- unlocked
1725     //    -- Locked
1726     //       = by self
1727     //       = by other
1728     // * biased
1729     //    -- by Self
1730     //    -- by other
1731     // * neutral
1732     // * stack-locked
1733     //    -- by self
1734     //       = sp-proximity test hits
1735     //       = sp-proximity test generates false-negative
1736     //    -- by other
1737     //
1738 
1739     Label IsInflated, DONE_LABEL;
1740 
1741     // it's stack-locked, biased or neutral
1742     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1743     // order to reduce the number of conditional branches in the most common cases.
1744     // Beware -- there's a subtle invariant that fetch of the markword
1745     // at [FETCH], below, will never observe a biased encoding (*101b).
1746     // If this invariant is not held we risk exclusion (safety) failure.
1747     if (UseBiasedLocking && !UseOptoBiasInlining) {
1748       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1749     }
1750 
1751 #if INCLUDE_RTM_OPT
1752     if (UseRTMForStackLocks && use_rtm) {
1753       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1754                         stack_rtm_counters, method_data, profile_rtm,
1755                         DONE_LABEL, IsInflated);
1756     }
1757 #endif // INCLUDE_RTM_OPT
1758 
1759     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1760     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1761     jccb(Assembler::notZero, IsInflated);
1762 
1763     // Attempt stack-locking ...
1764     orptr (tmpReg, markOopDesc::unlocked_value);
1765     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1766     if (os::is_MP()) {
1767       lock();
1768     }
1769     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1770     if (counters != NULL) {
1771       cond_inc32(Assembler::equal,
1772                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1773     }
1774     jcc(Assembler::equal, DONE_LABEL);           // Success
1775 
1776     // Recursive locking.
1777     // The object is stack-locked: markword contains stack pointer to BasicLock.
1778     // Locked by current thread if difference with current SP is less than one page.
1779     subptr(tmpReg, rsp);
1780     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1781     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1782     movptr(Address(boxReg, 0), tmpReg);
1783     if (counters != NULL) {
1784       cond_inc32(Assembler::equal,
1785                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1786     }
1787     jmp(DONE_LABEL);
1788 
1789     bind(IsInflated);
1790     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1791 
1792 #if INCLUDE_RTM_OPT
1793     // Use the same RTM locking code in 32- and 64-bit VM.
1794     if (use_rtm) {
1795       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1796                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1797     } else {
1798 #endif // INCLUDE_RTM_OPT
1799 
1800 #ifndef _LP64
1801     // The object is inflated.
1802 
1803     // boxReg refers to the on-stack BasicLock in the current frame.
1804     // We'd like to write:
1805     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1806     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1807     // additional latency as we have another ST in the store buffer that must drain.
1808 
1809     if (EmitSync & 8192) {
1810        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1811        get_thread (scrReg);
1812        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1813        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1814        if (os::is_MP()) {
1815          lock();
1816        }
1817        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1818     } else
1819     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1820        // register juggle because we need tmpReg for cmpxchgptr below
1821        movptr(scrReg, boxReg);
1822        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1823 
1824        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1825        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1826           // prefetchw [eax + Offset(_owner)-2]
1827           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1828        }
1829 
1830        if ((EmitSync & 64) == 0) {
1831          // Optimistic form: consider XORL tmpReg,tmpReg
1832          movptr(tmpReg, NULL_WORD);
1833        } else {
1834          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1835          // Test-And-CAS instead of CAS
1836          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1837          testptr(tmpReg, tmpReg);                   // Locked ?
1838          jccb  (Assembler::notZero, DONE_LABEL);
1839        }
1840 
1841        // Appears unlocked - try to swing _owner from null to non-null.
1842        // Ideally, I'd manifest "Self" with get_thread and then attempt
1843        // to CAS the register containing Self into m->Owner.
1844        // But we don't have enough registers, so instead we can either try to CAS
1845        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1846        // we later store "Self" into m->Owner.  Transiently storing a stack address
1847        // (rsp or the address of the box) into  m->owner is harmless.
1848        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1849        if (os::is_MP()) {
1850          lock();
1851        }
1852        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1853        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1854        // If we weren't able to swing _owner from NULL to the BasicLock
1855        // then take the slow path.
1856        jccb  (Assembler::notZero, DONE_LABEL);
1857        // update _owner from BasicLock to thread
1858        get_thread (scrReg);                    // beware: clobbers ICCs
1859        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1860        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1861 
1862        // If the CAS fails we can either retry or pass control to the slow-path.
1863        // We use the latter tactic.
1864        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1865        // If the CAS was successful ...
1866        //   Self has acquired the lock
1867        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1868        // Intentional fall-through into DONE_LABEL ...
1869     } else {
1870        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1871        movptr(boxReg, tmpReg);
1872 
1873        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1874        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1875           // prefetchw [eax + Offset(_owner)-2]
1876           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1877        }
1878 
1879        if ((EmitSync & 64) == 0) {
1880          // Optimistic form
1881          xorptr  (tmpReg, tmpReg);
1882        } else {
1883          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1884          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1885          testptr(tmpReg, tmpReg);                   // Locked ?
1886          jccb  (Assembler::notZero, DONE_LABEL);
1887        }
1888 
1889        // Appears unlocked - try to swing _owner from null to non-null.
1890        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1891        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1892        get_thread (scrReg);
1893        if (os::is_MP()) {
1894          lock();
1895        }
1896        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1897 
1898        // If the CAS fails we can either retry or pass control to the slow-path.
1899        // We use the latter tactic.
1900        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1901        // If the CAS was successful ...
1902        //   Self has acquired the lock
1903        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1904        // Intentional fall-through into DONE_LABEL ...
1905     }
1906 #else // _LP64
1907     // It's inflated
1908     movq(scrReg, tmpReg);
1909     xorq(tmpReg, tmpReg);
1910 
1911     if (os::is_MP()) {
1912       lock();
1913     }
1914     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1915     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1916     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1917     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1918     // Intentional fall-through into DONE_LABEL ...
1919     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1920 #endif // _LP64
1921 #if INCLUDE_RTM_OPT
1922     } // use_rtm()
1923 #endif
1924     // DONE_LABEL is a hot target - we'd really like to place it at the
1925     // start of cache line by padding with NOPs.
1926     // See the AMD and Intel software optimization manuals for the
1927     // most efficient "long" NOP encodings.
1928     // Unfortunately none of our alignment mechanisms suffice.
1929     bind(DONE_LABEL);
1930 
1931     // At DONE_LABEL the icc ZFlag is set as follows ...
1932     // Fast_Unlock uses the same protocol.
1933     // ZFlag == 1 -> Success
1934     // ZFlag == 0 -> Failure - force control through the slow-path
1935   }
1936 }
1937 
1938 // obj: object to unlock
1939 // box: box address (displaced header location), killed.  Must be EAX.
1940 // tmp: killed, cannot be obj nor box.
1941 //
1942 // Some commentary on balanced locking:
1943 //
1944 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1945 // Methods that don't have provably balanced locking are forced to run in the
1946 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1947 // The interpreter provides two properties:
1948 // I1:  At return-time the interpreter automatically and quietly unlocks any
1949 //      objects acquired the current activation (frame).  Recall that the
1950 //      interpreter maintains an on-stack list of locks currently held by
1951 //      a frame.
1952 // I2:  If a method attempts to unlock an object that is not held by the
1953 //      the frame the interpreter throws IMSX.
1954 //
1955 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1956 // B() doesn't have provably balanced locking so it runs in the interpreter.
1957 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1958 // is still locked by A().
1959 //
1960 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1961 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1962 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1963 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1964 // Arguably given that the spec legislates the JNI case as undefined our implementation
1965 // could reasonably *avoid* checking owner in Fast_Unlock().
1966 // In the interest of performance we elide m->Owner==Self check in unlock.
1967 // A perfectly viable alternative is to elide the owner check except when
1968 // Xcheck:jni is enabled.
1969 
1970 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1971   assert(boxReg == rax, "");
1972   assert_different_registers(objReg, boxReg, tmpReg);
1973 
1974   if (EmitSync & 4) {
1975     // Disable - inhibit all inlining.  Force control through the slow-path
1976     cmpptr (rsp, 0);
1977   } else {
1978     Label DONE_LABEL, Stacked, CheckSucc;
1979 
1980     // Critically, the biased locking test must have precedence over
1981     // and appear before the (box->dhw == 0) recursive stack-lock test.
1982     if (UseBiasedLocking && !UseOptoBiasInlining) {
1983        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1984     }
1985 
1986 #if INCLUDE_RTM_OPT
1987     if (UseRTMForStackLocks && use_rtm) {
1988       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1989       Label L_regular_unlock;
1990       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1991       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1992       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1993       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1994       xend();                                       // otherwise end...
1995       jmp(DONE_LABEL);                              // ... and we're done
1996       bind(L_regular_unlock);
1997     }
1998 #endif
1999 
2000     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2001     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2002     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2003     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2004     jccb  (Assembler::zero, Stacked);
2005 
2006     // It's inflated.
2007 #if INCLUDE_RTM_OPT
2008     if (use_rtm) {
2009       Label L_regular_inflated_unlock;
2010       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2011       movptr(boxReg, Address(tmpReg, owner_offset));
2012       testptr(boxReg, boxReg);
2013       jccb(Assembler::notZero, L_regular_inflated_unlock);
2014       xend();
2015       jmpb(DONE_LABEL);
2016       bind(L_regular_inflated_unlock);
2017     }
2018 #endif
2019 
2020     // Despite our balanced locking property we still check that m->_owner == Self
2021     // as java routines or native JNI code called by this thread might
2022     // have released the lock.
2023     // Refer to the comments in synchronizer.cpp for how we might encode extra
2024     // state in _succ so we can avoid fetching EntryList|cxq.
2025     //
2026     // I'd like to add more cases in fast_lock() and fast_unlock() --
2027     // such as recursive enter and exit -- but we have to be wary of
2028     // I$ bloat, T$ effects and BP$ effects.
2029     //
2030     // If there's no contention try a 1-0 exit.  That is, exit without
2031     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2032     // we detect and recover from the race that the 1-0 exit admits.
2033     //
2034     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2035     // before it STs null into _owner, releasing the lock.  Updates
2036     // to data protected by the critical section must be visible before
2037     // we drop the lock (and thus before any other thread could acquire
2038     // the lock and observe the fields protected by the lock).
2039     // IA32's memory-model is SPO, so STs are ordered with respect to
2040     // each other and there's no need for an explicit barrier (fence).
2041     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2042 #ifndef _LP64
2043     get_thread (boxReg);
2044     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2045       // prefetchw [ebx + Offset(_owner)-2]
2046       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2047     }
2048 
2049     // Note that we could employ various encoding schemes to reduce
2050     // the number of loads below (currently 4) to just 2 or 3.
2051     // Refer to the comments in synchronizer.cpp.
2052     // In practice the chain of fetches doesn't seem to impact performance, however.
2053     xorptr(boxReg, boxReg);
2054     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2055        // Attempt to reduce branch density - AMD's branch predictor.
2056        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2057        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2058        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2059        jccb  (Assembler::notZero, DONE_LABEL);
2060        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2061        jmpb  (DONE_LABEL);
2062     } else {
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2064        jccb  (Assembler::notZero, DONE_LABEL);
2065        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2066        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2067        jccb  (Assembler::notZero, CheckSucc);
2068        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2069        jmpb  (DONE_LABEL);
2070     }
2071 
2072     // The Following code fragment (EmitSync & 65536) improves the performance of
2073     // contended applications and contended synchronization microbenchmarks.
2074     // Unfortunately the emission of the code - even though not executed - causes regressions
2075     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2076     // with an equal number of never-executed NOPs results in the same regression.
2077     // We leave it off by default.
2078 
2079     if ((EmitSync & 65536) != 0) {
2080        Label LSuccess, LGoSlowPath ;
2081 
2082        bind  (CheckSucc);
2083 
2084        // Optional pre-test ... it's safe to elide this
2085        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2086        jccb(Assembler::zero, LGoSlowPath);
2087 
2088        // We have a classic Dekker-style idiom:
2089        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2090        // There are a number of ways to implement the barrier:
2091        // (1) lock:andl &m->_owner, 0
2092        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2093        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2094        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2095        // (2) If supported, an explicit MFENCE is appealing.
2096        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2097        //     particularly if the write-buffer is full as might be the case if
2098        //     if stores closely precede the fence or fence-equivalent instruction.
2099        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2100        //     as the situation has changed with Nehalem and Shanghai.
2101        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2102        //     The $lines underlying the top-of-stack should be in M-state.
2103        //     The locked add instruction is serializing, of course.
2104        // (4) Use xchg, which is serializing
2105        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2106        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2107        //     The integer condition codes will tell us if succ was 0.
2108        //     Since _succ and _owner should reside in the same $line and
2109        //     we just stored into _owner, it's likely that the $line
2110        //     remains in M-state for the lock:orl.
2111        //
2112        // We currently use (3), although it's likely that switching to (2)
2113        // is correct for the future.
2114 
2115        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2116        if (os::is_MP()) {
2117          lock(); addptr(Address(rsp, 0), 0);
2118        }
2119        // Ratify _succ remains non-null
2120        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2121        jccb  (Assembler::notZero, LSuccess);
2122 
2123        xorptr(boxReg, boxReg);                  // box is really EAX
2124        if (os::is_MP()) { lock(); }
2125        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2126        // There's no successor so we tried to regrab the lock with the
2127        // placeholder value. If that didn't work, then another thread
2128        // grabbed the lock so we're done (and exit was a success).
2129        jccb  (Assembler::notEqual, LSuccess);
2130        // Since we're low on registers we installed rsp as a placeholding in _owner.
2131        // Now install Self over rsp.  This is safe as we're transitioning from
2132        // non-null to non=null
2133        get_thread (boxReg);
2134        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2135        // Intentional fall-through into LGoSlowPath ...
2136 
2137        bind  (LGoSlowPath);
2138        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2139        jmpb  (DONE_LABEL);
2140 
2141        bind  (LSuccess);
2142        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2143        jmpb  (DONE_LABEL);
2144     }
2145 
2146     bind (Stacked);
2147     // It's not inflated and it's not recursively stack-locked and it's not biased.
2148     // It must be stack-locked.
2149     // Try to reset the header to displaced header.
2150     // The "box" value on the stack is stable, so we can reload
2151     // and be assured we observe the same value as above.
2152     movptr(tmpReg, Address(boxReg, 0));
2153     if (os::is_MP()) {
2154       lock();
2155     }
2156     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2157     // Intention fall-thru into DONE_LABEL
2158 
2159     // DONE_LABEL is a hot target - we'd really like to place it at the
2160     // start of cache line by padding with NOPs.
2161     // See the AMD and Intel software optimization manuals for the
2162     // most efficient "long" NOP encodings.
2163     // Unfortunately none of our alignment mechanisms suffice.
2164     if ((EmitSync & 65536) == 0) {
2165        bind (CheckSucc);
2166     }
2167 #else // _LP64
2168     // It's inflated
2169     if (EmitSync & 1024) {
2170       // Emit code to check that _owner == Self
2171       // We could fold the _owner test into subsequent code more efficiently
2172       // than using a stand-alone check, but since _owner checking is off by
2173       // default we don't bother. We also might consider predicating the
2174       // _owner==Self check on Xcheck:jni or running on a debug build.
2175       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2176       xorptr(boxReg, r15_thread);
2177     } else {
2178       xorptr(boxReg, boxReg);
2179     }
2180     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2181     jccb  (Assembler::notZero, DONE_LABEL);
2182     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2183     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2184     jccb  (Assembler::notZero, CheckSucc);
2185     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2186     jmpb  (DONE_LABEL);
2187 
2188     if ((EmitSync & 65536) == 0) {
2189       // Try to avoid passing control into the slow_path ...
2190       Label LSuccess, LGoSlowPath ;
2191       bind  (CheckSucc);
2192 
2193       // The following optional optimization can be elided if necessary
2194       // Effectively: if (succ == null) goto SlowPath
2195       // The code reduces the window for a race, however,
2196       // and thus benefits performance.
2197       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2198       jccb  (Assembler::zero, LGoSlowPath);
2199 
2200       xorptr(boxReg, boxReg);
2201       if ((EmitSync & 16) && os::is_MP()) {
2202         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2203       } else {
2204         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2205         if (os::is_MP()) {
2206           // Memory barrier/fence
2207           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2208           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2209           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2210           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2211           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2212           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2213           lock(); addl(Address(rsp, 0), 0);
2214         }
2215       }
2216       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2217       jccb  (Assembler::notZero, LSuccess);
2218 
2219       // Rare inopportune interleaving - race.
2220       // The successor vanished in the small window above.
2221       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2222       // We need to ensure progress and succession.
2223       // Try to reacquire the lock.
2224       // If that fails then the new owner is responsible for succession and this
2225       // thread needs to take no further action and can exit via the fast path (success).
2226       // If the re-acquire succeeds then pass control into the slow path.
2227       // As implemented, this latter mode is horrible because we generated more
2228       // coherence traffic on the lock *and* artifically extended the critical section
2229       // length while by virtue of passing control into the slow path.
2230 
2231       // box is really RAX -- the following CMPXCHG depends on that binding
2232       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2233       if (os::is_MP()) { lock(); }
2234       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2235       // There's no successor so we tried to regrab the lock.
2236       // If that didn't work, then another thread grabbed the
2237       // lock so we're done (and exit was a success).
2238       jccb  (Assembler::notEqual, LSuccess);
2239       // Intentional fall-through into slow-path
2240 
2241       bind  (LGoSlowPath);
2242       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2243       jmpb  (DONE_LABEL);
2244 
2245       bind  (LSuccess);
2246       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2247       jmpb  (DONE_LABEL);
2248     }
2249 
2250     bind  (Stacked);
2251     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2252     if (os::is_MP()) { lock(); }
2253     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2254 
2255     if (EmitSync & 65536) {
2256        bind (CheckSucc);
2257     }
2258 #endif
2259     bind(DONE_LABEL);
2260   }
2261 }
2262 #endif // COMPILER2
2263 
2264 void MacroAssembler::c2bool(Register x) {
2265   // implements x == 0 ? 0 : 1
2266   // note: must only look at least-significant byte of x
2267   //       since C-style booleans are stored in one byte
2268   //       only! (was bug)
2269   andl(x, 0xFF);
2270   setb(Assembler::notZero, x);
2271 }
2272 
2273 // Wouldn't need if AddressLiteral version had new name
2274 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2275   Assembler::call(L, rtype);
2276 }
2277 
2278 void MacroAssembler::call(Register entry) {
2279   Assembler::call(entry);
2280 }
2281 
2282 void MacroAssembler::call(AddressLiteral entry) {
2283   if (reachable(entry)) {
2284     Assembler::call_literal(entry.target(), entry.rspec());
2285   } else {
2286     lea(rscratch1, entry);
2287     Assembler::call(rscratch1);
2288   }
2289 }
2290 
2291 void MacroAssembler::ic_call(address entry, jint method_index) {
2292   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2293   movptr(rax, (intptr_t)Universe::non_oop_word());
2294   call(AddressLiteral(entry, rh));
2295 }
2296 
2297 // Implementation of call_VM versions
2298 
2299 void MacroAssembler::call_VM(Register oop_result,
2300                              address entry_point,
2301                              bool check_exceptions) {
2302   Label C, E;
2303   call(C, relocInfo::none);
2304   jmp(E);
2305 
2306   bind(C);
2307   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2308   ret(0);
2309 
2310   bind(E);
2311 }
2312 
2313 void MacroAssembler::call_VM(Register oop_result,
2314                              address entry_point,
2315                              Register arg_1,
2316                              bool check_exceptions) {
2317   Label C, E;
2318   call(C, relocInfo::none);
2319   jmp(E);
2320 
2321   bind(C);
2322   pass_arg1(this, arg_1);
2323   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2324   ret(0);
2325 
2326   bind(E);
2327 }
2328 
2329 void MacroAssembler::call_VM(Register oop_result,
2330                              address entry_point,
2331                              Register arg_1,
2332                              Register arg_2,
2333                              bool check_exceptions) {
2334   Label C, E;
2335   call(C, relocInfo::none);
2336   jmp(E);
2337 
2338   bind(C);
2339 
2340   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2341 
2342   pass_arg2(this, arg_2);
2343   pass_arg1(this, arg_1);
2344   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2345   ret(0);
2346 
2347   bind(E);
2348 }
2349 
2350 void MacroAssembler::call_VM(Register oop_result,
2351                              address entry_point,
2352                              Register arg_1,
2353                              Register arg_2,
2354                              Register arg_3,
2355                              bool check_exceptions) {
2356   Label C, E;
2357   call(C, relocInfo::none);
2358   jmp(E);
2359 
2360   bind(C);
2361 
2362   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2363   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2364   pass_arg3(this, arg_3);
2365 
2366   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2367   pass_arg2(this, arg_2);
2368 
2369   pass_arg1(this, arg_1);
2370   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2371   ret(0);
2372 
2373   bind(E);
2374 }
2375 
2376 void MacroAssembler::call_VM(Register oop_result,
2377                              Register last_java_sp,
2378                              address entry_point,
2379                              int number_of_arguments,
2380                              bool check_exceptions) {
2381   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2382   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2383 }
2384 
2385 void MacroAssembler::call_VM(Register oop_result,
2386                              Register last_java_sp,
2387                              address entry_point,
2388                              Register arg_1,
2389                              bool check_exceptions) {
2390   pass_arg1(this, arg_1);
2391   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2392 }
2393 
2394 void MacroAssembler::call_VM(Register oop_result,
2395                              Register last_java_sp,
2396                              address entry_point,
2397                              Register arg_1,
2398                              Register arg_2,
2399                              bool check_exceptions) {
2400 
2401   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2402   pass_arg2(this, arg_2);
2403   pass_arg1(this, arg_1);
2404   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2405 }
2406 
2407 void MacroAssembler::call_VM(Register oop_result,
2408                              Register last_java_sp,
2409                              address entry_point,
2410                              Register arg_1,
2411                              Register arg_2,
2412                              Register arg_3,
2413                              bool check_exceptions) {
2414   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2415   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2416   pass_arg3(this, arg_3);
2417   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2418   pass_arg2(this, arg_2);
2419   pass_arg1(this, arg_1);
2420   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2421 }
2422 
2423 void MacroAssembler::super_call_VM(Register oop_result,
2424                                    Register last_java_sp,
2425                                    address entry_point,
2426                                    int number_of_arguments,
2427                                    bool check_exceptions) {
2428   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2429   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2430 }
2431 
2432 void MacroAssembler::super_call_VM(Register oop_result,
2433                                    Register last_java_sp,
2434                                    address entry_point,
2435                                    Register arg_1,
2436                                    bool check_exceptions) {
2437   pass_arg1(this, arg_1);
2438   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2439 }
2440 
2441 void MacroAssembler::super_call_VM(Register oop_result,
2442                                    Register last_java_sp,
2443                                    address entry_point,
2444                                    Register arg_1,
2445                                    Register arg_2,
2446                                    bool check_exceptions) {
2447 
2448   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2449   pass_arg2(this, arg_2);
2450   pass_arg1(this, arg_1);
2451   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2452 }
2453 
2454 void MacroAssembler::super_call_VM(Register oop_result,
2455                                    Register last_java_sp,
2456                                    address entry_point,
2457                                    Register arg_1,
2458                                    Register arg_2,
2459                                    Register arg_3,
2460                                    bool check_exceptions) {
2461   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2462   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2463   pass_arg3(this, arg_3);
2464   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2465   pass_arg2(this, arg_2);
2466   pass_arg1(this, arg_1);
2467   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2468 }
2469 
2470 void MacroAssembler::call_VM_base(Register oop_result,
2471                                   Register java_thread,
2472                                   Register last_java_sp,
2473                                   address  entry_point,
2474                                   int      number_of_arguments,
2475                                   bool     check_exceptions) {
2476   // determine java_thread register
2477   if (!java_thread->is_valid()) {
2478 #ifdef _LP64
2479     java_thread = r15_thread;
2480 #else
2481     java_thread = rdi;
2482     get_thread(java_thread);
2483 #endif // LP64
2484   }
2485   // determine last_java_sp register
2486   if (!last_java_sp->is_valid()) {
2487     last_java_sp = rsp;
2488   }
2489   // debugging support
2490   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2491   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2492 #ifdef ASSERT
2493   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2494   // r12 is the heapbase.
2495   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2496 #endif // ASSERT
2497 
2498   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2499   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2500 
2501   // push java thread (becomes first argument of C function)
2502 
2503   NOT_LP64(push(java_thread); number_of_arguments++);
2504   LP64_ONLY(mov(c_rarg0, r15_thread));
2505 
2506   // set last Java frame before call
2507   assert(last_java_sp != rbp, "can't use ebp/rbp");
2508 
2509   // Only interpreter should have to set fp
2510   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2511 
2512   // do the call, remove parameters
2513   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2514 
2515   // restore the thread (cannot use the pushed argument since arguments
2516   // may be overwritten by C code generated by an optimizing compiler);
2517   // however can use the register value directly if it is callee saved.
2518   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2519     // rdi & rsi (also r15) are callee saved -> nothing to do
2520 #ifdef ASSERT
2521     guarantee(java_thread != rax, "change this code");
2522     push(rax);
2523     { Label L;
2524       get_thread(rax);
2525       cmpptr(java_thread, rax);
2526       jcc(Assembler::equal, L);
2527       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2528       bind(L);
2529     }
2530     pop(rax);
2531 #endif
2532   } else {
2533     get_thread(java_thread);
2534   }
2535   // reset last Java frame
2536   // Only interpreter should have to clear fp
2537   reset_last_Java_frame(java_thread, true);
2538 
2539    // C++ interp handles this in the interpreter
2540   check_and_handle_popframe(java_thread);
2541   check_and_handle_earlyret(java_thread);
2542 
2543   if (check_exceptions) {
2544     // check for pending exceptions (java_thread is set upon return)
2545     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2546 #ifndef _LP64
2547     jump_cc(Assembler::notEqual,
2548             RuntimeAddress(StubRoutines::forward_exception_entry()));
2549 #else
2550     // This used to conditionally jump to forward_exception however it is
2551     // possible if we relocate that the branch will not reach. So we must jump
2552     // around so we can always reach
2553 
2554     Label ok;
2555     jcc(Assembler::equal, ok);
2556     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2557     bind(ok);
2558 #endif // LP64
2559   }
2560 
2561   // get oop result if there is one and reset the value in the thread
2562   if (oop_result->is_valid()) {
2563     get_vm_result(oop_result, java_thread);
2564   }
2565 }
2566 
2567 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2568 
2569   // Calculate the value for last_Java_sp
2570   // somewhat subtle. call_VM does an intermediate call
2571   // which places a return address on the stack just under the
2572   // stack pointer as the user finsihed with it. This allows
2573   // use to retrieve last_Java_pc from last_Java_sp[-1].
2574   // On 32bit we then have to push additional args on the stack to accomplish
2575   // the actual requested call. On 64bit call_VM only can use register args
2576   // so the only extra space is the return address that call_VM created.
2577   // This hopefully explains the calculations here.
2578 
2579 #ifdef _LP64
2580   // We've pushed one address, correct last_Java_sp
2581   lea(rax, Address(rsp, wordSize));
2582 #else
2583   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2584 #endif // LP64
2585 
2586   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2587 
2588 }
2589 
2590 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2591 void MacroAssembler::call_VM_leaf0(address entry_point) {
2592   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2593 }
2594 
2595 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2596   call_VM_leaf_base(entry_point, number_of_arguments);
2597 }
2598 
2599 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2600   pass_arg0(this, arg_0);
2601   call_VM_leaf(entry_point, 1);
2602 }
2603 
2604 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2605 
2606   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2607   pass_arg1(this, arg_1);
2608   pass_arg0(this, arg_0);
2609   call_VM_leaf(entry_point, 2);
2610 }
2611 
2612 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2613   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2614   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2615   pass_arg2(this, arg_2);
2616   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2617   pass_arg1(this, arg_1);
2618   pass_arg0(this, arg_0);
2619   call_VM_leaf(entry_point, 3);
2620 }
2621 
2622 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2623   pass_arg0(this, arg_0);
2624   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2625 }
2626 
2627 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2628 
2629   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2630   pass_arg1(this, arg_1);
2631   pass_arg0(this, arg_0);
2632   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2633 }
2634 
2635 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2636   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2637   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2638   pass_arg2(this, arg_2);
2639   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2640   pass_arg1(this, arg_1);
2641   pass_arg0(this, arg_0);
2642   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2643 }
2644 
2645 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2646   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2647   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2648   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2649   pass_arg3(this, arg_3);
2650   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2651   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2652   pass_arg2(this, arg_2);
2653   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2654   pass_arg1(this, arg_1);
2655   pass_arg0(this, arg_0);
2656   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2657 }
2658 
2659 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2660   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2661   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2662   verify_oop(oop_result, "broken oop in call_VM_base");
2663 }
2664 
2665 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2666   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2667   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2668 }
2669 
2670 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2671 }
2672 
2673 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2674 }
2675 
2676 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2677   if (reachable(src1)) {
2678     cmpl(as_Address(src1), imm);
2679   } else {
2680     lea(rscratch1, src1);
2681     cmpl(Address(rscratch1, 0), imm);
2682   }
2683 }
2684 
2685 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2686   assert(!src2.is_lval(), "use cmpptr");
2687   if (reachable(src2)) {
2688     cmpl(src1, as_Address(src2));
2689   } else {
2690     lea(rscratch1, src2);
2691     cmpl(src1, Address(rscratch1, 0));
2692   }
2693 }
2694 
2695 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2696   Assembler::cmpl(src1, imm);
2697 }
2698 
2699 void MacroAssembler::cmp32(Register src1, Address src2) {
2700   Assembler::cmpl(src1, src2);
2701 }
2702 
2703 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2704   ucomisd(opr1, opr2);
2705 
2706   Label L;
2707   if (unordered_is_less) {
2708     movl(dst, -1);
2709     jcc(Assembler::parity, L);
2710     jcc(Assembler::below , L);
2711     movl(dst, 0);
2712     jcc(Assembler::equal , L);
2713     increment(dst);
2714   } else { // unordered is greater
2715     movl(dst, 1);
2716     jcc(Assembler::parity, L);
2717     jcc(Assembler::above , L);
2718     movl(dst, 0);
2719     jcc(Assembler::equal , L);
2720     decrementl(dst);
2721   }
2722   bind(L);
2723 }
2724 
2725 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2726   ucomiss(opr1, opr2);
2727 
2728   Label L;
2729   if (unordered_is_less) {
2730     movl(dst, -1);
2731     jcc(Assembler::parity, L);
2732     jcc(Assembler::below , L);
2733     movl(dst, 0);
2734     jcc(Assembler::equal , L);
2735     increment(dst);
2736   } else { // unordered is greater
2737     movl(dst, 1);
2738     jcc(Assembler::parity, L);
2739     jcc(Assembler::above , L);
2740     movl(dst, 0);
2741     jcc(Assembler::equal , L);
2742     decrementl(dst);
2743   }
2744   bind(L);
2745 }
2746 
2747 
2748 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2749   if (reachable(src1)) {
2750     cmpb(as_Address(src1), imm);
2751   } else {
2752     lea(rscratch1, src1);
2753     cmpb(Address(rscratch1, 0), imm);
2754   }
2755 }
2756 
2757 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2758 #ifdef _LP64
2759   if (src2.is_lval()) {
2760     movptr(rscratch1, src2);
2761     Assembler::cmpq(src1, rscratch1);
2762   } else if (reachable(src2)) {
2763     cmpq(src1, as_Address(src2));
2764   } else {
2765     lea(rscratch1, src2);
2766     Assembler::cmpq(src1, Address(rscratch1, 0));
2767   }
2768 #else
2769   if (src2.is_lval()) {
2770     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2771   } else {
2772     cmpl(src1, as_Address(src2));
2773   }
2774 #endif // _LP64
2775 }
2776 
2777 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2778   assert(src2.is_lval(), "not a mem-mem compare");
2779 #ifdef _LP64
2780   // moves src2's literal address
2781   movptr(rscratch1, src2);
2782   Assembler::cmpq(src1, rscratch1);
2783 #else
2784   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2785 #endif // _LP64
2786 }
2787 
2788 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2789   if (reachable(adr)) {
2790     if (os::is_MP())
2791       lock();
2792     cmpxchgptr(reg, as_Address(adr));
2793   } else {
2794     lea(rscratch1, adr);
2795     if (os::is_MP())
2796       lock();
2797     cmpxchgptr(reg, Address(rscratch1, 0));
2798   }
2799 }
2800 
2801 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2802   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2803 }
2804 
2805 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2806   if (reachable(src)) {
2807     Assembler::comisd(dst, as_Address(src));
2808   } else {
2809     lea(rscratch1, src);
2810     Assembler::comisd(dst, Address(rscratch1, 0));
2811   }
2812 }
2813 
2814 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2815   if (reachable(src)) {
2816     Assembler::comiss(dst, as_Address(src));
2817   } else {
2818     lea(rscratch1, src);
2819     Assembler::comiss(dst, Address(rscratch1, 0));
2820   }
2821 }
2822 
2823 
2824 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2825   Condition negated_cond = negate_condition(cond);
2826   Label L;
2827   jcc(negated_cond, L);
2828   pushf(); // Preserve flags
2829   atomic_incl(counter_addr);
2830   popf();
2831   bind(L);
2832 }
2833 
2834 int MacroAssembler::corrected_idivl(Register reg) {
2835   // Full implementation of Java idiv and irem; checks for
2836   // special case as described in JVM spec., p.243 & p.271.
2837   // The function returns the (pc) offset of the idivl
2838   // instruction - may be needed for implicit exceptions.
2839   //
2840   //         normal case                           special case
2841   //
2842   // input : rax,: dividend                         min_int
2843   //         reg: divisor   (may not be rax,/rdx)   -1
2844   //
2845   // output: rax,: quotient  (= rax, idiv reg)       min_int
2846   //         rdx: remainder (= rax, irem reg)       0
2847   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2848   const int min_int = 0x80000000;
2849   Label normal_case, special_case;
2850 
2851   // check for special case
2852   cmpl(rax, min_int);
2853   jcc(Assembler::notEqual, normal_case);
2854   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2855   cmpl(reg, -1);
2856   jcc(Assembler::equal, special_case);
2857 
2858   // handle normal case
2859   bind(normal_case);
2860   cdql();
2861   int idivl_offset = offset();
2862   idivl(reg);
2863 
2864   // normal and special case exit
2865   bind(special_case);
2866 
2867   return idivl_offset;
2868 }
2869 
2870 
2871 
2872 void MacroAssembler::decrementl(Register reg, int value) {
2873   if (value == min_jint) {subl(reg, value) ; return; }
2874   if (value <  0) { incrementl(reg, -value); return; }
2875   if (value == 0) {                        ; return; }
2876   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2877   /* else */      { subl(reg, value)       ; return; }
2878 }
2879 
2880 void MacroAssembler::decrementl(Address dst, int value) {
2881   if (value == min_jint) {subl(dst, value) ; return; }
2882   if (value <  0) { incrementl(dst, -value); return; }
2883   if (value == 0) {                        ; return; }
2884   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2885   /* else */      { subl(dst, value)       ; return; }
2886 }
2887 
2888 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2889   assert (shift_value > 0, "illegal shift value");
2890   Label _is_positive;
2891   testl (reg, reg);
2892   jcc (Assembler::positive, _is_positive);
2893   int offset = (1 << shift_value) - 1 ;
2894 
2895   if (offset == 1) {
2896     incrementl(reg);
2897   } else {
2898     addl(reg, offset);
2899   }
2900 
2901   bind (_is_positive);
2902   sarl(reg, shift_value);
2903 }
2904 
2905 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2906   if (reachable(src)) {
2907     Assembler::divsd(dst, as_Address(src));
2908   } else {
2909     lea(rscratch1, src);
2910     Assembler::divsd(dst, Address(rscratch1, 0));
2911   }
2912 }
2913 
2914 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2915   if (reachable(src)) {
2916     Assembler::divss(dst, as_Address(src));
2917   } else {
2918     lea(rscratch1, src);
2919     Assembler::divss(dst, Address(rscratch1, 0));
2920   }
2921 }
2922 
2923 // !defined(COMPILER2) is because of stupid core builds
2924 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2925 void MacroAssembler::empty_FPU_stack() {
2926   if (VM_Version::supports_mmx()) {
2927     emms();
2928   } else {
2929     for (int i = 8; i-- > 0; ) ffree(i);
2930   }
2931 }
2932 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2933 
2934 
2935 // Defines obj, preserves var_size_in_bytes
2936 void MacroAssembler::eden_allocate(Register obj,
2937                                    Register var_size_in_bytes,
2938                                    int con_size_in_bytes,
2939                                    Register t1,
2940                                    Label& slow_case) {
2941   assert(obj == rax, "obj must be in rax, for cmpxchg");
2942   assert_different_registers(obj, var_size_in_bytes, t1);
2943   if (!Universe::heap()->supports_inline_contig_alloc()) {
2944     jmp(slow_case);
2945   } else {
2946     Register end = t1;
2947     Label retry;
2948     bind(retry);
2949     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2950     movptr(obj, heap_top);
2951     if (var_size_in_bytes == noreg) {
2952       lea(end, Address(obj, con_size_in_bytes));
2953     } else {
2954       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2955     }
2956     // if end < obj then we wrapped around => object too long => slow case
2957     cmpptr(end, obj);
2958     jcc(Assembler::below, slow_case);
2959     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2960     jcc(Assembler::above, slow_case);
2961     // Compare obj with the top addr, and if still equal, store the new top addr in
2962     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2963     // it otherwise. Use lock prefix for atomicity on MPs.
2964     locked_cmpxchgptr(end, heap_top);
2965     jcc(Assembler::notEqual, retry);
2966   }
2967 }
2968 
2969 void MacroAssembler::enter() {
2970   push(rbp);
2971   mov(rbp, rsp);
2972 }
2973 
2974 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2975 void MacroAssembler::fat_nop() {
2976   if (UseAddressNop) {
2977     addr_nop_5();
2978   } else {
2979     emit_int8(0x26); // es:
2980     emit_int8(0x2e); // cs:
2981     emit_int8(0x64); // fs:
2982     emit_int8(0x65); // gs:
2983     emit_int8((unsigned char)0x90);
2984   }
2985 }
2986 
2987 void MacroAssembler::fcmp(Register tmp) {
2988   fcmp(tmp, 1, true, true);
2989 }
2990 
2991 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2992   assert(!pop_right || pop_left, "usage error");
2993   if (VM_Version::supports_cmov()) {
2994     assert(tmp == noreg, "unneeded temp");
2995     if (pop_left) {
2996       fucomip(index);
2997     } else {
2998       fucomi(index);
2999     }
3000     if (pop_right) {
3001       fpop();
3002     }
3003   } else {
3004     assert(tmp != noreg, "need temp");
3005     if (pop_left) {
3006       if (pop_right) {
3007         fcompp();
3008       } else {
3009         fcomp(index);
3010       }
3011     } else {
3012       fcom(index);
3013     }
3014     // convert FPU condition into eflags condition via rax,
3015     save_rax(tmp);
3016     fwait(); fnstsw_ax();
3017     sahf();
3018     restore_rax(tmp);
3019   }
3020   // condition codes set as follows:
3021   //
3022   // CF (corresponds to C0) if x < y
3023   // PF (corresponds to C2) if unordered
3024   // ZF (corresponds to C3) if x = y
3025 }
3026 
3027 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3028   fcmp2int(dst, unordered_is_less, 1, true, true);
3029 }
3030 
3031 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3032   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3033   Label L;
3034   if (unordered_is_less) {
3035     movl(dst, -1);
3036     jcc(Assembler::parity, L);
3037     jcc(Assembler::below , L);
3038     movl(dst, 0);
3039     jcc(Assembler::equal , L);
3040     increment(dst);
3041   } else { // unordered is greater
3042     movl(dst, 1);
3043     jcc(Assembler::parity, L);
3044     jcc(Assembler::above , L);
3045     movl(dst, 0);
3046     jcc(Assembler::equal , L);
3047     decrementl(dst);
3048   }
3049   bind(L);
3050 }
3051 
3052 void MacroAssembler::fld_d(AddressLiteral src) {
3053   fld_d(as_Address(src));
3054 }
3055 
3056 void MacroAssembler::fld_s(AddressLiteral src) {
3057   fld_s(as_Address(src));
3058 }
3059 
3060 void MacroAssembler::fld_x(AddressLiteral src) {
3061   Assembler::fld_x(as_Address(src));
3062 }
3063 
3064 void MacroAssembler::fldcw(AddressLiteral src) {
3065   Assembler::fldcw(as_Address(src));
3066 }
3067 
3068 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3069   if (reachable(src)) {
3070     Assembler::mulpd(dst, as_Address(src));
3071   } else {
3072     lea(rscratch1, src);
3073     Assembler::mulpd(dst, Address(rscratch1, 0));
3074   }
3075 }
3076 
3077 void MacroAssembler::increase_precision() {
3078   subptr(rsp, BytesPerWord);
3079   fnstcw(Address(rsp, 0));
3080   movl(rax, Address(rsp, 0));
3081   orl(rax, 0x300);
3082   push(rax);
3083   fldcw(Address(rsp, 0));
3084   pop(rax);
3085 }
3086 
3087 void MacroAssembler::restore_precision() {
3088   fldcw(Address(rsp, 0));
3089   addptr(rsp, BytesPerWord);
3090 }
3091 
3092 void MacroAssembler::fpop() {
3093   ffree();
3094   fincstp();
3095 }
3096 
3097 void MacroAssembler::load_float(Address src) {
3098   if (UseSSE >= 1) {
3099     movflt(xmm0, src);
3100   } else {
3101     LP64_ONLY(ShouldNotReachHere());
3102     NOT_LP64(fld_s(src));
3103   }
3104 }
3105 
3106 void MacroAssembler::store_float(Address dst) {
3107   if (UseSSE >= 1) {
3108     movflt(dst, xmm0);
3109   } else {
3110     LP64_ONLY(ShouldNotReachHere());
3111     NOT_LP64(fstp_s(dst));
3112   }
3113 }
3114 
3115 void MacroAssembler::load_double(Address src) {
3116   if (UseSSE >= 2) {
3117     movdbl(xmm0, src);
3118   } else {
3119     LP64_ONLY(ShouldNotReachHere());
3120     NOT_LP64(fld_d(src));
3121   }
3122 }
3123 
3124 void MacroAssembler::store_double(Address dst) {
3125   if (UseSSE >= 2) {
3126     movdbl(dst, xmm0);
3127   } else {
3128     LP64_ONLY(ShouldNotReachHere());
3129     NOT_LP64(fstp_d(dst));
3130   }
3131 }
3132 
3133 void MacroAssembler::fremr(Register tmp) {
3134   save_rax(tmp);
3135   { Label L;
3136     bind(L);
3137     fprem();
3138     fwait(); fnstsw_ax();
3139 #ifdef _LP64
3140     testl(rax, 0x400);
3141     jcc(Assembler::notEqual, L);
3142 #else
3143     sahf();
3144     jcc(Assembler::parity, L);
3145 #endif // _LP64
3146   }
3147   restore_rax(tmp);
3148   // Result is in ST0.
3149   // Note: fxch & fpop to get rid of ST1
3150   // (otherwise FPU stack could overflow eventually)
3151   fxch(1);
3152   fpop();
3153 }
3154 
3155 // dst = c = a * b + c
3156 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3157   Assembler::vfmadd231sd(c, a, b);
3158   if (dst != c) {
3159     movdbl(dst, c);
3160   }
3161 }
3162 
3163 // dst = c = a * b + c
3164 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3165   Assembler::vfmadd231ss(c, a, b);
3166   if (dst != c) {
3167     movflt(dst, c);
3168   }
3169 }
3170 
3171 // dst = c = a * b + c
3172 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3173   Assembler::vfmadd231pd(c, a, b, vector_len);
3174   if (dst != c) {
3175     vmovdqu(dst, c);
3176   }
3177 }
3178 
3179 // dst = c = a * b + c
3180 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3181   Assembler::vfmadd231ps(c, a, b, vector_len);
3182   if (dst != c) {
3183     vmovdqu(dst, c);
3184   }
3185 }
3186 
3187 // dst = c = a * b + c
3188 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3189   Assembler::vfmadd231pd(c, a, b, vector_len);
3190   if (dst != c) {
3191     vmovdqu(dst, c);
3192   }
3193 }
3194 
3195 // dst = c = a * b + c
3196 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3197   Assembler::vfmadd231ps(c, a, b, vector_len);
3198   if (dst != c) {
3199     vmovdqu(dst, c);
3200   }
3201 }
3202 
3203 void MacroAssembler::incrementl(AddressLiteral dst) {
3204   if (reachable(dst)) {
3205     incrementl(as_Address(dst));
3206   } else {
3207     lea(rscratch1, dst);
3208     incrementl(Address(rscratch1, 0));
3209   }
3210 }
3211 
3212 void MacroAssembler::incrementl(ArrayAddress dst) {
3213   incrementl(as_Address(dst));
3214 }
3215 
3216 void MacroAssembler::incrementl(Register reg, int value) {
3217   if (value == min_jint) {addl(reg, value) ; return; }
3218   if (value <  0) { decrementl(reg, -value); return; }
3219   if (value == 0) {                        ; return; }
3220   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3221   /* else */      { addl(reg, value)       ; return; }
3222 }
3223 
3224 void MacroAssembler::incrementl(Address dst, int value) {
3225   if (value == min_jint) {addl(dst, value) ; return; }
3226   if (value <  0) { decrementl(dst, -value); return; }
3227   if (value == 0) {                        ; return; }
3228   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3229   /* else */      { addl(dst, value)       ; return; }
3230 }
3231 
3232 void MacroAssembler::jump(AddressLiteral dst) {
3233   if (reachable(dst)) {
3234     jmp_literal(dst.target(), dst.rspec());
3235   } else {
3236     lea(rscratch1, dst);
3237     jmp(rscratch1);
3238   }
3239 }
3240 
3241 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3242   if (reachable(dst)) {
3243     InstructionMark im(this);
3244     relocate(dst.reloc());
3245     const int short_size = 2;
3246     const int long_size = 6;
3247     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3248     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3249       // 0111 tttn #8-bit disp
3250       emit_int8(0x70 | cc);
3251       emit_int8((offs - short_size) & 0xFF);
3252     } else {
3253       // 0000 1111 1000 tttn #32-bit disp
3254       emit_int8(0x0F);
3255       emit_int8((unsigned char)(0x80 | cc));
3256       emit_int32(offs - long_size);
3257     }
3258   } else {
3259 #ifdef ASSERT
3260     warning("reversing conditional branch");
3261 #endif /* ASSERT */
3262     Label skip;
3263     jccb(reverse[cc], skip);
3264     lea(rscratch1, dst);
3265     Assembler::jmp(rscratch1);
3266     bind(skip);
3267   }
3268 }
3269 
3270 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3271   if (reachable(src)) {
3272     Assembler::ldmxcsr(as_Address(src));
3273   } else {
3274     lea(rscratch1, src);
3275     Assembler::ldmxcsr(Address(rscratch1, 0));
3276   }
3277 }
3278 
3279 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3280   int off;
3281   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3282     off = offset();
3283     movsbl(dst, src); // movsxb
3284   } else {
3285     off = load_unsigned_byte(dst, src);
3286     shll(dst, 24);
3287     sarl(dst, 24);
3288   }
3289   return off;
3290 }
3291 
3292 // Note: load_signed_short used to be called load_signed_word.
3293 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3294 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3295 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3296 int MacroAssembler::load_signed_short(Register dst, Address src) {
3297   int off;
3298   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3299     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3300     // version but this is what 64bit has always done. This seems to imply
3301     // that users are only using 32bits worth.
3302     off = offset();
3303     movswl(dst, src); // movsxw
3304   } else {
3305     off = load_unsigned_short(dst, src);
3306     shll(dst, 16);
3307     sarl(dst, 16);
3308   }
3309   return off;
3310 }
3311 
3312 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3313   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3314   // and "3.9 Partial Register Penalties", p. 22).
3315   int off;
3316   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3317     off = offset();
3318     movzbl(dst, src); // movzxb
3319   } else {
3320     xorl(dst, dst);
3321     off = offset();
3322     movb(dst, src);
3323   }
3324   return off;
3325 }
3326 
3327 // Note: load_unsigned_short used to be called load_unsigned_word.
3328 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3329   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3330   // and "3.9 Partial Register Penalties", p. 22).
3331   int off;
3332   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3333     off = offset();
3334     movzwl(dst, src); // movzxw
3335   } else {
3336     xorl(dst, dst);
3337     off = offset();
3338     movw(dst, src);
3339   }
3340   return off;
3341 }
3342 
3343 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3344   switch (size_in_bytes) {
3345 #ifndef _LP64
3346   case  8:
3347     assert(dst2 != noreg, "second dest register required");
3348     movl(dst,  src);
3349     movl(dst2, src.plus_disp(BytesPerInt));
3350     break;
3351 #else
3352   case  8:  movq(dst, src); break;
3353 #endif
3354   case  4:  movl(dst, src); break;
3355   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3356   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3357   default:  ShouldNotReachHere();
3358   }
3359 }
3360 
3361 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3362   switch (size_in_bytes) {
3363 #ifndef _LP64
3364   case  8:
3365     assert(src2 != noreg, "second source register required");
3366     movl(dst,                        src);
3367     movl(dst.plus_disp(BytesPerInt), src2);
3368     break;
3369 #else
3370   case  8:  movq(dst, src); break;
3371 #endif
3372   case  4:  movl(dst, src); break;
3373   case  2:  movw(dst, src); break;
3374   case  1:  movb(dst, src); break;
3375   default:  ShouldNotReachHere();
3376   }
3377 }
3378 
3379 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3380   if (reachable(dst)) {
3381     movl(as_Address(dst), src);
3382   } else {
3383     lea(rscratch1, dst);
3384     movl(Address(rscratch1, 0), src);
3385   }
3386 }
3387 
3388 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3389   if (reachable(src)) {
3390     movl(dst, as_Address(src));
3391   } else {
3392     lea(rscratch1, src);
3393     movl(dst, Address(rscratch1, 0));
3394   }
3395 }
3396 
3397 // C++ bool manipulation
3398 
3399 void MacroAssembler::movbool(Register dst, Address src) {
3400   if(sizeof(bool) == 1)
3401     movb(dst, src);
3402   else if(sizeof(bool) == 2)
3403     movw(dst, src);
3404   else if(sizeof(bool) == 4)
3405     movl(dst, src);
3406   else
3407     // unsupported
3408     ShouldNotReachHere();
3409 }
3410 
3411 void MacroAssembler::movbool(Address dst, bool boolconst) {
3412   if(sizeof(bool) == 1)
3413     movb(dst, (int) boolconst);
3414   else if(sizeof(bool) == 2)
3415     movw(dst, (int) boolconst);
3416   else if(sizeof(bool) == 4)
3417     movl(dst, (int) boolconst);
3418   else
3419     // unsupported
3420     ShouldNotReachHere();
3421 }
3422 
3423 void MacroAssembler::movbool(Address dst, Register src) {
3424   if(sizeof(bool) == 1)
3425     movb(dst, src);
3426   else if(sizeof(bool) == 2)
3427     movw(dst, src);
3428   else if(sizeof(bool) == 4)
3429     movl(dst, src);
3430   else
3431     // unsupported
3432     ShouldNotReachHere();
3433 }
3434 
3435 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3436   movb(as_Address(dst), src);
3437 }
3438 
3439 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3440   if (reachable(src)) {
3441     movdl(dst, as_Address(src));
3442   } else {
3443     lea(rscratch1, src);
3444     movdl(dst, Address(rscratch1, 0));
3445   }
3446 }
3447 
3448 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3449   if (reachable(src)) {
3450     movq(dst, as_Address(src));
3451   } else {
3452     lea(rscratch1, src);
3453     movq(dst, Address(rscratch1, 0));
3454   }
3455 }
3456 
3457 void MacroAssembler::setvectmask(Register dst, Register src) {
3458   Assembler::movl(dst, 1);
3459   Assembler::shlxl(dst, dst, src);
3460   Assembler::decl(dst);
3461   Assembler::kmovdl(k1, dst);
3462   Assembler::movl(dst, src);
3463 }
3464 
3465 void MacroAssembler::restorevectmask() {
3466   Assembler::knotwl(k1, k0);
3467 }
3468 
3469 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3470   if (reachable(src)) {
3471     if (UseXmmLoadAndClearUpper) {
3472       movsd (dst, as_Address(src));
3473     } else {
3474       movlpd(dst, as_Address(src));
3475     }
3476   } else {
3477     lea(rscratch1, src);
3478     if (UseXmmLoadAndClearUpper) {
3479       movsd (dst, Address(rscratch1, 0));
3480     } else {
3481       movlpd(dst, Address(rscratch1, 0));
3482     }
3483   }
3484 }
3485 
3486 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3487   if (reachable(src)) {
3488     movss(dst, as_Address(src));
3489   } else {
3490     lea(rscratch1, src);
3491     movss(dst, Address(rscratch1, 0));
3492   }
3493 }
3494 
3495 void MacroAssembler::movptr(Register dst, Register src) {
3496   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3497 }
3498 
3499 void MacroAssembler::movptr(Register dst, Address src) {
3500   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3501 }
3502 
3503 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3504 void MacroAssembler::movptr(Register dst, intptr_t src) {
3505   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3506 }
3507 
3508 void MacroAssembler::movptr(Address dst, Register src) {
3509   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3510 }
3511 
3512 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3513   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3514     Assembler::vextractf32x4(dst, src, 0);
3515   } else {
3516     Assembler::movdqu(dst, src);
3517   }
3518 }
3519 
3520 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3521   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3522     Assembler::vinsertf32x4(dst, dst, src, 0);
3523   } else {
3524     Assembler::movdqu(dst, src);
3525   }
3526 }
3527 
3528 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3529   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3530     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3531   } else {
3532     Assembler::movdqu(dst, src);
3533   }
3534 }
3535 
3536 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3537   if (reachable(src)) {
3538     movdqu(dst, as_Address(src));
3539   } else {
3540     lea(scratchReg, src);
3541     movdqu(dst, Address(scratchReg, 0));
3542   }
3543 }
3544 
3545 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3546   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3547     vextractf64x4_low(dst, src);
3548   } else {
3549     Assembler::vmovdqu(dst, src);
3550   }
3551 }
3552 
3553 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3554   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3555     vinsertf64x4_low(dst, src);
3556   } else {
3557     Assembler::vmovdqu(dst, src);
3558   }
3559 }
3560 
3561 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3562   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3563     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3564   }
3565   else {
3566     Assembler::vmovdqu(dst, src);
3567   }
3568 }
3569 
3570 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3571   if (reachable(src)) {
3572     vmovdqu(dst, as_Address(src));
3573   }
3574   else {
3575     lea(rscratch1, src);
3576     vmovdqu(dst, Address(rscratch1, 0));
3577   }
3578 }
3579 
3580 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3581   if (reachable(src)) {
3582     Assembler::movdqa(dst, as_Address(src));
3583   } else {
3584     lea(rscratch1, src);
3585     Assembler::movdqa(dst, Address(rscratch1, 0));
3586   }
3587 }
3588 
3589 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3590   if (reachable(src)) {
3591     Assembler::movsd(dst, as_Address(src));
3592   } else {
3593     lea(rscratch1, src);
3594     Assembler::movsd(dst, Address(rscratch1, 0));
3595   }
3596 }
3597 
3598 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3599   if (reachable(src)) {
3600     Assembler::movss(dst, as_Address(src));
3601   } else {
3602     lea(rscratch1, src);
3603     Assembler::movss(dst, Address(rscratch1, 0));
3604   }
3605 }
3606 
3607 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3608   if (reachable(src)) {
3609     Assembler::mulsd(dst, as_Address(src));
3610   } else {
3611     lea(rscratch1, src);
3612     Assembler::mulsd(dst, Address(rscratch1, 0));
3613   }
3614 }
3615 
3616 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3617   if (reachable(src)) {
3618     Assembler::mulss(dst, as_Address(src));
3619   } else {
3620     lea(rscratch1, src);
3621     Assembler::mulss(dst, Address(rscratch1, 0));
3622   }
3623 }
3624 
3625 void MacroAssembler::null_check(Register reg, int offset) {
3626   if (needs_explicit_null_check(offset)) {
3627     // provoke OS NULL exception if reg = NULL by
3628     // accessing M[reg] w/o changing any (non-CC) registers
3629     // NOTE: cmpl is plenty here to provoke a segv
3630     cmpptr(rax, Address(reg, 0));
3631     // Note: should probably use testl(rax, Address(reg, 0));
3632     //       may be shorter code (however, this version of
3633     //       testl needs to be implemented first)
3634   } else {
3635     // nothing to do, (later) access of M[reg + offset]
3636     // will provoke OS NULL exception if reg = NULL
3637   }
3638 }
3639 
3640 void MacroAssembler::os_breakpoint() {
3641   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3642   // (e.g., MSVC can't call ps() otherwise)
3643   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3644 }
3645 
3646 void MacroAssembler::unimplemented(const char* what) {
3647   char* b = new char[1024];
3648   jio_snprintf(b, 1024, "unimplemented: %s", what);
3649   stop(b);
3650 }
3651 
3652 #ifdef _LP64
3653 #define XSTATE_BV 0x200
3654 #endif
3655 
3656 void MacroAssembler::pop_CPU_state() {
3657   pop_FPU_state();
3658   pop_IU_state();
3659 }
3660 
3661 void MacroAssembler::pop_FPU_state() {
3662 #ifndef _LP64
3663   frstor(Address(rsp, 0));
3664 #else
3665   fxrstor(Address(rsp, 0));
3666 #endif
3667   addptr(rsp, FPUStateSizeInWords * wordSize);
3668 }
3669 
3670 void MacroAssembler::pop_IU_state() {
3671   popa();
3672   LP64_ONLY(addq(rsp, 8));
3673   popf();
3674 }
3675 
3676 // Save Integer and Float state
3677 // Warning: Stack must be 16 byte aligned (64bit)
3678 void MacroAssembler::push_CPU_state() {
3679   push_IU_state();
3680   push_FPU_state();
3681 }
3682 
3683 void MacroAssembler::push_FPU_state() {
3684   subptr(rsp, FPUStateSizeInWords * wordSize);
3685 #ifndef _LP64
3686   fnsave(Address(rsp, 0));
3687   fwait();
3688 #else
3689   fxsave(Address(rsp, 0));
3690 #endif // LP64
3691 }
3692 
3693 void MacroAssembler::push_IU_state() {
3694   // Push flags first because pusha kills them
3695   pushf();
3696   // Make sure rsp stays 16-byte aligned
3697   LP64_ONLY(subq(rsp, 8));
3698   pusha();
3699 }
3700 
3701 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3702   if (!java_thread->is_valid()) {
3703     java_thread = rdi;
3704     get_thread(java_thread);
3705   }
3706   // we must set sp to zero to clear frame
3707   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3708   if (clear_fp) {
3709     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3710   }
3711 
3712   // Always clear the pc because it could have been set by make_walkable()
3713   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3714 
3715   vzeroupper();
3716 }
3717 
3718 void MacroAssembler::restore_rax(Register tmp) {
3719   if (tmp == noreg) pop(rax);
3720   else if (tmp != rax) mov(rax, tmp);
3721 }
3722 
3723 void MacroAssembler::round_to(Register reg, int modulus) {
3724   addptr(reg, modulus - 1);
3725   andptr(reg, -modulus);
3726 }
3727 
3728 void MacroAssembler::save_rax(Register tmp) {
3729   if (tmp == noreg) push(rax);
3730   else if (tmp != rax) mov(tmp, rax);
3731 }
3732 
3733 // Write serialization page so VM thread can do a pseudo remote membar.
3734 // We use the current thread pointer to calculate a thread specific
3735 // offset to write to within the page. This minimizes bus traffic
3736 // due to cache line collision.
3737 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3738   movl(tmp, thread);
3739   shrl(tmp, os::get_serialize_page_shift_count());
3740   andl(tmp, (os::vm_page_size() - sizeof(int)));
3741 
3742   Address index(noreg, tmp, Address::times_1);
3743   ExternalAddress page(os::get_memory_serialize_page());
3744 
3745   // Size of store must match masking code above
3746   movl(as_Address(ArrayAddress(page, index)), tmp);
3747 }
3748 
3749 #ifdef _LP64
3750 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3751   if (SafepointMechanism::uses_thread_local_poll()) {
3752     testb(Address(r15_thread, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3753     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3754   } else {
3755     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3756         SafepointSynchronize::_not_synchronized);
3757     jcc(Assembler::notEqual, slow_path);
3758   }
3759 }
3760 #else
3761 void MacroAssembler::safepoint_poll(Label& slow_path) {
3762   cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3763       SafepointSynchronize::_not_synchronized);
3764   jcc(Assembler::notEqual, slow_path);
3765 }
3766 #endif
3767 
3768 // Calls to C land
3769 //
3770 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3771 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3772 // has to be reset to 0. This is required to allow proper stack traversal.
3773 void MacroAssembler::set_last_Java_frame(Register java_thread,
3774                                          Register last_java_sp,
3775                                          Register last_java_fp,
3776                                          address  last_java_pc) {
3777   vzeroupper();
3778   // determine java_thread register
3779   if (!java_thread->is_valid()) {
3780     java_thread = rdi;
3781     get_thread(java_thread);
3782   }
3783   // determine last_java_sp register
3784   if (!last_java_sp->is_valid()) {
3785     last_java_sp = rsp;
3786   }
3787 
3788   // last_java_fp is optional
3789 
3790   if (last_java_fp->is_valid()) {
3791     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3792   }
3793 
3794   // last_java_pc is optional
3795 
3796   if (last_java_pc != NULL) {
3797     lea(Address(java_thread,
3798                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3799         InternalAddress(last_java_pc));
3800 
3801   }
3802   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3803 }
3804 
3805 void MacroAssembler::shlptr(Register dst, int imm8) {
3806   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3807 }
3808 
3809 void MacroAssembler::shrptr(Register dst, int imm8) {
3810   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3811 }
3812 
3813 void MacroAssembler::sign_extend_byte(Register reg) {
3814   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3815     movsbl(reg, reg); // movsxb
3816   } else {
3817     shll(reg, 24);
3818     sarl(reg, 24);
3819   }
3820 }
3821 
3822 void MacroAssembler::sign_extend_short(Register reg) {
3823   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3824     movswl(reg, reg); // movsxw
3825   } else {
3826     shll(reg, 16);
3827     sarl(reg, 16);
3828   }
3829 }
3830 
3831 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3832   assert(reachable(src), "Address should be reachable");
3833   testl(dst, as_Address(src));
3834 }
3835 
3836 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3837   int dst_enc = dst->encoding();
3838   int src_enc = src->encoding();
3839   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3840     Assembler::pcmpeqb(dst, src);
3841   } else if ((dst_enc < 16) && (src_enc < 16)) {
3842     Assembler::pcmpeqb(dst, src);
3843   } else if (src_enc < 16) {
3844     subptr(rsp, 64);
3845     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3846     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3847     Assembler::pcmpeqb(xmm0, src);
3848     movdqu(dst, xmm0);
3849     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3850     addptr(rsp, 64);
3851   } else if (dst_enc < 16) {
3852     subptr(rsp, 64);
3853     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3854     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3855     Assembler::pcmpeqb(dst, xmm0);
3856     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3857     addptr(rsp, 64);
3858   } else {
3859     subptr(rsp, 64);
3860     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3861     subptr(rsp, 64);
3862     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3863     movdqu(xmm0, src);
3864     movdqu(xmm1, dst);
3865     Assembler::pcmpeqb(xmm1, xmm0);
3866     movdqu(dst, xmm1);
3867     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3868     addptr(rsp, 64);
3869     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3870     addptr(rsp, 64);
3871   }
3872 }
3873 
3874 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3875   int dst_enc = dst->encoding();
3876   int src_enc = src->encoding();
3877   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3878     Assembler::pcmpeqw(dst, src);
3879   } else if ((dst_enc < 16) && (src_enc < 16)) {
3880     Assembler::pcmpeqw(dst, src);
3881   } else if (src_enc < 16) {
3882     subptr(rsp, 64);
3883     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3884     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3885     Assembler::pcmpeqw(xmm0, src);
3886     movdqu(dst, xmm0);
3887     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3888     addptr(rsp, 64);
3889   } else if (dst_enc < 16) {
3890     subptr(rsp, 64);
3891     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3892     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3893     Assembler::pcmpeqw(dst, xmm0);
3894     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3895     addptr(rsp, 64);
3896   } else {
3897     subptr(rsp, 64);
3898     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3899     subptr(rsp, 64);
3900     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3901     movdqu(xmm0, src);
3902     movdqu(xmm1, dst);
3903     Assembler::pcmpeqw(xmm1, xmm0);
3904     movdqu(dst, xmm1);
3905     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3906     addptr(rsp, 64);
3907     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3908     addptr(rsp, 64);
3909   }
3910 }
3911 
3912 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3913   int dst_enc = dst->encoding();
3914   if (dst_enc < 16) {
3915     Assembler::pcmpestri(dst, src, imm8);
3916   } else {
3917     subptr(rsp, 64);
3918     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3919     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3920     Assembler::pcmpestri(xmm0, src, imm8);
3921     movdqu(dst, xmm0);
3922     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3923     addptr(rsp, 64);
3924   }
3925 }
3926 
3927 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3928   int dst_enc = dst->encoding();
3929   int src_enc = src->encoding();
3930   if ((dst_enc < 16) && (src_enc < 16)) {
3931     Assembler::pcmpestri(dst, src, imm8);
3932   } else if (src_enc < 16) {
3933     subptr(rsp, 64);
3934     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3935     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3936     Assembler::pcmpestri(xmm0, src, imm8);
3937     movdqu(dst, xmm0);
3938     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3939     addptr(rsp, 64);
3940   } else if (dst_enc < 16) {
3941     subptr(rsp, 64);
3942     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3943     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3944     Assembler::pcmpestri(dst, xmm0, imm8);
3945     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3946     addptr(rsp, 64);
3947   } else {
3948     subptr(rsp, 64);
3949     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3950     subptr(rsp, 64);
3951     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3952     movdqu(xmm0, src);
3953     movdqu(xmm1, dst);
3954     Assembler::pcmpestri(xmm1, xmm0, imm8);
3955     movdqu(dst, xmm1);
3956     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3957     addptr(rsp, 64);
3958     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3959     addptr(rsp, 64);
3960   }
3961 }
3962 
3963 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3964   int dst_enc = dst->encoding();
3965   int src_enc = src->encoding();
3966   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3967     Assembler::pmovzxbw(dst, src);
3968   } else if ((dst_enc < 16) && (src_enc < 16)) {
3969     Assembler::pmovzxbw(dst, src);
3970   } else if (src_enc < 16) {
3971     subptr(rsp, 64);
3972     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3973     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3974     Assembler::pmovzxbw(xmm0, src);
3975     movdqu(dst, xmm0);
3976     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3977     addptr(rsp, 64);
3978   } else if (dst_enc < 16) {
3979     subptr(rsp, 64);
3980     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3981     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3982     Assembler::pmovzxbw(dst, xmm0);
3983     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985   } else {
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3988     subptr(rsp, 64);
3989     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3990     movdqu(xmm0, src);
3991     movdqu(xmm1, dst);
3992     Assembler::pmovzxbw(xmm1, xmm0);
3993     movdqu(dst, xmm1);
3994     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3995     addptr(rsp, 64);
3996     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3997     addptr(rsp, 64);
3998   }
3999 }
4000 
4001 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4002   int dst_enc = dst->encoding();
4003   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4004     Assembler::pmovzxbw(dst, src);
4005   } else if (dst_enc < 16) {
4006     Assembler::pmovzxbw(dst, src);
4007   } else {
4008     subptr(rsp, 64);
4009     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4010     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4011     Assembler::pmovzxbw(xmm0, src);
4012     movdqu(dst, xmm0);
4013     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4014     addptr(rsp, 64);
4015   }
4016 }
4017 
4018 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4019   int src_enc = src->encoding();
4020   if (src_enc < 16) {
4021     Assembler::pmovmskb(dst, src);
4022   } else {
4023     subptr(rsp, 64);
4024     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4025     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4026     Assembler::pmovmskb(dst, xmm0);
4027     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4028     addptr(rsp, 64);
4029   }
4030 }
4031 
4032 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4033   int dst_enc = dst->encoding();
4034   int src_enc = src->encoding();
4035   if ((dst_enc < 16) && (src_enc < 16)) {
4036     Assembler::ptest(dst, src);
4037   } else if (src_enc < 16) {
4038     subptr(rsp, 64);
4039     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4040     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4041     Assembler::ptest(xmm0, src);
4042     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4043     addptr(rsp, 64);
4044   } else if (dst_enc < 16) {
4045     subptr(rsp, 64);
4046     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4047     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4048     Assembler::ptest(dst, xmm0);
4049     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4050     addptr(rsp, 64);
4051   } else {
4052     subptr(rsp, 64);
4053     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4054     subptr(rsp, 64);
4055     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4056     movdqu(xmm0, src);
4057     movdqu(xmm1, dst);
4058     Assembler::ptest(xmm1, xmm0);
4059     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4060     addptr(rsp, 64);
4061     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4062     addptr(rsp, 64);
4063   }
4064 }
4065 
4066 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4067   if (reachable(src)) {
4068     Assembler::sqrtsd(dst, as_Address(src));
4069   } else {
4070     lea(rscratch1, src);
4071     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4072   }
4073 }
4074 
4075 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4076   if (reachable(src)) {
4077     Assembler::sqrtss(dst, as_Address(src));
4078   } else {
4079     lea(rscratch1, src);
4080     Assembler::sqrtss(dst, Address(rscratch1, 0));
4081   }
4082 }
4083 
4084 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4085   if (reachable(src)) {
4086     Assembler::subsd(dst, as_Address(src));
4087   } else {
4088     lea(rscratch1, src);
4089     Assembler::subsd(dst, Address(rscratch1, 0));
4090   }
4091 }
4092 
4093 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4094   if (reachable(src)) {
4095     Assembler::subss(dst, as_Address(src));
4096   } else {
4097     lea(rscratch1, src);
4098     Assembler::subss(dst, Address(rscratch1, 0));
4099   }
4100 }
4101 
4102 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4103   if (reachable(src)) {
4104     Assembler::ucomisd(dst, as_Address(src));
4105   } else {
4106     lea(rscratch1, src);
4107     Assembler::ucomisd(dst, Address(rscratch1, 0));
4108   }
4109 }
4110 
4111 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4112   if (reachable(src)) {
4113     Assembler::ucomiss(dst, as_Address(src));
4114   } else {
4115     lea(rscratch1, src);
4116     Assembler::ucomiss(dst, Address(rscratch1, 0));
4117   }
4118 }
4119 
4120 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4121   // Used in sign-bit flipping with aligned address.
4122   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4123   if (reachable(src)) {
4124     Assembler::xorpd(dst, as_Address(src));
4125   } else {
4126     lea(rscratch1, src);
4127     Assembler::xorpd(dst, Address(rscratch1, 0));
4128   }
4129 }
4130 
4131 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4132   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4133     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4134   }
4135   else {
4136     Assembler::xorpd(dst, src);
4137   }
4138 }
4139 
4140 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4141   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4142     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4143   } else {
4144     Assembler::xorps(dst, src);
4145   }
4146 }
4147 
4148 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4149   // Used in sign-bit flipping with aligned address.
4150   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4151   if (reachable(src)) {
4152     Assembler::xorps(dst, as_Address(src));
4153   } else {
4154     lea(rscratch1, src);
4155     Assembler::xorps(dst, Address(rscratch1, 0));
4156   }
4157 }
4158 
4159 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4160   // Used in sign-bit flipping with aligned address.
4161   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4162   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4163   if (reachable(src)) {
4164     Assembler::pshufb(dst, as_Address(src));
4165   } else {
4166     lea(rscratch1, src);
4167     Assembler::pshufb(dst, Address(rscratch1, 0));
4168   }
4169 }
4170 
4171 // AVX 3-operands instructions
4172 
4173 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4174   if (reachable(src)) {
4175     vaddsd(dst, nds, as_Address(src));
4176   } else {
4177     lea(rscratch1, src);
4178     vaddsd(dst, nds, Address(rscratch1, 0));
4179   }
4180 }
4181 
4182 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4183   if (reachable(src)) {
4184     vaddss(dst, nds, as_Address(src));
4185   } else {
4186     lea(rscratch1, src);
4187     vaddss(dst, nds, Address(rscratch1, 0));
4188   }
4189 }
4190 
4191 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4192   int dst_enc = dst->encoding();
4193   int nds_enc = nds->encoding();
4194   int src_enc = src->encoding();
4195   if ((dst_enc < 16) && (nds_enc < 16)) {
4196     vandps(dst, nds, negate_field, vector_len);
4197   } else if ((src_enc < 16) && (dst_enc < 16)) {
4198     evmovdqul(src, nds, Assembler::AVX_512bit);
4199     vandps(dst, src, negate_field, vector_len);
4200   } else if (src_enc < 16) {
4201     evmovdqul(src, nds, Assembler::AVX_512bit);
4202     vandps(src, src, negate_field, vector_len);
4203     evmovdqul(dst, src, Assembler::AVX_512bit);
4204   } else if (dst_enc < 16) {
4205     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4206     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4207     vandps(dst, xmm0, negate_field, vector_len);
4208     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4209   } else {
4210     if (src_enc != dst_enc) {
4211       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4212       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4213       vandps(xmm0, xmm0, negate_field, vector_len);
4214       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4215       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4216     } else {
4217       subptr(rsp, 64);
4218       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4219       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4220       vandps(xmm0, xmm0, negate_field, vector_len);
4221       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4222       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4223       addptr(rsp, 64);
4224     }
4225   }
4226 }
4227 
4228 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4229   int dst_enc = dst->encoding();
4230   int nds_enc = nds->encoding();
4231   int src_enc = src->encoding();
4232   if ((dst_enc < 16) && (nds_enc < 16)) {
4233     vandpd(dst, nds, negate_field, vector_len);
4234   } else if ((src_enc < 16) && (dst_enc < 16)) {
4235     evmovdqul(src, nds, Assembler::AVX_512bit);
4236     vandpd(dst, src, negate_field, vector_len);
4237   } else if (src_enc < 16) {
4238     evmovdqul(src, nds, Assembler::AVX_512bit);
4239     vandpd(src, src, negate_field, vector_len);
4240     evmovdqul(dst, src, Assembler::AVX_512bit);
4241   } else if (dst_enc < 16) {
4242     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4243     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4244     vandpd(dst, xmm0, negate_field, vector_len);
4245     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4246   } else {
4247     if (src_enc != dst_enc) {
4248       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4249       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4250       vandpd(xmm0, xmm0, negate_field, vector_len);
4251       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4252       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4253     } else {
4254       subptr(rsp, 64);
4255       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4256       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4257       vandpd(xmm0, xmm0, negate_field, vector_len);
4258       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4259       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4260       addptr(rsp, 64);
4261     }
4262   }
4263 }
4264 
4265 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4266   int dst_enc = dst->encoding();
4267   int nds_enc = nds->encoding();
4268   int src_enc = src->encoding();
4269   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4270     Assembler::vpaddb(dst, nds, src, vector_len);
4271   } else if ((dst_enc < 16) && (src_enc < 16)) {
4272     Assembler::vpaddb(dst, dst, src, vector_len);
4273   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4274     // use nds as scratch for src
4275     evmovdqul(nds, src, Assembler::AVX_512bit);
4276     Assembler::vpaddb(dst, dst, nds, vector_len);
4277   } else if ((src_enc < 16) && (nds_enc < 16)) {
4278     // use nds as scratch for dst
4279     evmovdqul(nds, dst, Assembler::AVX_512bit);
4280     Assembler::vpaddb(nds, nds, src, vector_len);
4281     evmovdqul(dst, nds, Assembler::AVX_512bit);
4282   } else if (dst_enc < 16) {
4283     // use nds as scatch for xmm0 to hold src
4284     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4285     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4286     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4287     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4288   } else {
4289     // worse case scenario, all regs are in the upper bank
4290     subptr(rsp, 64);
4291     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4292     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4293     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4294     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4295     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4296     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4297     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4298     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4299     addptr(rsp, 64);
4300   }
4301 }
4302 
4303 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4304   int dst_enc = dst->encoding();
4305   int nds_enc = nds->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) {
4309     Assembler::vpaddb(dst, dst, src, vector_len);
4310   } else if (nds_enc < 16) {
4311     // implies dst_enc in upper bank with src as scratch
4312     evmovdqul(nds, dst, Assembler::AVX_512bit);
4313     Assembler::vpaddb(nds, nds, src, vector_len);
4314     evmovdqul(dst, nds, Assembler::AVX_512bit);
4315   } else {
4316     // worse case scenario, all regs in upper bank
4317     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4318     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4319     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4320     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4321   }
4322 }
4323 
4324 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4325   int dst_enc = dst->encoding();
4326   int nds_enc = nds->encoding();
4327   int src_enc = src->encoding();
4328   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4329     Assembler::vpaddw(dst, nds, src, vector_len);
4330   } else if ((dst_enc < 16) && (src_enc < 16)) {
4331     Assembler::vpaddw(dst, dst, src, vector_len);
4332   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4333     // use nds as scratch for src
4334     evmovdqul(nds, src, Assembler::AVX_512bit);
4335     Assembler::vpaddw(dst, dst, nds, vector_len);
4336   } else if ((src_enc < 16) && (nds_enc < 16)) {
4337     // use nds as scratch for dst
4338     evmovdqul(nds, dst, Assembler::AVX_512bit);
4339     Assembler::vpaddw(nds, nds, src, vector_len);
4340     evmovdqul(dst, nds, Assembler::AVX_512bit);
4341   } else if (dst_enc < 16) {
4342     // use nds as scatch for xmm0 to hold src
4343     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4344     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4345     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4346     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4347   } else {
4348     // worse case scenario, all regs are in the upper bank
4349     subptr(rsp, 64);
4350     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4351     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4352     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4353     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4354     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4355     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4356     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4357     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4358     addptr(rsp, 64);
4359   }
4360 }
4361 
4362 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4363   int dst_enc = dst->encoding();
4364   int nds_enc = nds->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) {
4368     Assembler::vpaddw(dst, dst, src, vector_len);
4369   } else if (nds_enc < 16) {
4370     // implies dst_enc in upper bank with src as scratch
4371     evmovdqul(nds, dst, Assembler::AVX_512bit);
4372     Assembler::vpaddw(nds, nds, src, vector_len);
4373     evmovdqul(dst, nds, Assembler::AVX_512bit);
4374   } else {
4375     // worse case scenario, all regs in upper bank
4376     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4377     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4378     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4379     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4380   }
4381 }
4382 
4383 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4384   if (reachable(src)) {
4385     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4386   } else {
4387     lea(rscratch1, src);
4388     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4389   }
4390 }
4391 
4392 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4393   int dst_enc = dst->encoding();
4394   int src_enc = src->encoding();
4395   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4396     Assembler::vpbroadcastw(dst, src);
4397   } else if ((dst_enc < 16) && (src_enc < 16)) {
4398     Assembler::vpbroadcastw(dst, src);
4399   } else if (src_enc < 16) {
4400     subptr(rsp, 64);
4401     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4402     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4403     Assembler::vpbroadcastw(xmm0, src);
4404     movdqu(dst, xmm0);
4405     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4406     addptr(rsp, 64);
4407   } else if (dst_enc < 16) {
4408     subptr(rsp, 64);
4409     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4410     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4411     Assembler::vpbroadcastw(dst, xmm0);
4412     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4413     addptr(rsp, 64);
4414   } else {
4415     subptr(rsp, 64);
4416     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4417     subptr(rsp, 64);
4418     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4419     movdqu(xmm0, src);
4420     movdqu(xmm1, dst);
4421     Assembler::vpbroadcastw(xmm1, xmm0);
4422     movdqu(dst, xmm1);
4423     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4424     addptr(rsp, 64);
4425     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4426     addptr(rsp, 64);
4427   }
4428 }
4429 
4430 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4431   int dst_enc = dst->encoding();
4432   int nds_enc = nds->encoding();
4433   int src_enc = src->encoding();
4434   assert(dst_enc == nds_enc, "");
4435   if ((dst_enc < 16) && (src_enc < 16)) {
4436     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4437   } else if (src_enc < 16) {
4438     subptr(rsp, 64);
4439     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4440     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4441     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4442     movdqu(dst, xmm0);
4443     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4444     addptr(rsp, 64);
4445   } else if (dst_enc < 16) {
4446     subptr(rsp, 64);
4447     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4448     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4449     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4450     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4451     addptr(rsp, 64);
4452   } else {
4453     subptr(rsp, 64);
4454     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4455     subptr(rsp, 64);
4456     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4457     movdqu(xmm0, src);
4458     movdqu(xmm1, dst);
4459     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4460     movdqu(dst, xmm1);
4461     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4462     addptr(rsp, 64);
4463     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4464     addptr(rsp, 64);
4465   }
4466 }
4467 
4468 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4469   int dst_enc = dst->encoding();
4470   int nds_enc = nds->encoding();
4471   int src_enc = src->encoding();
4472   assert(dst_enc == nds_enc, "");
4473   if ((dst_enc < 16) && (src_enc < 16)) {
4474     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4475   } else if (src_enc < 16) {
4476     subptr(rsp, 64);
4477     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4478     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4479     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4480     movdqu(dst, xmm0);
4481     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4482     addptr(rsp, 64);
4483   } else if (dst_enc < 16) {
4484     subptr(rsp, 64);
4485     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4486     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4487     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4488     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4489     addptr(rsp, 64);
4490   } else {
4491     subptr(rsp, 64);
4492     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4493     subptr(rsp, 64);
4494     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4495     movdqu(xmm0, src);
4496     movdqu(xmm1, dst);
4497     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4498     movdqu(dst, xmm1);
4499     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4500     addptr(rsp, 64);
4501     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4502     addptr(rsp, 64);
4503   }
4504 }
4505 
4506 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4507   int dst_enc = dst->encoding();
4508   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4509     Assembler::vpmovzxbw(dst, src, vector_len);
4510   } else if (dst_enc < 16) {
4511     Assembler::vpmovzxbw(dst, src, vector_len);
4512   } else {
4513     subptr(rsp, 64);
4514     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4515     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4516     Assembler::vpmovzxbw(xmm0, src, vector_len);
4517     movdqu(dst, xmm0);
4518     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4519     addptr(rsp, 64);
4520   }
4521 }
4522 
4523 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4524   int src_enc = src->encoding();
4525   if (src_enc < 16) {
4526     Assembler::vpmovmskb(dst, src);
4527   } else {
4528     subptr(rsp, 64);
4529     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4530     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4531     Assembler::vpmovmskb(dst, xmm0);
4532     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4533     addptr(rsp, 64);
4534   }
4535 }
4536 
4537 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4538   int dst_enc = dst->encoding();
4539   int nds_enc = nds->encoding();
4540   int src_enc = src->encoding();
4541   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4542     Assembler::vpmullw(dst, nds, src, vector_len);
4543   } else if ((dst_enc < 16) && (src_enc < 16)) {
4544     Assembler::vpmullw(dst, dst, src, vector_len);
4545   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4546     // use nds as scratch for src
4547     evmovdqul(nds, src, Assembler::AVX_512bit);
4548     Assembler::vpmullw(dst, dst, nds, vector_len);
4549   } else if ((src_enc < 16) && (nds_enc < 16)) {
4550     // use nds as scratch for dst
4551     evmovdqul(nds, dst, Assembler::AVX_512bit);
4552     Assembler::vpmullw(nds, nds, src, vector_len);
4553     evmovdqul(dst, nds, Assembler::AVX_512bit);
4554   } else if (dst_enc < 16) {
4555     // use nds as scatch for xmm0 to hold src
4556     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4557     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4558     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4559     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4560   } else {
4561     // worse case scenario, all regs are in the upper bank
4562     subptr(rsp, 64);
4563     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4564     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4565     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4566     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4567     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4568     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4569     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4570     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4571     addptr(rsp, 64);
4572   }
4573 }
4574 
4575 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4576   int dst_enc = dst->encoding();
4577   int nds_enc = nds->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) {
4581     Assembler::vpmullw(dst, dst, src, vector_len);
4582   } else if (nds_enc < 16) {
4583     // implies dst_enc in upper bank with src as scratch
4584     evmovdqul(nds, dst, Assembler::AVX_512bit);
4585     Assembler::vpmullw(nds, nds, src, vector_len);
4586     evmovdqul(dst, nds, Assembler::AVX_512bit);
4587   } else {
4588     // worse case scenario, all regs in upper bank
4589     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4590     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4591     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4592     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4593   }
4594 }
4595 
4596 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4597   int dst_enc = dst->encoding();
4598   int nds_enc = nds->encoding();
4599   int src_enc = src->encoding();
4600   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4601     Assembler::vpsubb(dst, nds, src, vector_len);
4602   } else if ((dst_enc < 16) && (src_enc < 16)) {
4603     Assembler::vpsubb(dst, dst, src, vector_len);
4604   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4605     // use nds as scratch for src
4606     evmovdqul(nds, src, Assembler::AVX_512bit);
4607     Assembler::vpsubb(dst, dst, nds, vector_len);
4608   } else if ((src_enc < 16) && (nds_enc < 16)) {
4609     // use nds as scratch for dst
4610     evmovdqul(nds, dst, Assembler::AVX_512bit);
4611     Assembler::vpsubb(nds, nds, src, vector_len);
4612     evmovdqul(dst, nds, Assembler::AVX_512bit);
4613   } else if (dst_enc < 16) {
4614     // use nds as scatch for xmm0 to hold src
4615     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4616     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4617     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4618     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4619   } else {
4620     // worse case scenario, all regs are in the upper bank
4621     subptr(rsp, 64);
4622     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4623     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4624     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4625     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4626     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4627     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4628     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4629     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4630     addptr(rsp, 64);
4631   }
4632 }
4633 
4634 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4635   int dst_enc = dst->encoding();
4636   int nds_enc = nds->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) {
4640     Assembler::vpsubb(dst, dst, src, vector_len);
4641   } else if (nds_enc < 16) {
4642     // implies dst_enc in upper bank with src as scratch
4643     evmovdqul(nds, dst, Assembler::AVX_512bit);
4644     Assembler::vpsubb(nds, nds, src, vector_len);
4645     evmovdqul(dst, nds, Assembler::AVX_512bit);
4646   } else {
4647     // worse case scenario, all regs in upper bank
4648     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4649     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4650     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4651     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4652   }
4653 }
4654 
4655 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4656   int dst_enc = dst->encoding();
4657   int nds_enc = nds->encoding();
4658   int src_enc = src->encoding();
4659   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4660     Assembler::vpsubw(dst, nds, src, vector_len);
4661   } else if ((dst_enc < 16) && (src_enc < 16)) {
4662     Assembler::vpsubw(dst, dst, src, vector_len);
4663   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4664     // use nds as scratch for src
4665     evmovdqul(nds, src, Assembler::AVX_512bit);
4666     Assembler::vpsubw(dst, dst, nds, vector_len);
4667   } else if ((src_enc < 16) && (nds_enc < 16)) {
4668     // use nds as scratch for dst
4669     evmovdqul(nds, dst, Assembler::AVX_512bit);
4670     Assembler::vpsubw(nds, nds, src, vector_len);
4671     evmovdqul(dst, nds, Assembler::AVX_512bit);
4672   } else if (dst_enc < 16) {
4673     // use nds as scatch for xmm0 to hold src
4674     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4675     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4676     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4677     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4678   } else {
4679     // worse case scenario, all regs are in the upper bank
4680     subptr(rsp, 64);
4681     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4682     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4683     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4684     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4685     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4686     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4687     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4688     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4689     addptr(rsp, 64);
4690   }
4691 }
4692 
4693 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4694   int dst_enc = dst->encoding();
4695   int nds_enc = nds->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) {
4699     Assembler::vpsubw(dst, dst, src, vector_len);
4700   } else if (nds_enc < 16) {
4701     // implies dst_enc in upper bank with src as scratch
4702     evmovdqul(nds, dst, Assembler::AVX_512bit);
4703     Assembler::vpsubw(nds, nds, src, vector_len);
4704     evmovdqul(dst, nds, Assembler::AVX_512bit);
4705   } else {
4706     // worse case scenario, all regs in upper bank
4707     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4708     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4709     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4710     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4711   }
4712 }
4713 
4714 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4715   int dst_enc = dst->encoding();
4716   int nds_enc = nds->encoding();
4717   int shift_enc = shift->encoding();
4718   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4719     Assembler::vpsraw(dst, nds, shift, vector_len);
4720   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4721     Assembler::vpsraw(dst, dst, shift, vector_len);
4722   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4723     // use nds_enc as scratch with shift
4724     evmovdqul(nds, shift, Assembler::AVX_512bit);
4725     Assembler::vpsraw(dst, dst, nds, vector_len);
4726   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4727     // use nds as scratch with dst
4728     evmovdqul(nds, dst, Assembler::AVX_512bit);
4729     Assembler::vpsraw(nds, nds, shift, vector_len);
4730     evmovdqul(dst, nds, Assembler::AVX_512bit);
4731   } else if (dst_enc < 16) {
4732     // use nds to save a copy of xmm0 and hold shift
4733     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4734     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4735     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4736     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4737   } else if (nds_enc < 16) {
4738     // use nds as dest as temps
4739     evmovdqul(nds, dst, Assembler::AVX_512bit);
4740     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4741     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4742     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4743     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4744     evmovdqul(dst, nds, Assembler::AVX_512bit);
4745   } else {
4746     // worse case scenario, all regs are in the upper bank
4747     subptr(rsp, 64);
4748     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4749     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4750     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4751     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4752     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4753     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4754     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4755     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4756     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4757     addptr(rsp, 64);
4758   }
4759 }
4760 
4761 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4762   int dst_enc = dst->encoding();
4763   int nds_enc = nds->encoding();
4764   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4765     Assembler::vpsraw(dst, nds, shift, vector_len);
4766   } else if (dst_enc < 16) {
4767     Assembler::vpsraw(dst, dst, shift, vector_len);
4768   } else if (nds_enc < 16) {
4769     // use nds as scratch
4770     evmovdqul(nds, dst, Assembler::AVX_512bit);
4771     Assembler::vpsraw(nds, nds, shift, vector_len);
4772     evmovdqul(dst, nds, Assembler::AVX_512bit);
4773   } else {
4774     // use nds as scratch for xmm0
4775     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4776     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4777     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4778     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4779   }
4780 }
4781 
4782 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4783   int dst_enc = dst->encoding();
4784   int nds_enc = nds->encoding();
4785   int shift_enc = shift->encoding();
4786   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4787     Assembler::vpsrlw(dst, nds, shift, vector_len);
4788   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4789     Assembler::vpsrlw(dst, dst, shift, vector_len);
4790   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4791     // use nds_enc as scratch with shift
4792     evmovdqul(nds, shift, Assembler::AVX_512bit);
4793     Assembler::vpsrlw(dst, dst, nds, vector_len);
4794   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4795     // use nds as scratch with dst
4796     evmovdqul(nds, dst, Assembler::AVX_512bit);
4797     Assembler::vpsrlw(nds, nds, shift, vector_len);
4798     evmovdqul(dst, nds, Assembler::AVX_512bit);
4799   } else if (dst_enc < 16) {
4800     // use nds to save a copy of xmm0 and hold shift
4801     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4802     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4803     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4804     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4805   } else if (nds_enc < 16) {
4806     // use nds as dest as temps
4807     evmovdqul(nds, dst, Assembler::AVX_512bit);
4808     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4809     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4810     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4811     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4812     evmovdqul(dst, nds, Assembler::AVX_512bit);
4813   } else {
4814     // worse case scenario, all regs are in the upper bank
4815     subptr(rsp, 64);
4816     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4817     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4818     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4819     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4820     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4821     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4822     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4823     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4824     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4825     addptr(rsp, 64);
4826   }
4827 }
4828 
4829 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4830   int dst_enc = dst->encoding();
4831   int nds_enc = nds->encoding();
4832   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4833     Assembler::vpsrlw(dst, nds, shift, vector_len);
4834   } else if (dst_enc < 16) {
4835     Assembler::vpsrlw(dst, dst, shift, vector_len);
4836   } else if (nds_enc < 16) {
4837     // use nds as scratch
4838     evmovdqul(nds, dst, Assembler::AVX_512bit);
4839     Assembler::vpsrlw(nds, nds, shift, vector_len);
4840     evmovdqul(dst, nds, Assembler::AVX_512bit);
4841   } else {
4842     // use nds as scratch for xmm0
4843     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4844     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4845     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4846     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4847   }
4848 }
4849 
4850 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4851   int dst_enc = dst->encoding();
4852   int nds_enc = nds->encoding();
4853   int shift_enc = shift->encoding();
4854   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4855     Assembler::vpsllw(dst, nds, shift, vector_len);
4856   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4857     Assembler::vpsllw(dst, dst, shift, vector_len);
4858   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4859     // use nds_enc as scratch with shift
4860     evmovdqul(nds, shift, Assembler::AVX_512bit);
4861     Assembler::vpsllw(dst, dst, nds, vector_len);
4862   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4863     // use nds as scratch with dst
4864     evmovdqul(nds, dst, Assembler::AVX_512bit);
4865     Assembler::vpsllw(nds, nds, shift, vector_len);
4866     evmovdqul(dst, nds, Assembler::AVX_512bit);
4867   } else if (dst_enc < 16) {
4868     // use nds to save a copy of xmm0 and hold shift
4869     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4870     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4871     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4872     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4873   } else if (nds_enc < 16) {
4874     // use nds as dest as temps
4875     evmovdqul(nds, dst, Assembler::AVX_512bit);
4876     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4877     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4878     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4879     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4880     evmovdqul(dst, nds, Assembler::AVX_512bit);
4881   } else {
4882     // worse case scenario, all regs are in the upper bank
4883     subptr(rsp, 64);
4884     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4885     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4886     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4887     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4888     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4889     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4890     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4891     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4892     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4893     addptr(rsp, 64);
4894   }
4895 }
4896 
4897 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4898   int dst_enc = dst->encoding();
4899   int nds_enc = nds->encoding();
4900   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4901     Assembler::vpsllw(dst, nds, shift, vector_len);
4902   } else if (dst_enc < 16) {
4903     Assembler::vpsllw(dst, dst, shift, vector_len);
4904   } else if (nds_enc < 16) {
4905     // use nds as scratch
4906     evmovdqul(nds, dst, Assembler::AVX_512bit);
4907     Assembler::vpsllw(nds, nds, shift, vector_len);
4908     evmovdqul(dst, nds, Assembler::AVX_512bit);
4909   } else {
4910     // use nds as scratch for xmm0
4911     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4912     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4913     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4914     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4915   }
4916 }
4917 
4918 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4919   int dst_enc = dst->encoding();
4920   int src_enc = src->encoding();
4921   if ((dst_enc < 16) && (src_enc < 16)) {
4922     Assembler::vptest(dst, src);
4923   } else if (src_enc < 16) {
4924     subptr(rsp, 64);
4925     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4926     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4927     Assembler::vptest(xmm0, src);
4928     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4929     addptr(rsp, 64);
4930   } else if (dst_enc < 16) {
4931     subptr(rsp, 64);
4932     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4933     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4934     Assembler::vptest(dst, xmm0);
4935     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4936     addptr(rsp, 64);
4937   } else {
4938     subptr(rsp, 64);
4939     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4940     subptr(rsp, 64);
4941     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4942     movdqu(xmm0, src);
4943     movdqu(xmm1, dst);
4944     Assembler::vptest(xmm1, xmm0);
4945     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4946     addptr(rsp, 64);
4947     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4948     addptr(rsp, 64);
4949   }
4950 }
4951 
4952 // This instruction exists within macros, ergo we cannot control its input
4953 // when emitted through those patterns.
4954 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4955   if (VM_Version::supports_avx512nobw()) {
4956     int dst_enc = dst->encoding();
4957     int src_enc = src->encoding();
4958     if (dst_enc == src_enc) {
4959       if (dst_enc < 16) {
4960         Assembler::punpcklbw(dst, src);
4961       } else {
4962         subptr(rsp, 64);
4963         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4964         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4965         Assembler::punpcklbw(xmm0, xmm0);
4966         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4967         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4968         addptr(rsp, 64);
4969       }
4970     } else {
4971       if ((src_enc < 16) && (dst_enc < 16)) {
4972         Assembler::punpcklbw(dst, src);
4973       } else if (src_enc < 16) {
4974         subptr(rsp, 64);
4975         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4976         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4977         Assembler::punpcklbw(xmm0, src);
4978         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4979         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4980         addptr(rsp, 64);
4981       } else if (dst_enc < 16) {
4982         subptr(rsp, 64);
4983         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4984         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4985         Assembler::punpcklbw(dst, xmm0);
4986         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4987         addptr(rsp, 64);
4988       } else {
4989         subptr(rsp, 64);
4990         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4991         subptr(rsp, 64);
4992         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4993         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4994         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4995         Assembler::punpcklbw(xmm0, xmm1);
4996         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4997         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4998         addptr(rsp, 64);
4999         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5000         addptr(rsp, 64);
5001       }
5002     }
5003   } else {
5004     Assembler::punpcklbw(dst, src);
5005   }
5006 }
5007 
5008 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5009   if (VM_Version::supports_avx512vl()) {
5010     Assembler::pshufd(dst, src, mode);
5011   } else {
5012     int dst_enc = dst->encoding();
5013     if (dst_enc < 16) {
5014       Assembler::pshufd(dst, src, mode);
5015     } else {
5016       subptr(rsp, 64);
5017       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5018       Assembler::pshufd(xmm0, src, mode);
5019       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5020       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5021       addptr(rsp, 64);
5022     }
5023   }
5024 }
5025 
5026 // This instruction exists within macros, ergo we cannot control its input
5027 // when emitted through those patterns.
5028 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5029   if (VM_Version::supports_avx512nobw()) {
5030     int dst_enc = dst->encoding();
5031     int src_enc = src->encoding();
5032     if (dst_enc == src_enc) {
5033       if (dst_enc < 16) {
5034         Assembler::pshuflw(dst, src, mode);
5035       } else {
5036         subptr(rsp, 64);
5037         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5038         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5039         Assembler::pshuflw(xmm0, xmm0, mode);
5040         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5041         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5042         addptr(rsp, 64);
5043       }
5044     } else {
5045       if ((src_enc < 16) && (dst_enc < 16)) {
5046         Assembler::pshuflw(dst, src, mode);
5047       } else if (src_enc < 16) {
5048         subptr(rsp, 64);
5049         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5050         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5051         Assembler::pshuflw(xmm0, src, mode);
5052         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5053         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5054         addptr(rsp, 64);
5055       } else if (dst_enc < 16) {
5056         subptr(rsp, 64);
5057         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5058         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5059         Assembler::pshuflw(dst, xmm0, mode);
5060         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5061         addptr(rsp, 64);
5062       } else {
5063         subptr(rsp, 64);
5064         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065         subptr(rsp, 64);
5066         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5067         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5068         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5069         Assembler::pshuflw(xmm0, xmm1, mode);
5070         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5071         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5072         addptr(rsp, 64);
5073         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5074         addptr(rsp, 64);
5075       }
5076     }
5077   } else {
5078     Assembler::pshuflw(dst, src, mode);
5079   }
5080 }
5081 
5082 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5083   if (reachable(src)) {
5084     vandpd(dst, nds, as_Address(src), vector_len);
5085   } else {
5086     lea(rscratch1, src);
5087     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5088   }
5089 }
5090 
5091 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5092   if (reachable(src)) {
5093     vandps(dst, nds, as_Address(src), vector_len);
5094   } else {
5095     lea(rscratch1, src);
5096     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5097   }
5098 }
5099 
5100 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5101   if (reachable(src)) {
5102     vdivsd(dst, nds, as_Address(src));
5103   } else {
5104     lea(rscratch1, src);
5105     vdivsd(dst, nds, Address(rscratch1, 0));
5106   }
5107 }
5108 
5109 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5110   if (reachable(src)) {
5111     vdivss(dst, nds, as_Address(src));
5112   } else {
5113     lea(rscratch1, src);
5114     vdivss(dst, nds, Address(rscratch1, 0));
5115   }
5116 }
5117 
5118 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5119   if (reachable(src)) {
5120     vmulsd(dst, nds, as_Address(src));
5121   } else {
5122     lea(rscratch1, src);
5123     vmulsd(dst, nds, Address(rscratch1, 0));
5124   }
5125 }
5126 
5127 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5128   if (reachable(src)) {
5129     vmulss(dst, nds, as_Address(src));
5130   } else {
5131     lea(rscratch1, src);
5132     vmulss(dst, nds, Address(rscratch1, 0));
5133   }
5134 }
5135 
5136 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5137   if (reachable(src)) {
5138     vsubsd(dst, nds, as_Address(src));
5139   } else {
5140     lea(rscratch1, src);
5141     vsubsd(dst, nds, Address(rscratch1, 0));
5142   }
5143 }
5144 
5145 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5146   if (reachable(src)) {
5147     vsubss(dst, nds, as_Address(src));
5148   } else {
5149     lea(rscratch1, src);
5150     vsubss(dst, nds, Address(rscratch1, 0));
5151   }
5152 }
5153 
5154 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5155   int nds_enc = nds->encoding();
5156   int dst_enc = dst->encoding();
5157   bool dst_upper_bank = (dst_enc > 15);
5158   bool nds_upper_bank = (nds_enc > 15);
5159   if (VM_Version::supports_avx512novl() &&
5160       (nds_upper_bank || dst_upper_bank)) {
5161     if (dst_upper_bank) {
5162       subptr(rsp, 64);
5163       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5164       movflt(xmm0, nds);
5165       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5166       movflt(dst, xmm0);
5167       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5168       addptr(rsp, 64);
5169     } else {
5170       movflt(dst, nds);
5171       vxorps(dst, dst, src, Assembler::AVX_128bit);
5172     }
5173   } else {
5174     vxorps(dst, nds, src, Assembler::AVX_128bit);
5175   }
5176 }
5177 
5178 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5179   int nds_enc = nds->encoding();
5180   int dst_enc = dst->encoding();
5181   bool dst_upper_bank = (dst_enc > 15);
5182   bool nds_upper_bank = (nds_enc > 15);
5183   if (VM_Version::supports_avx512novl() &&
5184       (nds_upper_bank || dst_upper_bank)) {
5185     if (dst_upper_bank) {
5186       subptr(rsp, 64);
5187       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5188       movdbl(xmm0, nds);
5189       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5190       movdbl(dst, xmm0);
5191       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5192       addptr(rsp, 64);
5193     } else {
5194       movdbl(dst, nds);
5195       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5196     }
5197   } else {
5198     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5199   }
5200 }
5201 
5202 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5203   if (reachable(src)) {
5204     vxorpd(dst, nds, as_Address(src), vector_len);
5205   } else {
5206     lea(rscratch1, src);
5207     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5208   }
5209 }
5210 
5211 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5212   if (reachable(src)) {
5213     vxorps(dst, nds, as_Address(src), vector_len);
5214   } else {
5215     lea(rscratch1, src);
5216     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5217   }
5218 }
5219 
5220 
5221 void MacroAssembler::resolve_jobject(Register value,
5222                                      Register thread,
5223                                      Register tmp) {
5224   assert_different_registers(value, thread, tmp);
5225   Label done, not_weak;
5226   testptr(value, value);
5227   jcc(Assembler::zero, done);                // Use NULL as-is.
5228   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5229   jcc(Assembler::zero, not_weak);
5230   // Resolve jweak.
5231   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5232   verify_oop(value);
5233 #if INCLUDE_ALL_GCS
5234   if (UseG1GC) {
5235     g1_write_barrier_pre(noreg /* obj */,
5236                          value /* pre_val */,
5237                          thread /* thread */,
5238                          tmp /* tmp */,
5239                          true /* tosca_live */,
5240                          true /* expand_call */);
5241   }
5242 #endif // INCLUDE_ALL_GCS
5243   jmp(done);
5244   bind(not_weak);
5245   // Resolve (untagged) jobject.
5246   movptr(value, Address(value, 0));
5247   verify_oop(value);
5248   bind(done);
5249 }
5250 
5251 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5252   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5253   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5254   // The inverted mask is sign-extended
5255   andptr(possibly_jweak, inverted_jweak_mask);
5256 }
5257 
5258 //////////////////////////////////////////////////////////////////////////////////
5259 #if INCLUDE_ALL_GCS
5260 
5261 void MacroAssembler::g1_write_barrier_pre(Register obj,
5262                                           Register pre_val,
5263                                           Register thread,
5264                                           Register tmp,
5265                                           bool tosca_live,
5266                                           bool expand_call) {
5267 
5268   // If expand_call is true then we expand the call_VM_leaf macro
5269   // directly to skip generating the check by
5270   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5271 
5272 #ifdef _LP64
5273   assert(thread == r15_thread, "must be");
5274 #endif // _LP64
5275 
5276   Label done;
5277   Label runtime;
5278 
5279   assert(pre_val != noreg, "check this code");
5280 
5281   if (obj != noreg) {
5282     assert_different_registers(obj, pre_val, tmp);
5283     assert(pre_val != rax, "check this code");
5284   }
5285 
5286   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5287                                        SATBMarkQueue::byte_offset_of_active()));
5288   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5289                                        SATBMarkQueue::byte_offset_of_index()));
5290   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5291                                        SATBMarkQueue::byte_offset_of_buf()));
5292 
5293 
5294   // Is marking active?
5295   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5296     cmpl(in_progress, 0);
5297   } else {
5298     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5299     cmpb(in_progress, 0);
5300   }
5301   jcc(Assembler::equal, done);
5302 
5303   // Do we need to load the previous value?
5304   if (obj != noreg) {
5305     load_heap_oop(pre_val, Address(obj, 0));
5306   }
5307 
5308   // Is the previous value null?
5309   cmpptr(pre_val, (int32_t) NULL_WORD);
5310   jcc(Assembler::equal, done);
5311 
5312   // Can we store original value in the thread's buffer?
5313   // Is index == 0?
5314   // (The index field is typed as size_t.)
5315 
5316   movptr(tmp, index);                   // tmp := *index_adr
5317   cmpptr(tmp, 0);                       // tmp == 0?
5318   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5319 
5320   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5321   movptr(index, tmp);                   // *index_adr := tmp
5322   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5323 
5324   // Record the previous value
5325   movptr(Address(tmp, 0), pre_val);
5326   jmp(done);
5327 
5328   bind(runtime);
5329   // save the live input values
5330   if(tosca_live) push(rax);
5331 
5332   if (obj != noreg && obj != rax)
5333     push(obj);
5334 
5335   if (pre_val != rax)
5336     push(pre_val);
5337 
5338   // Calling the runtime using the regular call_VM_leaf mechanism generates
5339   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5340   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5341   //
5342   // If we care generating the pre-barrier without a frame (e.g. in the
5343   // intrinsified Reference.get() routine) then ebp might be pointing to
5344   // the caller frame and so this check will most likely fail at runtime.
5345   //
5346   // Expanding the call directly bypasses the generation of the check.
5347   // So when we do not have have a full interpreter frame on the stack
5348   // expand_call should be passed true.
5349 
5350   NOT_LP64( push(thread); )
5351 
5352   if (expand_call) {
5353     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5354     pass_arg1(this, thread);
5355     pass_arg0(this, pre_val);
5356     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5357   } else {
5358     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5359   }
5360 
5361   NOT_LP64( pop(thread); )
5362 
5363   // save the live input values
5364   if (pre_val != rax)
5365     pop(pre_val);
5366 
5367   if (obj != noreg && obj != rax)
5368     pop(obj);
5369 
5370   if(tosca_live) pop(rax);
5371 
5372   bind(done);
5373 }
5374 
5375 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5376                                            Register new_val,
5377                                            Register thread,
5378                                            Register tmp,
5379                                            Register tmp2) {
5380 #ifdef _LP64
5381   assert(thread == r15_thread, "must be");
5382 #endif // _LP64
5383 
5384   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5385                                        DirtyCardQueue::byte_offset_of_index()));
5386   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5387                                        DirtyCardQueue::byte_offset_of_buf()));
5388 
5389   CardTableModRefBS* ct =
5390     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5391   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5392 
5393   Label done;
5394   Label runtime;
5395 
5396   // Does store cross heap regions?
5397 
5398   movptr(tmp, store_addr);
5399   xorptr(tmp, new_val);
5400   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5401   jcc(Assembler::equal, done);
5402 
5403   // crosses regions, storing NULL?
5404 
5405   cmpptr(new_val, (int32_t) NULL_WORD);
5406   jcc(Assembler::equal, done);
5407 
5408   // storing region crossing non-NULL, is card already dirty?
5409 
5410   const Register card_addr = tmp;
5411   const Register cardtable = tmp2;
5412 
5413   movptr(card_addr, store_addr);
5414   shrptr(card_addr, CardTableModRefBS::card_shift);
5415   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5416   // a valid address and therefore is not properly handled by the relocation code.
5417   movptr(cardtable, (intptr_t)ct->byte_map_base);
5418   addptr(card_addr, cardtable);
5419 
5420   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5421   jcc(Assembler::equal, done);
5422 
5423   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5424   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5425   jcc(Assembler::equal, done);
5426 
5427 
5428   // storing a region crossing, non-NULL oop, card is clean.
5429   // dirty card and log.
5430 
5431   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5432 
5433   cmpl(queue_index, 0);
5434   jcc(Assembler::equal, runtime);
5435   subl(queue_index, wordSize);
5436   movptr(tmp2, buffer);
5437 #ifdef _LP64
5438   movslq(rscratch1, queue_index);
5439   addq(tmp2, rscratch1);
5440   movq(Address(tmp2, 0), card_addr);
5441 #else
5442   addl(tmp2, queue_index);
5443   movl(Address(tmp2, 0), card_addr);
5444 #endif
5445   jmp(done);
5446 
5447   bind(runtime);
5448   // save the live input values
5449   push(store_addr);
5450   push(new_val);
5451 #ifdef _LP64
5452   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5453 #else
5454   push(thread);
5455   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5456   pop(thread);
5457 #endif
5458   pop(new_val);
5459   pop(store_addr);
5460 
5461   bind(done);
5462 }
5463 
5464 #endif // INCLUDE_ALL_GCS
5465 //////////////////////////////////////////////////////////////////////////////////
5466 
5467 
5468 void MacroAssembler::store_check(Register obj, Address dst) {
5469   store_check(obj);
5470 }
5471 
5472 void MacroAssembler::store_check(Register obj) {
5473   // Does a store check for the oop in register obj. The content of
5474   // register obj is destroyed afterwards.
5475   BarrierSet* bs = Universe::heap()->barrier_set();
5476   assert(bs->kind() == BarrierSet::CardTableForRS ||
5477          bs->kind() == BarrierSet::CardTableExtension,
5478          "Wrong barrier set kind");
5479 
5480   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5481   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5482 
5483   shrptr(obj, CardTableModRefBS::card_shift);
5484 
5485   Address card_addr;
5486 
5487   // The calculation for byte_map_base is as follows:
5488   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5489   // So this essentially converts an address to a displacement and it will
5490   // never need to be relocated. On 64bit however the value may be too
5491   // large for a 32bit displacement.
5492   intptr_t disp = (intptr_t) ct->byte_map_base;
5493   if (is_simm32(disp)) {
5494     card_addr = Address(noreg, obj, Address::times_1, disp);
5495   } else {
5496     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5497     // displacement and done in a single instruction given favorable mapping and a
5498     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5499     // entry and that entry is not properly handled by the relocation code.
5500     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5501     Address index(noreg, obj, Address::times_1);
5502     card_addr = as_Address(ArrayAddress(cardtable, index));
5503   }
5504 
5505   int dirty = CardTableModRefBS::dirty_card_val();
5506   if (UseCondCardMark) {
5507     Label L_already_dirty;
5508     if (UseConcMarkSweepGC) {
5509       membar(Assembler::StoreLoad);
5510     }
5511     cmpb(card_addr, dirty);
5512     jcc(Assembler::equal, L_already_dirty);
5513     movb(card_addr, dirty);
5514     bind(L_already_dirty);
5515   } else {
5516     movb(card_addr, dirty);
5517   }
5518 }
5519 
5520 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5521   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5522 }
5523 
5524 // Force generation of a 4 byte immediate value even if it fits into 8bit
5525 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5526   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5527 }
5528 
5529 void MacroAssembler::subptr(Register dst, Register src) {
5530   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5531 }
5532 
5533 // C++ bool manipulation
5534 void MacroAssembler::testbool(Register dst) {
5535   if(sizeof(bool) == 1)
5536     testb(dst, 0xff);
5537   else if(sizeof(bool) == 2) {
5538     // testw implementation needed for two byte bools
5539     ShouldNotReachHere();
5540   } else if(sizeof(bool) == 4)
5541     testl(dst, dst);
5542   else
5543     // unsupported
5544     ShouldNotReachHere();
5545 }
5546 
5547 void MacroAssembler::testptr(Register dst, Register src) {
5548   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5549 }
5550 
5551 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5552 void MacroAssembler::tlab_allocate(Register obj,
5553                                    Register var_size_in_bytes,
5554                                    int con_size_in_bytes,
5555                                    Register t1,
5556                                    Register t2,
5557                                    Label& slow_case) {
5558   assert_different_registers(obj, t1, t2);
5559   assert_different_registers(obj, var_size_in_bytes, t1);
5560   Register end = t2;
5561   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5562 
5563   verify_tlab();
5564 
5565   NOT_LP64(get_thread(thread));
5566 
5567   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5568   if (var_size_in_bytes == noreg) {
5569     lea(end, Address(obj, con_size_in_bytes));
5570   } else {
5571     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5572   }
5573   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5574   jcc(Assembler::above, slow_case);
5575 
5576   // update the tlab top pointer
5577   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5578 
5579   // recover var_size_in_bytes if necessary
5580   if (var_size_in_bytes == end) {
5581     subptr(var_size_in_bytes, obj);
5582   }
5583   verify_tlab();
5584 }
5585 
5586 // Preserves rbx, and rdx.
5587 Register MacroAssembler::tlab_refill(Label& retry,
5588                                      Label& try_eden,
5589                                      Label& slow_case) {
5590   Register top = rax;
5591   Register t1  = rcx; // object size
5592   Register t2  = rsi;
5593   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5594   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5595   Label do_refill, discard_tlab;
5596 
5597   if (!Universe::heap()->supports_inline_contig_alloc()) {
5598     // No allocation in the shared eden.
5599     jmp(slow_case);
5600   }
5601 
5602   NOT_LP64(get_thread(thread_reg));
5603 
5604   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5605   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5606 
5607   // calculate amount of free space
5608   subptr(t1, top);
5609   shrptr(t1, LogHeapWordSize);
5610 
5611   // Retain tlab and allocate object in shared space if
5612   // the amount free in the tlab is too large to discard.
5613   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5614   jcc(Assembler::lessEqual, discard_tlab);
5615 
5616   // Retain
5617   // %%% yuck as movptr...
5618   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5619   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5620   if (TLABStats) {
5621     // increment number of slow_allocations
5622     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5623   }
5624   jmp(try_eden);
5625 
5626   bind(discard_tlab);
5627   if (TLABStats) {
5628     // increment number of refills
5629     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5630     // accumulate wastage -- t1 is amount free in tlab
5631     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5632   }
5633 
5634   // if tlab is currently allocated (top or end != null) then
5635   // fill [top, end + alignment_reserve) with array object
5636   testptr(top, top);
5637   jcc(Assembler::zero, do_refill);
5638 
5639   // set up the mark word
5640   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5641   // set the length to the remaining space
5642   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5643   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5644   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5645   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5646   // set klass to intArrayKlass
5647   // dubious reloc why not an oop reloc?
5648   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5649   // store klass last.  concurrent gcs assumes klass length is valid if
5650   // klass field is not null.
5651   store_klass(top, t1);
5652 
5653   movptr(t1, top);
5654   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5655   incr_allocated_bytes(thread_reg, t1, 0);
5656 
5657   // refill the tlab with an eden allocation
5658   bind(do_refill);
5659   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5660   shlptr(t1, LogHeapWordSize);
5661   // allocate new tlab, address returned in top
5662   eden_allocate(top, t1, 0, t2, slow_case);
5663 
5664   // Check that t1 was preserved in eden_allocate.
5665 #ifdef ASSERT
5666   if (UseTLAB) {
5667     Label ok;
5668     Register tsize = rsi;
5669     assert_different_registers(tsize, thread_reg, t1);
5670     push(tsize);
5671     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5672     shlptr(tsize, LogHeapWordSize);
5673     cmpptr(t1, tsize);
5674     jcc(Assembler::equal, ok);
5675     STOP("assert(t1 != tlab size)");
5676     should_not_reach_here();
5677 
5678     bind(ok);
5679     pop(tsize);
5680   }
5681 #endif
5682   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5683   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5684   addptr(top, t1);
5685   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5686   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5687 
5688   if (ZeroTLAB) {
5689     // This is a fast TLAB refill, therefore the GC is not notified of it.
5690     // So compiled code must fill the new TLAB with zeroes.
5691     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5692     zero_memory(top, t1, 0, t2);
5693   }
5694 
5695   verify_tlab();
5696   jmp(retry);
5697 
5698   return thread_reg; // for use by caller
5699 }
5700 
5701 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5702 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5703   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5704   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5705   Label done;
5706 
5707   testptr(length_in_bytes, length_in_bytes);
5708   jcc(Assembler::zero, done);
5709 
5710   // initialize topmost word, divide index by 2, check if odd and test if zero
5711   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5712 #ifdef ASSERT
5713   {
5714     Label L;
5715     testptr(length_in_bytes, BytesPerWord - 1);
5716     jcc(Assembler::zero, L);
5717     stop("length must be a multiple of BytesPerWord");
5718     bind(L);
5719   }
5720 #endif
5721   Register index = length_in_bytes;
5722   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5723   if (UseIncDec) {
5724     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5725   } else {
5726     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5727     shrptr(index, 1);
5728   }
5729 #ifndef _LP64
5730   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5731   {
5732     Label even;
5733     // note: if index was a multiple of 8, then it cannot
5734     //       be 0 now otherwise it must have been 0 before
5735     //       => if it is even, we don't need to check for 0 again
5736     jcc(Assembler::carryClear, even);
5737     // clear topmost word (no jump would be needed if conditional assignment worked here)
5738     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5739     // index could be 0 now, must check again
5740     jcc(Assembler::zero, done);
5741     bind(even);
5742   }
5743 #endif // !_LP64
5744   // initialize remaining object fields: index is a multiple of 2 now
5745   {
5746     Label loop;
5747     bind(loop);
5748     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5749     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5750     decrement(index);
5751     jcc(Assembler::notZero, loop);
5752   }
5753 
5754   bind(done);
5755 }
5756 
5757 void MacroAssembler::incr_allocated_bytes(Register thread,
5758                                           Register var_size_in_bytes,
5759                                           int con_size_in_bytes,
5760                                           Register t1) {
5761   if (!thread->is_valid()) {
5762 #ifdef _LP64
5763     thread = r15_thread;
5764 #else
5765     assert(t1->is_valid(), "need temp reg");
5766     thread = t1;
5767     get_thread(thread);
5768 #endif
5769   }
5770 
5771 #ifdef _LP64
5772   if (var_size_in_bytes->is_valid()) {
5773     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5774   } else {
5775     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5776   }
5777 #else
5778   if (var_size_in_bytes->is_valid()) {
5779     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5780   } else {
5781     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5782   }
5783   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5784 #endif
5785 }
5786 
5787 // Look up the method for a megamorphic invokeinterface call.
5788 // The target method is determined by <intf_klass, itable_index>.
5789 // The receiver klass is in recv_klass.
5790 // On success, the result will be in method_result, and execution falls through.
5791 // On failure, execution transfers to the given label.
5792 void MacroAssembler::lookup_interface_method(Register recv_klass,
5793                                              Register intf_klass,
5794                                              RegisterOrConstant itable_index,
5795                                              Register method_result,
5796                                              Register scan_temp,
5797                                              Label& L_no_such_interface) {
5798   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5799   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5800          "caller must use same register for non-constant itable index as for method");
5801 
5802   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5803   int vtable_base = in_bytes(Klass::vtable_start_offset());
5804   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5805   int scan_step   = itableOffsetEntry::size() * wordSize;
5806   int vte_size    = vtableEntry::size_in_bytes();
5807   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5808   assert(vte_size == wordSize, "else adjust times_vte_scale");
5809 
5810   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5811 
5812   // %%% Could store the aligned, prescaled offset in the klassoop.
5813   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5814 
5815   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5816   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5817   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5818 
5819   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5820   //   if (scan->interface() == intf) {
5821   //     result = (klass + scan->offset() + itable_index);
5822   //   }
5823   // }
5824   Label search, found_method;
5825 
5826   for (int peel = 1; peel >= 0; peel--) {
5827     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5828     cmpptr(intf_klass, method_result);
5829 
5830     if (peel) {
5831       jccb(Assembler::equal, found_method);
5832     } else {
5833       jccb(Assembler::notEqual, search);
5834       // (invert the test to fall through to found_method...)
5835     }
5836 
5837     if (!peel)  break;
5838 
5839     bind(search);
5840 
5841     // Check that the previous entry is non-null.  A null entry means that
5842     // the receiver class doesn't implement the interface, and wasn't the
5843     // same as when the caller was compiled.
5844     testptr(method_result, method_result);
5845     jcc(Assembler::zero, L_no_such_interface);
5846     addptr(scan_temp, scan_step);
5847   }
5848 
5849   bind(found_method);
5850 
5851   // Got a hit.
5852   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5853   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5854 }
5855 
5856 
5857 // virtual method calling
5858 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5859                                            RegisterOrConstant vtable_index,
5860                                            Register method_result) {
5861   const int base = in_bytes(Klass::vtable_start_offset());
5862   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5863   Address vtable_entry_addr(recv_klass,
5864                             vtable_index, Address::times_ptr,
5865                             base + vtableEntry::method_offset_in_bytes());
5866   movptr(method_result, vtable_entry_addr);
5867 }
5868 
5869 
5870 void MacroAssembler::check_klass_subtype(Register sub_klass,
5871                            Register super_klass,
5872                            Register temp_reg,
5873                            Label& L_success) {
5874   Label L_failure;
5875   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5876   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5877   bind(L_failure);
5878 }
5879 
5880 
5881 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5882                                                    Register super_klass,
5883                                                    Register temp_reg,
5884                                                    Label* L_success,
5885                                                    Label* L_failure,
5886                                                    Label* L_slow_path,
5887                                         RegisterOrConstant super_check_offset) {
5888   assert_different_registers(sub_klass, super_klass, temp_reg);
5889   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5890   if (super_check_offset.is_register()) {
5891     assert_different_registers(sub_klass, super_klass,
5892                                super_check_offset.as_register());
5893   } else if (must_load_sco) {
5894     assert(temp_reg != noreg, "supply either a temp or a register offset");
5895   }
5896 
5897   Label L_fallthrough;
5898   int label_nulls = 0;
5899   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5900   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5901   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5902   assert(label_nulls <= 1, "at most one NULL in the batch");
5903 
5904   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5905   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5906   Address super_check_offset_addr(super_klass, sco_offset);
5907 
5908   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5909   // range of a jccb.  If this routine grows larger, reconsider at
5910   // least some of these.
5911 #define local_jcc(assembler_cond, label)                                \
5912   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5913   else                             jcc( assembler_cond, label) /*omit semi*/
5914 
5915   // Hacked jmp, which may only be used just before L_fallthrough.
5916 #define final_jmp(label)                                                \
5917   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5918   else                            jmp(label)                /*omit semi*/
5919 
5920   // If the pointers are equal, we are done (e.g., String[] elements).
5921   // This self-check enables sharing of secondary supertype arrays among
5922   // non-primary types such as array-of-interface.  Otherwise, each such
5923   // type would need its own customized SSA.
5924   // We move this check to the front of the fast path because many
5925   // type checks are in fact trivially successful in this manner,
5926   // so we get a nicely predicted branch right at the start of the check.
5927   cmpptr(sub_klass, super_klass);
5928   local_jcc(Assembler::equal, *L_success);
5929 
5930   // Check the supertype display:
5931   if (must_load_sco) {
5932     // Positive movl does right thing on LP64.
5933     movl(temp_reg, super_check_offset_addr);
5934     super_check_offset = RegisterOrConstant(temp_reg);
5935   }
5936   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5937   cmpptr(super_klass, super_check_addr); // load displayed supertype
5938 
5939   // This check has worked decisively for primary supers.
5940   // Secondary supers are sought in the super_cache ('super_cache_addr').
5941   // (Secondary supers are interfaces and very deeply nested subtypes.)
5942   // This works in the same check above because of a tricky aliasing
5943   // between the super_cache and the primary super display elements.
5944   // (The 'super_check_addr' can address either, as the case requires.)
5945   // Note that the cache is updated below if it does not help us find
5946   // what we need immediately.
5947   // So if it was a primary super, we can just fail immediately.
5948   // Otherwise, it's the slow path for us (no success at this point).
5949 
5950   if (super_check_offset.is_register()) {
5951     local_jcc(Assembler::equal, *L_success);
5952     cmpl(super_check_offset.as_register(), sc_offset);
5953     if (L_failure == &L_fallthrough) {
5954       local_jcc(Assembler::equal, *L_slow_path);
5955     } else {
5956       local_jcc(Assembler::notEqual, *L_failure);
5957       final_jmp(*L_slow_path);
5958     }
5959   } else if (super_check_offset.as_constant() == sc_offset) {
5960     // Need a slow path; fast failure is impossible.
5961     if (L_slow_path == &L_fallthrough) {
5962       local_jcc(Assembler::equal, *L_success);
5963     } else {
5964       local_jcc(Assembler::notEqual, *L_slow_path);
5965       final_jmp(*L_success);
5966     }
5967   } else {
5968     // No slow path; it's a fast decision.
5969     if (L_failure == &L_fallthrough) {
5970       local_jcc(Assembler::equal, *L_success);
5971     } else {
5972       local_jcc(Assembler::notEqual, *L_failure);
5973       final_jmp(*L_success);
5974     }
5975   }
5976 
5977   bind(L_fallthrough);
5978 
5979 #undef local_jcc
5980 #undef final_jmp
5981 }
5982 
5983 
5984 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5985                                                    Register super_klass,
5986                                                    Register temp_reg,
5987                                                    Register temp2_reg,
5988                                                    Label* L_success,
5989                                                    Label* L_failure,
5990                                                    bool set_cond_codes) {
5991   assert_different_registers(sub_klass, super_klass, temp_reg);
5992   if (temp2_reg != noreg)
5993     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5994 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5995 
5996   Label L_fallthrough;
5997   int label_nulls = 0;
5998   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5999   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6000   assert(label_nulls <= 1, "at most one NULL in the batch");
6001 
6002   // a couple of useful fields in sub_klass:
6003   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6004   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6005   Address secondary_supers_addr(sub_klass, ss_offset);
6006   Address super_cache_addr(     sub_klass, sc_offset);
6007 
6008   // Do a linear scan of the secondary super-klass chain.
6009   // This code is rarely used, so simplicity is a virtue here.
6010   // The repne_scan instruction uses fixed registers, which we must spill.
6011   // Don't worry too much about pre-existing connections with the input regs.
6012 
6013   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6014   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6015 
6016   // Get super_klass value into rax (even if it was in rdi or rcx).
6017   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6018   if (super_klass != rax || UseCompressedOops) {
6019     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6020     mov(rax, super_klass);
6021   }
6022   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6023   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6024 
6025 #ifndef PRODUCT
6026   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6027   ExternalAddress pst_counter_addr((address) pst_counter);
6028   NOT_LP64(  incrementl(pst_counter_addr) );
6029   LP64_ONLY( lea(rcx, pst_counter_addr) );
6030   LP64_ONLY( incrementl(Address(rcx, 0)) );
6031 #endif //PRODUCT
6032 
6033   // We will consult the secondary-super array.
6034   movptr(rdi, secondary_supers_addr);
6035   // Load the array length.  (Positive movl does right thing on LP64.)
6036   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6037   // Skip to start of data.
6038   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6039 
6040   // Scan RCX words at [RDI] for an occurrence of RAX.
6041   // Set NZ/Z based on last compare.
6042   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6043   // not change flags (only scas instruction which is repeated sets flags).
6044   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6045 
6046     testptr(rax,rax); // Set Z = 0
6047     repne_scan();
6048 
6049   // Unspill the temp. registers:
6050   if (pushed_rdi)  pop(rdi);
6051   if (pushed_rcx)  pop(rcx);
6052   if (pushed_rax)  pop(rax);
6053 
6054   if (set_cond_codes) {
6055     // Special hack for the AD files:  rdi is guaranteed non-zero.
6056     assert(!pushed_rdi, "rdi must be left non-NULL");
6057     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6058   }
6059 
6060   if (L_failure == &L_fallthrough)
6061         jccb(Assembler::notEqual, *L_failure);
6062   else  jcc(Assembler::notEqual, *L_failure);
6063 
6064   // Success.  Cache the super we found and proceed in triumph.
6065   movptr(super_cache_addr, super_klass);
6066 
6067   if (L_success != &L_fallthrough) {
6068     jmp(*L_success);
6069   }
6070 
6071 #undef IS_A_TEMP
6072 
6073   bind(L_fallthrough);
6074 }
6075 
6076 
6077 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6078   if (VM_Version::supports_cmov()) {
6079     cmovl(cc, dst, src);
6080   } else {
6081     Label L;
6082     jccb(negate_condition(cc), L);
6083     movl(dst, src);
6084     bind(L);
6085   }
6086 }
6087 
6088 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6089   if (VM_Version::supports_cmov()) {
6090     cmovl(cc, dst, src);
6091   } else {
6092     Label L;
6093     jccb(negate_condition(cc), L);
6094     movl(dst, src);
6095     bind(L);
6096   }
6097 }
6098 
6099 void MacroAssembler::verify_oop(Register reg, const char* s) {
6100   if (!VerifyOops) return;
6101 
6102   // Pass register number to verify_oop_subroutine
6103   const char* b = NULL;
6104   {
6105     ResourceMark rm;
6106     stringStream ss;
6107     ss.print("verify_oop: %s: %s", reg->name(), s);
6108     b = code_string(ss.as_string());
6109   }
6110   BLOCK_COMMENT("verify_oop {");
6111 #ifdef _LP64
6112   push(rscratch1);                    // save r10, trashed by movptr()
6113 #endif
6114   push(rax);                          // save rax,
6115   push(reg);                          // pass register argument
6116   ExternalAddress buffer((address) b);
6117   // avoid using pushptr, as it modifies scratch registers
6118   // and our contract is not to modify anything
6119   movptr(rax, buffer.addr());
6120   push(rax);
6121   // call indirectly to solve generation ordering problem
6122   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6123   call(rax);
6124   // Caller pops the arguments (oop, message) and restores rax, r10
6125   BLOCK_COMMENT("} verify_oop");
6126 }
6127 
6128 
6129 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6130                                                       Register tmp,
6131                                                       int offset) {
6132   intptr_t value = *delayed_value_addr;
6133   if (value != 0)
6134     return RegisterOrConstant(value + offset);
6135 
6136   // load indirectly to solve generation ordering problem
6137   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6138 
6139 #ifdef ASSERT
6140   { Label L;
6141     testptr(tmp, tmp);
6142     if (WizardMode) {
6143       const char* buf = NULL;
6144       {
6145         ResourceMark rm;
6146         stringStream ss;
6147         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6148         buf = code_string(ss.as_string());
6149       }
6150       jcc(Assembler::notZero, L);
6151       STOP(buf);
6152     } else {
6153       jccb(Assembler::notZero, L);
6154       hlt();
6155     }
6156     bind(L);
6157   }
6158 #endif
6159 
6160   if (offset != 0)
6161     addptr(tmp, offset);
6162 
6163   return RegisterOrConstant(tmp);
6164 }
6165 
6166 
6167 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6168                                          int extra_slot_offset) {
6169   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6170   int stackElementSize = Interpreter::stackElementSize;
6171   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6172 #ifdef ASSERT
6173   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6174   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6175 #endif
6176   Register             scale_reg    = noreg;
6177   Address::ScaleFactor scale_factor = Address::no_scale;
6178   if (arg_slot.is_constant()) {
6179     offset += arg_slot.as_constant() * stackElementSize;
6180   } else {
6181     scale_reg    = arg_slot.as_register();
6182     scale_factor = Address::times(stackElementSize);
6183   }
6184   offset += wordSize;           // return PC is on stack
6185   return Address(rsp, scale_reg, scale_factor, offset);
6186 }
6187 
6188 
6189 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6190   if (!VerifyOops) return;
6191 
6192   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6193   // Pass register number to verify_oop_subroutine
6194   const char* b = NULL;
6195   {
6196     ResourceMark rm;
6197     stringStream ss;
6198     ss.print("verify_oop_addr: %s", s);
6199     b = code_string(ss.as_string());
6200   }
6201 #ifdef _LP64
6202   push(rscratch1);                    // save r10, trashed by movptr()
6203 #endif
6204   push(rax);                          // save rax,
6205   // addr may contain rsp so we will have to adjust it based on the push
6206   // we just did (and on 64 bit we do two pushes)
6207   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6208   // stores rax into addr which is backwards of what was intended.
6209   if (addr.uses(rsp)) {
6210     lea(rax, addr);
6211     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6212   } else {
6213     pushptr(addr);
6214   }
6215 
6216   ExternalAddress buffer((address) b);
6217   // pass msg argument
6218   // avoid using pushptr, as it modifies scratch registers
6219   // and our contract is not to modify anything
6220   movptr(rax, buffer.addr());
6221   push(rax);
6222 
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 (addr, message) and restores rax, r10.
6227 }
6228 
6229 void MacroAssembler::verify_tlab() {
6230 #ifdef ASSERT
6231   if (UseTLAB && VerifyOops) {
6232     Label next, ok;
6233     Register t1 = rsi;
6234     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6235 
6236     push(t1);
6237     NOT_LP64(push(thread_reg));
6238     NOT_LP64(get_thread(thread_reg));
6239 
6240     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6241     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6242     jcc(Assembler::aboveEqual, next);
6243     STOP("assert(top >= start)");
6244     should_not_reach_here();
6245 
6246     bind(next);
6247     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6248     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6249     jcc(Assembler::aboveEqual, ok);
6250     STOP("assert(top <= end)");
6251     should_not_reach_here();
6252 
6253     bind(ok);
6254     NOT_LP64(pop(thread_reg));
6255     pop(t1);
6256   }
6257 #endif
6258 }
6259 
6260 class ControlWord {
6261  public:
6262   int32_t _value;
6263 
6264   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6265   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6266   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6267   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6268   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6269   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6270   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6271   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6272 
6273   void print() const {
6274     // rounding control
6275     const char* rc;
6276     switch (rounding_control()) {
6277       case 0: rc = "round near"; break;
6278       case 1: rc = "round down"; break;
6279       case 2: rc = "round up  "; break;
6280       case 3: rc = "chop      "; break;
6281     };
6282     // precision control
6283     const char* pc;
6284     switch (precision_control()) {
6285       case 0: pc = "24 bits "; break;
6286       case 1: pc = "reserved"; break;
6287       case 2: pc = "53 bits "; break;
6288       case 3: pc = "64 bits "; break;
6289     };
6290     // flags
6291     char f[9];
6292     f[0] = ' ';
6293     f[1] = ' ';
6294     f[2] = (precision   ()) ? 'P' : 'p';
6295     f[3] = (underflow   ()) ? 'U' : 'u';
6296     f[4] = (overflow    ()) ? 'O' : 'o';
6297     f[5] = (zero_divide ()) ? 'Z' : 'z';
6298     f[6] = (denormalized()) ? 'D' : 'd';
6299     f[7] = (invalid     ()) ? 'I' : 'i';
6300     f[8] = '\x0';
6301     // output
6302     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6303   }
6304 
6305 };
6306 
6307 class StatusWord {
6308  public:
6309   int32_t _value;
6310 
6311   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6312   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6313   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6314   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6315   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6316   int  top() const                     { return  (_value >> 11) & 7      ; }
6317   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6318   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6319   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6320   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6321   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6322   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6323   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6324   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6325 
6326   void print() const {
6327     // condition codes
6328     char c[5];
6329     c[0] = (C3()) ? '3' : '-';
6330     c[1] = (C2()) ? '2' : '-';
6331     c[2] = (C1()) ? '1' : '-';
6332     c[3] = (C0()) ? '0' : '-';
6333     c[4] = '\x0';
6334     // flags
6335     char f[9];
6336     f[0] = (error_status()) ? 'E' : '-';
6337     f[1] = (stack_fault ()) ? 'S' : '-';
6338     f[2] = (precision   ()) ? 'P' : '-';
6339     f[3] = (underflow   ()) ? 'U' : '-';
6340     f[4] = (overflow    ()) ? 'O' : '-';
6341     f[5] = (zero_divide ()) ? 'Z' : '-';
6342     f[6] = (denormalized()) ? 'D' : '-';
6343     f[7] = (invalid     ()) ? 'I' : '-';
6344     f[8] = '\x0';
6345     // output
6346     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6347   }
6348 
6349 };
6350 
6351 class TagWord {
6352  public:
6353   int32_t _value;
6354 
6355   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6356 
6357   void print() const {
6358     printf("%04x", _value & 0xFFFF);
6359   }
6360 
6361 };
6362 
6363 class FPU_Register {
6364  public:
6365   int32_t _m0;
6366   int32_t _m1;
6367   int16_t _ex;
6368 
6369   bool is_indefinite() const           {
6370     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6371   }
6372 
6373   void print() const {
6374     char  sign = (_ex < 0) ? '-' : '+';
6375     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6376     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6377   };
6378 
6379 };
6380 
6381 class FPU_State {
6382  public:
6383   enum {
6384     register_size       = 10,
6385     number_of_registers =  8,
6386     register_mask       =  7
6387   };
6388 
6389   ControlWord  _control_word;
6390   StatusWord   _status_word;
6391   TagWord      _tag_word;
6392   int32_t      _error_offset;
6393   int32_t      _error_selector;
6394   int32_t      _data_offset;
6395   int32_t      _data_selector;
6396   int8_t       _register[register_size * number_of_registers];
6397 
6398   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6399   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6400 
6401   const char* tag_as_string(int tag) const {
6402     switch (tag) {
6403       case 0: return "valid";
6404       case 1: return "zero";
6405       case 2: return "special";
6406       case 3: return "empty";
6407     }
6408     ShouldNotReachHere();
6409     return NULL;
6410   }
6411 
6412   void print() const {
6413     // print computation registers
6414     { int t = _status_word.top();
6415       for (int i = 0; i < number_of_registers; i++) {
6416         int j = (i - t) & register_mask;
6417         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6418         st(j)->print();
6419         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6420       }
6421     }
6422     printf("\n");
6423     // print control registers
6424     printf("ctrl = "); _control_word.print(); printf("\n");
6425     printf("stat = "); _status_word .print(); printf("\n");
6426     printf("tags = "); _tag_word    .print(); printf("\n");
6427   }
6428 
6429 };
6430 
6431 class Flag_Register {
6432  public:
6433   int32_t _value;
6434 
6435   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6436   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6437   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6438   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6439   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6440   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6441   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6442 
6443   void print() const {
6444     // flags
6445     char f[8];
6446     f[0] = (overflow       ()) ? 'O' : '-';
6447     f[1] = (direction      ()) ? 'D' : '-';
6448     f[2] = (sign           ()) ? 'S' : '-';
6449     f[3] = (zero           ()) ? 'Z' : '-';
6450     f[4] = (auxiliary_carry()) ? 'A' : '-';
6451     f[5] = (parity         ()) ? 'P' : '-';
6452     f[6] = (carry          ()) ? 'C' : '-';
6453     f[7] = '\x0';
6454     // output
6455     printf("%08x  flags = %s", _value, f);
6456   }
6457 
6458 };
6459 
6460 class IU_Register {
6461  public:
6462   int32_t _value;
6463 
6464   void print() const {
6465     printf("%08x  %11d", _value, _value);
6466   }
6467 
6468 };
6469 
6470 class IU_State {
6471  public:
6472   Flag_Register _eflags;
6473   IU_Register   _rdi;
6474   IU_Register   _rsi;
6475   IU_Register   _rbp;
6476   IU_Register   _rsp;
6477   IU_Register   _rbx;
6478   IU_Register   _rdx;
6479   IU_Register   _rcx;
6480   IU_Register   _rax;
6481 
6482   void print() const {
6483     // computation registers
6484     printf("rax,  = "); _rax.print(); printf("\n");
6485     printf("rbx,  = "); _rbx.print(); printf("\n");
6486     printf("rcx  = "); _rcx.print(); printf("\n");
6487     printf("rdx  = "); _rdx.print(); printf("\n");
6488     printf("rdi  = "); _rdi.print(); printf("\n");
6489     printf("rsi  = "); _rsi.print(); printf("\n");
6490     printf("rbp,  = "); _rbp.print(); printf("\n");
6491     printf("rsp  = "); _rsp.print(); printf("\n");
6492     printf("\n");
6493     // control registers
6494     printf("flgs = "); _eflags.print(); printf("\n");
6495   }
6496 };
6497 
6498 
6499 class CPU_State {
6500  public:
6501   FPU_State _fpu_state;
6502   IU_State  _iu_state;
6503 
6504   void print() const {
6505     printf("--------------------------------------------------\n");
6506     _iu_state .print();
6507     printf("\n");
6508     _fpu_state.print();
6509     printf("--------------------------------------------------\n");
6510   }
6511 
6512 };
6513 
6514 
6515 static void _print_CPU_state(CPU_State* state) {
6516   state->print();
6517 };
6518 
6519 
6520 void MacroAssembler::print_CPU_state() {
6521   push_CPU_state();
6522   push(rsp);                // pass CPU state
6523   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6524   addptr(rsp, wordSize);       // discard argument
6525   pop_CPU_state();
6526 }
6527 
6528 
6529 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6530   static int counter = 0;
6531   FPU_State* fs = &state->_fpu_state;
6532   counter++;
6533   // For leaf calls, only verify that the top few elements remain empty.
6534   // We only need 1 empty at the top for C2 code.
6535   if( stack_depth < 0 ) {
6536     if( fs->tag_for_st(7) != 3 ) {
6537       printf("FPR7 not empty\n");
6538       state->print();
6539       assert(false, "error");
6540       return false;
6541     }
6542     return true;                // All other stack states do not matter
6543   }
6544 
6545   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6546          "bad FPU control word");
6547 
6548   // compute stack depth
6549   int i = 0;
6550   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6551   int d = i;
6552   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6553   // verify findings
6554   if (i != FPU_State::number_of_registers) {
6555     // stack not contiguous
6556     printf("%s: stack not contiguous at ST%d\n", s, i);
6557     state->print();
6558     assert(false, "error");
6559     return false;
6560   }
6561   // check if computed stack depth corresponds to expected stack depth
6562   if (stack_depth < 0) {
6563     // expected stack depth is -stack_depth or less
6564     if (d > -stack_depth) {
6565       // too many elements on the stack
6566       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6567       state->print();
6568       assert(false, "error");
6569       return false;
6570     }
6571   } else {
6572     // expected stack depth is stack_depth
6573     if (d != stack_depth) {
6574       // wrong stack depth
6575       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6576       state->print();
6577       assert(false, "error");
6578       return false;
6579     }
6580   }
6581   // everything is cool
6582   return true;
6583 }
6584 
6585 
6586 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6587   if (!VerifyFPU) return;
6588   push_CPU_state();
6589   push(rsp);                // pass CPU state
6590   ExternalAddress msg((address) s);
6591   // pass message string s
6592   pushptr(msg.addr());
6593   push(stack_depth);        // pass stack depth
6594   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6595   addptr(rsp, 3 * wordSize);   // discard arguments
6596   // check for error
6597   { Label L;
6598     testl(rax, rax);
6599     jcc(Assembler::notZero, L);
6600     int3();                  // break if error condition
6601     bind(L);
6602   }
6603   pop_CPU_state();
6604 }
6605 
6606 void MacroAssembler::restore_cpu_control_state_after_jni() {
6607   // Either restore the MXCSR register after returning from the JNI Call
6608   // or verify that it wasn't changed (with -Xcheck:jni flag).
6609   if (VM_Version::supports_sse()) {
6610     if (RestoreMXCSROnJNICalls) {
6611       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6612     } else if (CheckJNICalls) {
6613       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6614     }
6615   }
6616   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6617   vzeroupper();
6618 
6619 #ifndef _LP64
6620   // Either restore the x87 floating pointer control word after returning
6621   // from the JNI call or verify that it wasn't changed.
6622   if (CheckJNICalls) {
6623     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6624   }
6625 #endif // _LP64
6626 }
6627 
6628 // ((OopHandle)result).resolve();
6629 void MacroAssembler::resolve_oop_handle(Register result) {
6630   // OopHandle::resolve is an indirection.
6631   movptr(result, Address(result, 0));
6632 }
6633 
6634 void MacroAssembler::load_mirror(Register mirror, Register method) {
6635   // get mirror
6636   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6637   movptr(mirror, Address(method, Method::const_offset()));
6638   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6639   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6640   movptr(mirror, Address(mirror, mirror_offset));
6641   resolve_oop_handle(mirror);
6642 }
6643 
6644 void MacroAssembler::load_klass(Register dst, Register src) {
6645 #ifdef _LP64
6646   if (UseCompressedClassPointers) {
6647     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6648     decode_klass_not_null(dst);
6649   } else
6650 #endif
6651     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6652 }
6653 
6654 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6655   load_klass(dst, src);
6656   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6657 }
6658 
6659 void MacroAssembler::store_klass(Register dst, Register src) {
6660 #ifdef _LP64
6661   if (UseCompressedClassPointers) {
6662     encode_klass_not_null(src);
6663     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6664   } else
6665 #endif
6666     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6667 }
6668 
6669 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6670 #ifdef _LP64
6671   // FIXME: Must change all places where we try to load the klass.
6672   if (UseCompressedOops) {
6673     movl(dst, src);
6674     decode_heap_oop(dst);
6675   } else
6676 #endif
6677     movptr(dst, src);
6678 }
6679 
6680 // Doesn't do verfication, generates fixed size code
6681 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6682 #ifdef _LP64
6683   if (UseCompressedOops) {
6684     movl(dst, src);
6685     decode_heap_oop_not_null(dst);
6686   } else
6687 #endif
6688     movptr(dst, src);
6689 }
6690 
6691 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6692 #ifdef _LP64
6693   if (UseCompressedOops) {
6694     assert(!dst.uses(src), "not enough registers");
6695     encode_heap_oop(src);
6696     movl(dst, src);
6697   } else
6698 #endif
6699     movptr(dst, src);
6700 }
6701 
6702 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6703   assert_different_registers(src1, tmp);
6704 #ifdef _LP64
6705   if (UseCompressedOops) {
6706     bool did_push = false;
6707     if (tmp == noreg) {
6708       tmp = rax;
6709       push(tmp);
6710       did_push = true;
6711       assert(!src2.uses(rsp), "can't push");
6712     }
6713     load_heap_oop(tmp, src2);
6714     cmpptr(src1, tmp);
6715     if (did_push)  pop(tmp);
6716   } else
6717 #endif
6718     cmpptr(src1, src2);
6719 }
6720 
6721 // Used for storing NULLs.
6722 void MacroAssembler::store_heap_oop_null(Address dst) {
6723 #ifdef _LP64
6724   if (UseCompressedOops) {
6725     movl(dst, (int32_t)NULL_WORD);
6726   } else {
6727     movslq(dst, (int32_t)NULL_WORD);
6728   }
6729 #else
6730   movl(dst, (int32_t)NULL_WORD);
6731 #endif
6732 }
6733 
6734 #ifdef _LP64
6735 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6736   if (UseCompressedClassPointers) {
6737     // Store to klass gap in destination
6738     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6739   }
6740 }
6741 
6742 #ifdef ASSERT
6743 void MacroAssembler::verify_heapbase(const char* msg) {
6744   assert (UseCompressedOops, "should be compressed");
6745   assert (Universe::heap() != NULL, "java heap should be initialized");
6746   if (CheckCompressedOops) {
6747     Label ok;
6748     push(rscratch1); // cmpptr trashes rscratch1
6749     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6750     jcc(Assembler::equal, ok);
6751     STOP(msg);
6752     bind(ok);
6753     pop(rscratch1);
6754   }
6755 }
6756 #endif
6757 
6758 // Algorithm must match oop.inline.hpp encode_heap_oop.
6759 void MacroAssembler::encode_heap_oop(Register r) {
6760 #ifdef ASSERT
6761   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6762 #endif
6763   verify_oop(r, "broken oop in encode_heap_oop");
6764   if (Universe::narrow_oop_base() == NULL) {
6765     if (Universe::narrow_oop_shift() != 0) {
6766       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6767       shrq(r, LogMinObjAlignmentInBytes);
6768     }
6769     return;
6770   }
6771   testq(r, r);
6772   cmovq(Assembler::equal, r, r12_heapbase);
6773   subq(r, r12_heapbase);
6774   shrq(r, LogMinObjAlignmentInBytes);
6775 }
6776 
6777 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6778 #ifdef ASSERT
6779   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6780   if (CheckCompressedOops) {
6781     Label ok;
6782     testq(r, r);
6783     jcc(Assembler::notEqual, ok);
6784     STOP("null oop passed to encode_heap_oop_not_null");
6785     bind(ok);
6786   }
6787 #endif
6788   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6789   if (Universe::narrow_oop_base() != NULL) {
6790     subq(r, r12_heapbase);
6791   }
6792   if (Universe::narrow_oop_shift() != 0) {
6793     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6794     shrq(r, LogMinObjAlignmentInBytes);
6795   }
6796 }
6797 
6798 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6799 #ifdef ASSERT
6800   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6801   if (CheckCompressedOops) {
6802     Label ok;
6803     testq(src, src);
6804     jcc(Assembler::notEqual, ok);
6805     STOP("null oop passed to encode_heap_oop_not_null2");
6806     bind(ok);
6807   }
6808 #endif
6809   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6810   if (dst != src) {
6811     movq(dst, src);
6812   }
6813   if (Universe::narrow_oop_base() != NULL) {
6814     subq(dst, r12_heapbase);
6815   }
6816   if (Universe::narrow_oop_shift() != 0) {
6817     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6818     shrq(dst, LogMinObjAlignmentInBytes);
6819   }
6820 }
6821 
6822 void  MacroAssembler::decode_heap_oop(Register r) {
6823 #ifdef ASSERT
6824   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6825 #endif
6826   if (Universe::narrow_oop_base() == NULL) {
6827     if (Universe::narrow_oop_shift() != 0) {
6828       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6829       shlq(r, LogMinObjAlignmentInBytes);
6830     }
6831   } else {
6832     Label done;
6833     shlq(r, LogMinObjAlignmentInBytes);
6834     jccb(Assembler::equal, done);
6835     addq(r, r12_heapbase);
6836     bind(done);
6837   }
6838   verify_oop(r, "broken oop in decode_heap_oop");
6839 }
6840 
6841 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6842   // Note: it will change flags
6843   assert (UseCompressedOops, "should only be used for compressed headers");
6844   assert (Universe::heap() != NULL, "java heap should be initialized");
6845   // Cannot assert, unverified entry point counts instructions (see .ad file)
6846   // vtableStubs also counts instructions in pd_code_size_limit.
6847   // Also do not verify_oop as this is called by verify_oop.
6848   if (Universe::narrow_oop_shift() != 0) {
6849     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6850     shlq(r, LogMinObjAlignmentInBytes);
6851     if (Universe::narrow_oop_base() != NULL) {
6852       addq(r, r12_heapbase);
6853     }
6854   } else {
6855     assert (Universe::narrow_oop_base() == NULL, "sanity");
6856   }
6857 }
6858 
6859 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6860   // Note: it will change flags
6861   assert (UseCompressedOops, "should only be used for compressed headers");
6862   assert (Universe::heap() != NULL, "java heap should be initialized");
6863   // Cannot assert, unverified entry point counts instructions (see .ad file)
6864   // vtableStubs also counts instructions in pd_code_size_limit.
6865   // Also do not verify_oop as this is called by verify_oop.
6866   if (Universe::narrow_oop_shift() != 0) {
6867     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6868     if (LogMinObjAlignmentInBytes == Address::times_8) {
6869       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6870     } else {
6871       if (dst != src) {
6872         movq(dst, src);
6873       }
6874       shlq(dst, LogMinObjAlignmentInBytes);
6875       if (Universe::narrow_oop_base() != NULL) {
6876         addq(dst, r12_heapbase);
6877       }
6878     }
6879   } else {
6880     assert (Universe::narrow_oop_base() == NULL, "sanity");
6881     if (dst != src) {
6882       movq(dst, src);
6883     }
6884   }
6885 }
6886 
6887 void MacroAssembler::encode_klass_not_null(Register r) {
6888   if (Universe::narrow_klass_base() != NULL) {
6889     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6890     assert(r != r12_heapbase, "Encoding a klass in r12");
6891     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6892     subq(r, r12_heapbase);
6893   }
6894   if (Universe::narrow_klass_shift() != 0) {
6895     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6896     shrq(r, LogKlassAlignmentInBytes);
6897   }
6898   if (Universe::narrow_klass_base() != NULL) {
6899     reinit_heapbase();
6900   }
6901 }
6902 
6903 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6904   if (dst == src) {
6905     encode_klass_not_null(src);
6906   } else {
6907     if (Universe::narrow_klass_base() != NULL) {
6908       mov64(dst, (int64_t)Universe::narrow_klass_base());
6909       negq(dst);
6910       addq(dst, src);
6911     } else {
6912       movptr(dst, src);
6913     }
6914     if (Universe::narrow_klass_shift() != 0) {
6915       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6916       shrq(dst, LogKlassAlignmentInBytes);
6917     }
6918   }
6919 }
6920 
6921 // Function instr_size_for_decode_klass_not_null() counts the instructions
6922 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6923 // when (Universe::heap() != NULL).  Hence, if the instructions they
6924 // generate change, then this method needs to be updated.
6925 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6926   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6927   if (Universe::narrow_klass_base() != NULL) {
6928     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6929     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6930   } else {
6931     // longest load decode klass function, mov64, leaq
6932     return 16;
6933   }
6934 }
6935 
6936 // !!! If the instructions that get generated here change then function
6937 // instr_size_for_decode_klass_not_null() needs to get updated.
6938 void  MacroAssembler::decode_klass_not_null(Register r) {
6939   // Note: it will change flags
6940   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6941   assert(r != r12_heapbase, "Decoding a klass in r12");
6942   // Cannot assert, unverified entry point counts instructions (see .ad file)
6943   // vtableStubs also counts instructions in pd_code_size_limit.
6944   // Also do not verify_oop as this is called by verify_oop.
6945   if (Universe::narrow_klass_shift() != 0) {
6946     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6947     shlq(r, LogKlassAlignmentInBytes);
6948   }
6949   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6950   if (Universe::narrow_klass_base() != NULL) {
6951     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6952     addq(r, r12_heapbase);
6953     reinit_heapbase();
6954   }
6955 }
6956 
6957 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6958   // Note: it will change flags
6959   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6960   if (dst == src) {
6961     decode_klass_not_null(dst);
6962   } else {
6963     // Cannot assert, unverified entry point counts instructions (see .ad file)
6964     // vtableStubs also counts instructions in pd_code_size_limit.
6965     // Also do not verify_oop as this is called by verify_oop.
6966     mov64(dst, (int64_t)Universe::narrow_klass_base());
6967     if (Universe::narrow_klass_shift() != 0) {
6968       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6969       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6970       leaq(dst, Address(dst, src, Address::times_8, 0));
6971     } else {
6972       addq(dst, src);
6973     }
6974   }
6975 }
6976 
6977 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6978   assert (UseCompressedOops, "should only be used for compressed headers");
6979   assert (Universe::heap() != NULL, "java heap should be initialized");
6980   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6981   int oop_index = oop_recorder()->find_index(obj);
6982   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6983   mov_narrow_oop(dst, oop_index, rspec);
6984 }
6985 
6986 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6987   assert (UseCompressedOops, "should only be used for compressed headers");
6988   assert (Universe::heap() != NULL, "java heap should be initialized");
6989   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6990   int oop_index = oop_recorder()->find_index(obj);
6991   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6992   mov_narrow_oop(dst, oop_index, rspec);
6993 }
6994 
6995 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6996   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6997   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6998   int klass_index = oop_recorder()->find_index(k);
6999   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7000   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7001 }
7002 
7003 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7004   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7005   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7006   int klass_index = oop_recorder()->find_index(k);
7007   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7008   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7009 }
7010 
7011 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7012   assert (UseCompressedOops, "should only be used for compressed headers");
7013   assert (Universe::heap() != NULL, "java heap should be initialized");
7014   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7015   int oop_index = oop_recorder()->find_index(obj);
7016   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7017   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7018 }
7019 
7020 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7021   assert (UseCompressedOops, "should only be used for compressed headers");
7022   assert (Universe::heap() != NULL, "java heap should be initialized");
7023   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7024   int oop_index = oop_recorder()->find_index(obj);
7025   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7026   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7027 }
7028 
7029 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7030   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7031   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7032   int klass_index = oop_recorder()->find_index(k);
7033   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7034   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7035 }
7036 
7037 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7038   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7039   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7040   int klass_index = oop_recorder()->find_index(k);
7041   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7042   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7043 }
7044 
7045 void MacroAssembler::reinit_heapbase() {
7046   if (UseCompressedOops || UseCompressedClassPointers) {
7047     if (Universe::heap() != NULL) {
7048       if (Universe::narrow_oop_base() == NULL) {
7049         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7050       } else {
7051         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7052       }
7053     } else {
7054       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7055     }
7056   }
7057 }
7058 
7059 #endif // _LP64
7060 
7061 // C2 compiled method's prolog code.
7062 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7063 
7064   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7065   // NativeJump::patch_verified_entry will be able to patch out the entry
7066   // code safely. The push to verify stack depth is ok at 5 bytes,
7067   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7068   // stack bang then we must use the 6 byte frame allocation even if
7069   // we have no frame. :-(
7070   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7071 
7072   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7073   // Remove word for return addr
7074   framesize -= wordSize;
7075   stack_bang_size -= wordSize;
7076 
7077   // Calls to C2R adapters often do not accept exceptional returns.
7078   // We require that their callers must bang for them.  But be careful, because
7079   // some VM calls (such as call site linkage) can use several kilobytes of
7080   // stack.  But the stack safety zone should account for that.
7081   // See bugs 4446381, 4468289, 4497237.
7082   if (stack_bang_size > 0) {
7083     generate_stack_overflow_check(stack_bang_size);
7084 
7085     // We always push rbp, so that on return to interpreter rbp, will be
7086     // restored correctly and we can correct the stack.
7087     push(rbp);
7088     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7089     if (PreserveFramePointer) {
7090       mov(rbp, rsp);
7091     }
7092     // Remove word for ebp
7093     framesize -= wordSize;
7094 
7095     // Create frame
7096     if (framesize) {
7097       subptr(rsp, framesize);
7098     }
7099   } else {
7100     // Create frame (force generation of a 4 byte immediate value)
7101     subptr_imm32(rsp, framesize);
7102 
7103     // Save RBP register now.
7104     framesize -= wordSize;
7105     movptr(Address(rsp, framesize), rbp);
7106     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7107     if (PreserveFramePointer) {
7108       movptr(rbp, rsp);
7109       if (framesize > 0) {
7110         addptr(rbp, framesize);
7111       }
7112     }
7113   }
7114 
7115   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7116     framesize -= wordSize;
7117     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7118   }
7119 
7120 #ifndef _LP64
7121   // If method sets FPU control word do it now
7122   if (fp_mode_24b) {
7123     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7124   }
7125   if (UseSSE >= 2 && VerifyFPU) {
7126     verify_FPU(0, "FPU stack must be clean on entry");
7127   }
7128 #endif
7129 
7130 #ifdef ASSERT
7131   if (VerifyStackAtCalls) {
7132     Label L;
7133     push(rax);
7134     mov(rax, rsp);
7135     andptr(rax, StackAlignmentInBytes-1);
7136     cmpptr(rax, StackAlignmentInBytes-wordSize);
7137     pop(rax);
7138     jcc(Assembler::equal, L);
7139     STOP("Stack is not properly aligned!");
7140     bind(L);
7141   }
7142 #endif
7143 
7144 }
7145 
7146 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7147   // cnt - number of qwords (8-byte words).
7148   // base - start address, qword aligned.
7149   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7150   assert(base==rdi, "base register must be edi for rep stos");
7151   assert(tmp==rax,   "tmp register must be eax for rep stos");
7152   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7153   assert(InitArrayShortSize % BytesPerLong == 0,
7154     "InitArrayShortSize should be the multiple of BytesPerLong");
7155 
7156   Label DONE;
7157 
7158   xorptr(tmp, tmp);
7159 
7160   if (!is_large) {
7161     Label LOOP, LONG;
7162     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7163     jccb(Assembler::greater, LONG);
7164 
7165     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7166 
7167     decrement(cnt);
7168     jccb(Assembler::negative, DONE); // Zero length
7169 
7170     // Use individual pointer-sized stores for small counts:
7171     BIND(LOOP);
7172     movptr(Address(base, cnt, Address::times_ptr), tmp);
7173     decrement(cnt);
7174     jccb(Assembler::greaterEqual, LOOP);
7175     jmpb(DONE);
7176 
7177     BIND(LONG);
7178   }
7179 
7180   // Use longer rep-prefixed ops for non-small counts:
7181   if (UseFastStosb) {
7182     shlptr(cnt, 3); // convert to number of bytes
7183     rep_stosb();
7184   } else {
7185     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7186     rep_stos();
7187   }
7188 
7189   BIND(DONE);
7190 }
7191 
7192 #ifdef COMPILER2
7193 
7194 // IndexOf for constant substrings with size >= 8 chars
7195 // which don't need to be loaded through stack.
7196 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7197                                       Register cnt1, Register cnt2,
7198                                       int int_cnt2,  Register result,
7199                                       XMMRegister vec, Register tmp,
7200                                       int ae) {
7201   ShortBranchVerifier sbv(this);
7202   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7203   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7204 
7205   // This method uses the pcmpestri instruction with bound registers
7206   //   inputs:
7207   //     xmm - substring
7208   //     rax - substring length (elements count)
7209   //     mem - scanned string
7210   //     rdx - string length (elements count)
7211   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7212   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7213   //   outputs:
7214   //     rcx - matched index in string
7215   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7216   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7217   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7218   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7219   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7220 
7221   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7222         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7223         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7224 
7225   // Note, inline_string_indexOf() generates checks:
7226   // if (substr.count > string.count) return -1;
7227   // if (substr.count == 0) return 0;
7228   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7229 
7230   // Load substring.
7231   if (ae == StrIntrinsicNode::UL) {
7232     pmovzxbw(vec, Address(str2, 0));
7233   } else {
7234     movdqu(vec, Address(str2, 0));
7235   }
7236   movl(cnt2, int_cnt2);
7237   movptr(result, str1); // string addr
7238 
7239   if (int_cnt2 > stride) {
7240     jmpb(SCAN_TO_SUBSTR);
7241 
7242     // Reload substr for rescan, this code
7243     // is executed only for large substrings (> 8 chars)
7244     bind(RELOAD_SUBSTR);
7245     if (ae == StrIntrinsicNode::UL) {
7246       pmovzxbw(vec, Address(str2, 0));
7247     } else {
7248       movdqu(vec, Address(str2, 0));
7249     }
7250     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7251 
7252     bind(RELOAD_STR);
7253     // We came here after the beginning of the substring was
7254     // matched but the rest of it was not so we need to search
7255     // again. Start from the next element after the previous match.
7256 
7257     // cnt2 is number of substring reminding elements and
7258     // cnt1 is number of string reminding elements when cmp failed.
7259     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7260     subl(cnt1, cnt2);
7261     addl(cnt1, int_cnt2);
7262     movl(cnt2, int_cnt2); // Now restore cnt2
7263 
7264     decrementl(cnt1);     // Shift to next element
7265     cmpl(cnt1, cnt2);
7266     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7267 
7268     addptr(result, (1<<scale1));
7269 
7270   } // (int_cnt2 > 8)
7271 
7272   // Scan string for start of substr in 16-byte vectors
7273   bind(SCAN_TO_SUBSTR);
7274   pcmpestri(vec, Address(result, 0), mode);
7275   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7276   subl(cnt1, stride);
7277   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7278   cmpl(cnt1, cnt2);
7279   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7280   addptr(result, 16);
7281   jmpb(SCAN_TO_SUBSTR);
7282 
7283   // Found a potential substr
7284   bind(FOUND_CANDIDATE);
7285   // Matched whole vector if first element matched (tmp(rcx) == 0).
7286   if (int_cnt2 == stride) {
7287     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7288   } else { // int_cnt2 > 8
7289     jccb(Assembler::overflow, FOUND_SUBSTR);
7290   }
7291   // After pcmpestri tmp(rcx) contains matched element index
7292   // Compute start addr of substr
7293   lea(result, Address(result, tmp, scale1));
7294 
7295   // Make sure string is still long enough
7296   subl(cnt1, tmp);
7297   cmpl(cnt1, cnt2);
7298   if (int_cnt2 == stride) {
7299     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7300   } else { // int_cnt2 > 8
7301     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7302   }
7303   // Left less then substring.
7304 
7305   bind(RET_NOT_FOUND);
7306   movl(result, -1);
7307   jmp(EXIT);
7308 
7309   if (int_cnt2 > stride) {
7310     // This code is optimized for the case when whole substring
7311     // is matched if its head is matched.
7312     bind(MATCH_SUBSTR_HEAD);
7313     pcmpestri(vec, Address(result, 0), mode);
7314     // Reload only string if does not match
7315     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7316 
7317     Label CONT_SCAN_SUBSTR;
7318     // Compare the rest of substring (> 8 chars).
7319     bind(FOUND_SUBSTR);
7320     // First 8 chars are already matched.
7321     negptr(cnt2);
7322     addptr(cnt2, stride);
7323 
7324     bind(SCAN_SUBSTR);
7325     subl(cnt1, stride);
7326     cmpl(cnt2, -stride); // Do not read beyond substring
7327     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7328     // Back-up strings to avoid reading beyond substring:
7329     // cnt1 = cnt1 - cnt2 + 8
7330     addl(cnt1, cnt2); // cnt2 is negative
7331     addl(cnt1, stride);
7332     movl(cnt2, stride); negptr(cnt2);
7333     bind(CONT_SCAN_SUBSTR);
7334     if (int_cnt2 < (int)G) {
7335       int tail_off1 = int_cnt2<<scale1;
7336       int tail_off2 = int_cnt2<<scale2;
7337       if (ae == StrIntrinsicNode::UL) {
7338         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7339       } else {
7340         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7341       }
7342       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7343     } else {
7344       // calculate index in register to avoid integer overflow (int_cnt2*2)
7345       movl(tmp, int_cnt2);
7346       addptr(tmp, cnt2);
7347       if (ae == StrIntrinsicNode::UL) {
7348         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7349       } else {
7350         movdqu(vec, Address(str2, tmp, scale2, 0));
7351       }
7352       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7353     }
7354     // Need to reload strings pointers if not matched whole vector
7355     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7356     addptr(cnt2, stride);
7357     jcc(Assembler::negative, SCAN_SUBSTR);
7358     // Fall through if found full substring
7359 
7360   } // (int_cnt2 > 8)
7361 
7362   bind(RET_FOUND);
7363   // Found result if we matched full small substring.
7364   // Compute substr offset
7365   subptr(result, str1);
7366   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7367     shrl(result, 1); // index
7368   }
7369   bind(EXIT);
7370 
7371 } // string_indexofC8
7372 
7373 // Small strings are loaded through stack if they cross page boundary.
7374 void MacroAssembler::string_indexof(Register str1, Register str2,
7375                                     Register cnt1, Register cnt2,
7376                                     int int_cnt2,  Register result,
7377                                     XMMRegister vec, Register tmp,
7378                                     int ae) {
7379   ShortBranchVerifier sbv(this);
7380   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7381   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7382 
7383   //
7384   // int_cnt2 is length of small (< 8 chars) constant substring
7385   // or (-1) for non constant substring in which case its length
7386   // is in cnt2 register.
7387   //
7388   // Note, inline_string_indexOf() generates checks:
7389   // if (substr.count > string.count) return -1;
7390   // if (substr.count == 0) return 0;
7391   //
7392   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7393   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7394   // This method uses the pcmpestri instruction with bound registers
7395   //   inputs:
7396   //     xmm - substring
7397   //     rax - substring length (elements count)
7398   //     mem - scanned string
7399   //     rdx - string length (elements count)
7400   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7401   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7402   //   outputs:
7403   //     rcx - matched index in string
7404   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7405   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7406   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7407   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7408 
7409   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7410         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7411         FOUND_CANDIDATE;
7412 
7413   { //========================================================
7414     // We don't know where these strings are located
7415     // and we can't read beyond them. Load them through stack.
7416     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7417 
7418     movptr(tmp, rsp); // save old SP
7419 
7420     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7421       if (int_cnt2 == (1>>scale2)) { // One byte
7422         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7423         load_unsigned_byte(result, Address(str2, 0));
7424         movdl(vec, result); // move 32 bits
7425       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7426         // Not enough header space in 32-bit VM: 12+3 = 15.
7427         movl(result, Address(str2, -1));
7428         shrl(result, 8);
7429         movdl(vec, result); // move 32 bits
7430       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7431         load_unsigned_short(result, Address(str2, 0));
7432         movdl(vec, result); // move 32 bits
7433       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7434         movdl(vec, Address(str2, 0)); // move 32 bits
7435       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7436         movq(vec, Address(str2, 0));  // move 64 bits
7437       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7438         // Array header size is 12 bytes in 32-bit VM
7439         // + 6 bytes for 3 chars == 18 bytes,
7440         // enough space to load vec and shift.
7441         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7442         if (ae == StrIntrinsicNode::UL) {
7443           int tail_off = int_cnt2-8;
7444           pmovzxbw(vec, Address(str2, tail_off));
7445           psrldq(vec, -2*tail_off);
7446         }
7447         else {
7448           int tail_off = int_cnt2*(1<<scale2);
7449           movdqu(vec, Address(str2, tail_off-16));
7450           psrldq(vec, 16-tail_off);
7451         }
7452       }
7453     } else { // not constant substring
7454       cmpl(cnt2, stride);
7455       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7456 
7457       // We can read beyond string if srt+16 does not cross page boundary
7458       // since heaps are aligned and mapped by pages.
7459       assert(os::vm_page_size() < (int)G, "default page should be small");
7460       movl(result, str2); // We need only low 32 bits
7461       andl(result, (os::vm_page_size()-1));
7462       cmpl(result, (os::vm_page_size()-16));
7463       jccb(Assembler::belowEqual, CHECK_STR);
7464 
7465       // Move small strings to stack to allow load 16 bytes into vec.
7466       subptr(rsp, 16);
7467       int stk_offset = wordSize-(1<<scale2);
7468       push(cnt2);
7469 
7470       bind(COPY_SUBSTR);
7471       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7472         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7473         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7474       } else if (ae == StrIntrinsicNode::UU) {
7475         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7476         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7477       }
7478       decrement(cnt2);
7479       jccb(Assembler::notZero, COPY_SUBSTR);
7480 
7481       pop(cnt2);
7482       movptr(str2, rsp);  // New substring address
7483     } // non constant
7484 
7485     bind(CHECK_STR);
7486     cmpl(cnt1, stride);
7487     jccb(Assembler::aboveEqual, BIG_STRINGS);
7488 
7489     // Check cross page boundary.
7490     movl(result, str1); // We need only low 32 bits
7491     andl(result, (os::vm_page_size()-1));
7492     cmpl(result, (os::vm_page_size()-16));
7493     jccb(Assembler::belowEqual, BIG_STRINGS);
7494 
7495     subptr(rsp, 16);
7496     int stk_offset = -(1<<scale1);
7497     if (int_cnt2 < 0) { // not constant
7498       push(cnt2);
7499       stk_offset += wordSize;
7500     }
7501     movl(cnt2, cnt1);
7502 
7503     bind(COPY_STR);
7504     if (ae == StrIntrinsicNode::LL) {
7505       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7506       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7507     } else {
7508       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7509       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7510     }
7511     decrement(cnt2);
7512     jccb(Assembler::notZero, COPY_STR);
7513 
7514     if (int_cnt2 < 0) { // not constant
7515       pop(cnt2);
7516     }
7517     movptr(str1, rsp);  // New string address
7518 
7519     bind(BIG_STRINGS);
7520     // Load substring.
7521     if (int_cnt2 < 0) { // -1
7522       if (ae == StrIntrinsicNode::UL) {
7523         pmovzxbw(vec, Address(str2, 0));
7524       } else {
7525         movdqu(vec, Address(str2, 0));
7526       }
7527       push(cnt2);       // substr count
7528       push(str2);       // substr addr
7529       push(str1);       // string addr
7530     } else {
7531       // Small (< 8 chars) constant substrings are loaded already.
7532       movl(cnt2, int_cnt2);
7533     }
7534     push(tmp);  // original SP
7535 
7536   } // Finished loading
7537 
7538   //========================================================
7539   // Start search
7540   //
7541 
7542   movptr(result, str1); // string addr
7543 
7544   if (int_cnt2  < 0) {  // Only for non constant substring
7545     jmpb(SCAN_TO_SUBSTR);
7546 
7547     // SP saved at sp+0
7548     // String saved at sp+1*wordSize
7549     // Substr saved at sp+2*wordSize
7550     // Substr count saved at sp+3*wordSize
7551 
7552     // Reload substr for rescan, this code
7553     // is executed only for large substrings (> 8 chars)
7554     bind(RELOAD_SUBSTR);
7555     movptr(str2, Address(rsp, 2*wordSize));
7556     movl(cnt2, Address(rsp, 3*wordSize));
7557     if (ae == StrIntrinsicNode::UL) {
7558       pmovzxbw(vec, Address(str2, 0));
7559     } else {
7560       movdqu(vec, Address(str2, 0));
7561     }
7562     // We came here after the beginning of the substring was
7563     // matched but the rest of it was not so we need to search
7564     // again. Start from the next element after the previous match.
7565     subptr(str1, result); // Restore counter
7566     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7567       shrl(str1, 1);
7568     }
7569     addl(cnt1, str1);
7570     decrementl(cnt1);   // Shift to next element
7571     cmpl(cnt1, cnt2);
7572     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7573 
7574     addptr(result, (1<<scale1));
7575   } // non constant
7576 
7577   // Scan string for start of substr in 16-byte vectors
7578   bind(SCAN_TO_SUBSTR);
7579   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7580   pcmpestri(vec, Address(result, 0), mode);
7581   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7582   subl(cnt1, stride);
7583   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7584   cmpl(cnt1, cnt2);
7585   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7586   addptr(result, 16);
7587 
7588   bind(ADJUST_STR);
7589   cmpl(cnt1, stride); // Do not read beyond string
7590   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7591   // Back-up string to avoid reading beyond string.
7592   lea(result, Address(result, cnt1, scale1, -16));
7593   movl(cnt1, stride);
7594   jmpb(SCAN_TO_SUBSTR);
7595 
7596   // Found a potential substr
7597   bind(FOUND_CANDIDATE);
7598   // After pcmpestri tmp(rcx) contains matched element index
7599 
7600   // Make sure string is still long enough
7601   subl(cnt1, tmp);
7602   cmpl(cnt1, cnt2);
7603   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7604   // Left less then substring.
7605 
7606   bind(RET_NOT_FOUND);
7607   movl(result, -1);
7608   jmpb(CLEANUP);
7609 
7610   bind(FOUND_SUBSTR);
7611   // Compute start addr of substr
7612   lea(result, Address(result, tmp, scale1));
7613   if (int_cnt2 > 0) { // Constant substring
7614     // Repeat search for small substring (< 8 chars)
7615     // from new point without reloading substring.
7616     // Have to check that we don't read beyond string.
7617     cmpl(tmp, stride-int_cnt2);
7618     jccb(Assembler::greater, ADJUST_STR);
7619     // Fall through if matched whole substring.
7620   } else { // non constant
7621     assert(int_cnt2 == -1, "should be != 0");
7622 
7623     addl(tmp, cnt2);
7624     // Found result if we matched whole substring.
7625     cmpl(tmp, stride);
7626     jccb(Assembler::lessEqual, RET_FOUND);
7627 
7628     // Repeat search for small substring (<= 8 chars)
7629     // from new point 'str1' without reloading substring.
7630     cmpl(cnt2, stride);
7631     // Have to check that we don't read beyond string.
7632     jccb(Assembler::lessEqual, ADJUST_STR);
7633 
7634     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7635     // Compare the rest of substring (> 8 chars).
7636     movptr(str1, result);
7637 
7638     cmpl(tmp, cnt2);
7639     // First 8 chars are already matched.
7640     jccb(Assembler::equal, CHECK_NEXT);
7641 
7642     bind(SCAN_SUBSTR);
7643     pcmpestri(vec, Address(str1, 0), mode);
7644     // Need to reload strings pointers if not matched whole vector
7645     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7646 
7647     bind(CHECK_NEXT);
7648     subl(cnt2, stride);
7649     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7650     addptr(str1, 16);
7651     if (ae == StrIntrinsicNode::UL) {
7652       addptr(str2, 8);
7653     } else {
7654       addptr(str2, 16);
7655     }
7656     subl(cnt1, stride);
7657     cmpl(cnt2, stride); // Do not read beyond substring
7658     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7659     // Back-up strings to avoid reading beyond substring.
7660 
7661     if (ae == StrIntrinsicNode::UL) {
7662       lea(str2, Address(str2, cnt2, scale2, -8));
7663       lea(str1, Address(str1, cnt2, scale1, -16));
7664     } else {
7665       lea(str2, Address(str2, cnt2, scale2, -16));
7666       lea(str1, Address(str1, cnt2, scale1, -16));
7667     }
7668     subl(cnt1, cnt2);
7669     movl(cnt2, stride);
7670     addl(cnt1, stride);
7671     bind(CONT_SCAN_SUBSTR);
7672     if (ae == StrIntrinsicNode::UL) {
7673       pmovzxbw(vec, Address(str2, 0));
7674     } else {
7675       movdqu(vec, Address(str2, 0));
7676     }
7677     jmp(SCAN_SUBSTR);
7678 
7679     bind(RET_FOUND_LONG);
7680     movptr(str1, Address(rsp, wordSize));
7681   } // non constant
7682 
7683   bind(RET_FOUND);
7684   // Compute substr offset
7685   subptr(result, str1);
7686   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7687     shrl(result, 1); // index
7688   }
7689   bind(CLEANUP);
7690   pop(rsp); // restore SP
7691 
7692 } // string_indexof
7693 
7694 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7695                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7696   ShortBranchVerifier sbv(this);
7697   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7698 
7699   int stride = 8;
7700 
7701   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7702         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7703         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7704         FOUND_SEQ_CHAR, DONE_LABEL;
7705 
7706   movptr(result, str1);
7707   if (UseAVX >= 2) {
7708     cmpl(cnt1, stride);
7709     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7710     cmpl(cnt1, 2*stride);
7711     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7712     movdl(vec1, ch);
7713     vpbroadcastw(vec1, vec1);
7714     vpxor(vec2, vec2);
7715     movl(tmp, cnt1);
7716     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7717     andl(cnt1,0x0000000F);  //tail count (in chars)
7718 
7719     bind(SCAN_TO_16_CHAR_LOOP);
7720     vmovdqu(vec3, Address(result, 0));
7721     vpcmpeqw(vec3, vec3, vec1, 1);
7722     vptest(vec2, vec3);
7723     jcc(Assembler::carryClear, FOUND_CHAR);
7724     addptr(result, 32);
7725     subl(tmp, 2*stride);
7726     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7727     jmp(SCAN_TO_8_CHAR);
7728     bind(SCAN_TO_8_CHAR_INIT);
7729     movdl(vec1, ch);
7730     pshuflw(vec1, vec1, 0x00);
7731     pshufd(vec1, vec1, 0);
7732     pxor(vec2, vec2);
7733   }
7734   bind(SCAN_TO_8_CHAR);
7735   cmpl(cnt1, stride);
7736   if (UseAVX >= 2) {
7737     jcc(Assembler::less, SCAN_TO_CHAR);
7738   } else {
7739     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7740     movdl(vec1, ch);
7741     pshuflw(vec1, vec1, 0x00);
7742     pshufd(vec1, vec1, 0);
7743     pxor(vec2, vec2);
7744   }
7745   movl(tmp, cnt1);
7746   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7747   andl(cnt1,0x00000007);  //tail count (in chars)
7748 
7749   bind(SCAN_TO_8_CHAR_LOOP);
7750   movdqu(vec3, Address(result, 0));
7751   pcmpeqw(vec3, vec1);
7752   ptest(vec2, vec3);
7753   jcc(Assembler::carryClear, FOUND_CHAR);
7754   addptr(result, 16);
7755   subl(tmp, stride);
7756   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7757   bind(SCAN_TO_CHAR);
7758   testl(cnt1, cnt1);
7759   jcc(Assembler::zero, RET_NOT_FOUND);
7760   bind(SCAN_TO_CHAR_LOOP);
7761   load_unsigned_short(tmp, Address(result, 0));
7762   cmpl(ch, tmp);
7763   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7764   addptr(result, 2);
7765   subl(cnt1, 1);
7766   jccb(Assembler::zero, RET_NOT_FOUND);
7767   jmp(SCAN_TO_CHAR_LOOP);
7768 
7769   bind(RET_NOT_FOUND);
7770   movl(result, -1);
7771   jmpb(DONE_LABEL);
7772 
7773   bind(FOUND_CHAR);
7774   if (UseAVX >= 2) {
7775     vpmovmskb(tmp, vec3);
7776   } else {
7777     pmovmskb(tmp, vec3);
7778   }
7779   bsfl(ch, tmp);
7780   addl(result, ch);
7781 
7782   bind(FOUND_SEQ_CHAR);
7783   subptr(result, str1);
7784   shrl(result, 1);
7785 
7786   bind(DONE_LABEL);
7787 } // string_indexof_char
7788 
7789 // helper function for string_compare
7790 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7791                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7792                                         Address::ScaleFactor scale2, Register index, int ae) {
7793   if (ae == StrIntrinsicNode::LL) {
7794     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7795     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7796   } else if (ae == StrIntrinsicNode::UU) {
7797     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7798     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7799   } else {
7800     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7801     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7802   }
7803 }
7804 
7805 // Compare strings, used for char[] and byte[].
7806 void MacroAssembler::string_compare(Register str1, Register str2,
7807                                     Register cnt1, Register cnt2, Register result,
7808                                     XMMRegister vec1, int ae) {
7809   ShortBranchVerifier sbv(this);
7810   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7811   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7812   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7813   int stride2x2 = 0x40;
7814   Address::ScaleFactor scale = Address::no_scale;
7815   Address::ScaleFactor scale1 = Address::no_scale;
7816   Address::ScaleFactor scale2 = Address::no_scale;
7817 
7818   if (ae != StrIntrinsicNode::LL) {
7819     stride2x2 = 0x20;
7820   }
7821 
7822   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7823     shrl(cnt2, 1);
7824   }
7825   // Compute the minimum of the string lengths and the
7826   // difference of the string lengths (stack).
7827   // Do the conditional move stuff
7828   movl(result, cnt1);
7829   subl(cnt1, cnt2);
7830   push(cnt1);
7831   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7832 
7833   // Is the minimum length zero?
7834   testl(cnt2, cnt2);
7835   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7836   if (ae == StrIntrinsicNode::LL) {
7837     // Load first bytes
7838     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7839     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7840   } else if (ae == StrIntrinsicNode::UU) {
7841     // Load first characters
7842     load_unsigned_short(result, Address(str1, 0));
7843     load_unsigned_short(cnt1, Address(str2, 0));
7844   } else {
7845     load_unsigned_byte(result, Address(str1, 0));
7846     load_unsigned_short(cnt1, Address(str2, 0));
7847   }
7848   subl(result, cnt1);
7849   jcc(Assembler::notZero,  POP_LABEL);
7850 
7851   if (ae == StrIntrinsicNode::UU) {
7852     // Divide length by 2 to get number of chars
7853     shrl(cnt2, 1);
7854   }
7855   cmpl(cnt2, 1);
7856   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7857 
7858   // Check if the strings start at the same location and setup scale and stride
7859   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7860     cmpptr(str1, str2);
7861     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7862     if (ae == StrIntrinsicNode::LL) {
7863       scale = Address::times_1;
7864       stride = 16;
7865     } else {
7866       scale = Address::times_2;
7867       stride = 8;
7868     }
7869   } else {
7870     scale1 = Address::times_1;
7871     scale2 = Address::times_2;
7872     // scale not used
7873     stride = 8;
7874   }
7875 
7876   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7877     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7878     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7879     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7880     Label COMPARE_TAIL_LONG;
7881     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7882 
7883     int pcmpmask = 0x19;
7884     if (ae == StrIntrinsicNode::LL) {
7885       pcmpmask &= ~0x01;
7886     }
7887 
7888     // Setup to compare 16-chars (32-bytes) vectors,
7889     // start from first character again because it has aligned address.
7890     if (ae == StrIntrinsicNode::LL) {
7891       stride2 = 32;
7892     } else {
7893       stride2 = 16;
7894     }
7895     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7896       adr_stride = stride << scale;
7897     } else {
7898       adr_stride1 = 8;  //stride << scale1;
7899       adr_stride2 = 16; //stride << scale2;
7900     }
7901 
7902     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7903     // rax and rdx are used by pcmpestri as elements counters
7904     movl(result, cnt2);
7905     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7906     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7907 
7908     // fast path : compare first 2 8-char vectors.
7909     bind(COMPARE_16_CHARS);
7910     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7911       movdqu(vec1, Address(str1, 0));
7912     } else {
7913       pmovzxbw(vec1, Address(str1, 0));
7914     }
7915     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7916     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7917 
7918     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7919       movdqu(vec1, Address(str1, adr_stride));
7920       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7921     } else {
7922       pmovzxbw(vec1, Address(str1, adr_stride1));
7923       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7924     }
7925     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7926     addl(cnt1, stride);
7927 
7928     // Compare the characters at index in cnt1
7929     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7930     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7931     subl(result, cnt2);
7932     jmp(POP_LABEL);
7933 
7934     // Setup the registers to start vector comparison loop
7935     bind(COMPARE_WIDE_VECTORS);
7936     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7937       lea(str1, Address(str1, result, scale));
7938       lea(str2, Address(str2, result, scale));
7939     } else {
7940       lea(str1, Address(str1, result, scale1));
7941       lea(str2, Address(str2, result, scale2));
7942     }
7943     subl(result, stride2);
7944     subl(cnt2, stride2);
7945     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7946     negptr(result);
7947 
7948     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7949     bind(COMPARE_WIDE_VECTORS_LOOP);
7950 
7951 #ifdef _LP64
7952     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7953       cmpl(cnt2, stride2x2);
7954       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7955       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7956       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7957 
7958       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7959       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7960         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7961         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7962       } else {
7963         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7964         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7965       }
7966       kortestql(k7, k7);
7967       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7968       addptr(result, stride2x2);  // update since we already compared at this addr
7969       subl(cnt2, stride2x2);      // and sub the size too
7970       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7971 
7972       vpxor(vec1, vec1);
7973       jmpb(COMPARE_WIDE_TAIL);
7974     }//if (VM_Version::supports_avx512vlbw())
7975 #endif // _LP64
7976 
7977 
7978     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7979     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7980       vmovdqu(vec1, Address(str1, result, scale));
7981       vpxor(vec1, Address(str2, result, scale));
7982     } else {
7983       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7984       vpxor(vec1, Address(str2, result, scale2));
7985     }
7986     vptest(vec1, vec1);
7987     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7988     addptr(result, stride2);
7989     subl(cnt2, stride2);
7990     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7991     // clean upper bits of YMM registers
7992     vpxor(vec1, vec1);
7993 
7994     // compare wide vectors tail
7995     bind(COMPARE_WIDE_TAIL);
7996     testptr(result, result);
7997     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7998 
7999     movl(result, stride2);
8000     movl(cnt2, result);
8001     negptr(result);
8002     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8003 
8004     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8005     bind(VECTOR_NOT_EQUAL);
8006     // clean upper bits of YMM registers
8007     vpxor(vec1, vec1);
8008     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8009       lea(str1, Address(str1, result, scale));
8010       lea(str2, Address(str2, result, scale));
8011     } else {
8012       lea(str1, Address(str1, result, scale1));
8013       lea(str2, Address(str2, result, scale2));
8014     }
8015     jmp(COMPARE_16_CHARS);
8016 
8017     // Compare tail chars, length between 1 to 15 chars
8018     bind(COMPARE_TAIL_LONG);
8019     movl(cnt2, result);
8020     cmpl(cnt2, stride);
8021     jcc(Assembler::less, COMPARE_SMALL_STR);
8022 
8023     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8024       movdqu(vec1, Address(str1, 0));
8025     } else {
8026       pmovzxbw(vec1, Address(str1, 0));
8027     }
8028     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8029     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8030     subptr(cnt2, stride);
8031     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8032     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8033       lea(str1, Address(str1, result, scale));
8034       lea(str2, Address(str2, result, scale));
8035     } else {
8036       lea(str1, Address(str1, result, scale1));
8037       lea(str2, Address(str2, result, scale2));
8038     }
8039     negptr(cnt2);
8040     jmpb(WHILE_HEAD_LABEL);
8041 
8042     bind(COMPARE_SMALL_STR);
8043   } else if (UseSSE42Intrinsics) {
8044     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8045     int pcmpmask = 0x19;
8046     // Setup to compare 8-char (16-byte) vectors,
8047     // start from first character again because it has aligned address.
8048     movl(result, cnt2);
8049     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8050     if (ae == StrIntrinsicNode::LL) {
8051       pcmpmask &= ~0x01;
8052     }
8053     jcc(Assembler::zero, COMPARE_TAIL);
8054     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8055       lea(str1, Address(str1, result, scale));
8056       lea(str2, Address(str2, result, scale));
8057     } else {
8058       lea(str1, Address(str1, result, scale1));
8059       lea(str2, Address(str2, result, scale2));
8060     }
8061     negptr(result);
8062 
8063     // pcmpestri
8064     //   inputs:
8065     //     vec1- substring
8066     //     rax - negative string length (elements count)
8067     //     mem - scanned string
8068     //     rdx - string length (elements count)
8069     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8070     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8071     //   outputs:
8072     //     rcx - first mismatched element index
8073     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8074 
8075     bind(COMPARE_WIDE_VECTORS);
8076     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8077       movdqu(vec1, Address(str1, result, scale));
8078       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8079     } else {
8080       pmovzxbw(vec1, Address(str1, result, scale1));
8081       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8082     }
8083     // After pcmpestri cnt1(rcx) contains mismatched element index
8084 
8085     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8086     addptr(result, stride);
8087     subptr(cnt2, stride);
8088     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8089 
8090     // compare wide vectors tail
8091     testptr(result, result);
8092     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8093 
8094     movl(cnt2, stride);
8095     movl(result, stride);
8096     negptr(result);
8097     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8098       movdqu(vec1, Address(str1, result, scale));
8099       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8100     } else {
8101       pmovzxbw(vec1, Address(str1, result, scale1));
8102       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8103     }
8104     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8105 
8106     // Mismatched characters in the vectors
8107     bind(VECTOR_NOT_EQUAL);
8108     addptr(cnt1, result);
8109     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8110     subl(result, cnt2);
8111     jmpb(POP_LABEL);
8112 
8113     bind(COMPARE_TAIL); // limit is zero
8114     movl(cnt2, result);
8115     // Fallthru to tail compare
8116   }
8117   // Shift str2 and str1 to the end of the arrays, negate min
8118   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8119     lea(str1, Address(str1, cnt2, scale));
8120     lea(str2, Address(str2, cnt2, scale));
8121   } else {
8122     lea(str1, Address(str1, cnt2, scale1));
8123     lea(str2, Address(str2, cnt2, scale2));
8124   }
8125   decrementl(cnt2);  // first character was compared already
8126   negptr(cnt2);
8127 
8128   // Compare the rest of the elements
8129   bind(WHILE_HEAD_LABEL);
8130   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8131   subl(result, cnt1);
8132   jccb(Assembler::notZero, POP_LABEL);
8133   increment(cnt2);
8134   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8135 
8136   // Strings are equal up to min length.  Return the length difference.
8137   bind(LENGTH_DIFF_LABEL);
8138   pop(result);
8139   if (ae == StrIntrinsicNode::UU) {
8140     // Divide diff by 2 to get number of chars
8141     sarl(result, 1);
8142   }
8143   jmpb(DONE_LABEL);
8144 
8145 #ifdef _LP64
8146   if (VM_Version::supports_avx512vlbw()) {
8147 
8148     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8149 
8150     kmovql(cnt1, k7);
8151     notq(cnt1);
8152     bsfq(cnt2, cnt1);
8153     if (ae != StrIntrinsicNode::LL) {
8154       // Divide diff by 2 to get number of chars
8155       sarl(cnt2, 1);
8156     }
8157     addq(result, cnt2);
8158     if (ae == StrIntrinsicNode::LL) {
8159       load_unsigned_byte(cnt1, Address(str2, result));
8160       load_unsigned_byte(result, Address(str1, result));
8161     } else if (ae == StrIntrinsicNode::UU) {
8162       load_unsigned_short(cnt1, Address(str2, result, scale));
8163       load_unsigned_short(result, Address(str1, result, scale));
8164     } else {
8165       load_unsigned_short(cnt1, Address(str2, result, scale2));
8166       load_unsigned_byte(result, Address(str1, result, scale1));
8167     }
8168     subl(result, cnt1);
8169     jmpb(POP_LABEL);
8170   }//if (VM_Version::supports_avx512vlbw())
8171 #endif // _LP64
8172 
8173   // Discard the stored length difference
8174   bind(POP_LABEL);
8175   pop(cnt1);
8176 
8177   // That's it
8178   bind(DONE_LABEL);
8179   if(ae == StrIntrinsicNode::UL) {
8180     negl(result);
8181   }
8182 
8183 }
8184 
8185 // Search for Non-ASCII character (Negative byte value) in a byte array,
8186 // return true if it has any and false otherwise.
8187 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8188 //   @HotSpotIntrinsicCandidate
8189 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8190 //     for (int i = off; i < off + len; i++) {
8191 //       if (ba[i] < 0) {
8192 //         return true;
8193 //       }
8194 //     }
8195 //     return false;
8196 //   }
8197 void MacroAssembler::has_negatives(Register ary1, Register len,
8198   Register result, Register tmp1,
8199   XMMRegister vec1, XMMRegister vec2) {
8200   // rsi: byte array
8201   // rcx: len
8202   // rax: result
8203   ShortBranchVerifier sbv(this);
8204   assert_different_registers(ary1, len, result, tmp1);
8205   assert_different_registers(vec1, vec2);
8206   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8207 
8208   // len == 0
8209   testl(len, len);
8210   jcc(Assembler::zero, FALSE_LABEL);
8211 
8212   if ((UseAVX > 2) && // AVX512
8213     VM_Version::supports_avx512vlbw() &&
8214     VM_Version::supports_bmi2()) {
8215 
8216     set_vector_masking();  // opening of the stub context for programming mask registers
8217 
8218     Label test_64_loop, test_tail;
8219     Register tmp3_aliased = len;
8220 
8221     movl(tmp1, len);
8222     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8223 
8224     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8225     andl(len, ~(64 - 1));    // vector count (in chars)
8226     jccb(Assembler::zero, test_tail);
8227 
8228     lea(ary1, Address(ary1, len, Address::times_1));
8229     negptr(len);
8230 
8231     bind(test_64_loop);
8232     // Check whether our 64 elements of size byte contain negatives
8233     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8234     kortestql(k2, k2);
8235     jcc(Assembler::notZero, TRUE_LABEL);
8236 
8237     addptr(len, 64);
8238     jccb(Assembler::notZero, test_64_loop);
8239 
8240 
8241     bind(test_tail);
8242     // bail out when there is nothing to be done
8243     testl(tmp1, -1);
8244     jcc(Assembler::zero, FALSE_LABEL);
8245 
8246     // Save k1
8247     kmovql(k3, k1);
8248 
8249     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8250 #ifdef _LP64
8251     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8252     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8253     notq(tmp3_aliased);
8254     kmovql(k1, tmp3_aliased);
8255 #else
8256     Label k_init;
8257     jmp(k_init);
8258 
8259     // We could not read 64-bits from a general purpose register thus we move
8260     // data required to compose 64 1's to the instruction stream
8261     // We emit 64 byte wide series of elements from 0..63 which later on would
8262     // be used as a compare targets with tail count contained in tmp1 register.
8263     // Result would be a k1 register having tmp1 consecutive number or 1
8264     // counting from least significant bit.
8265     address tmp = pc();
8266     emit_int64(0x0706050403020100);
8267     emit_int64(0x0F0E0D0C0B0A0908);
8268     emit_int64(0x1716151413121110);
8269     emit_int64(0x1F1E1D1C1B1A1918);
8270     emit_int64(0x2726252423222120);
8271     emit_int64(0x2F2E2D2C2B2A2928);
8272     emit_int64(0x3736353433323130);
8273     emit_int64(0x3F3E3D3C3B3A3938);
8274 
8275     bind(k_init);
8276     lea(len, InternalAddress(tmp));
8277     // create mask to test for negative byte inside a vector
8278     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8279     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8280 
8281 #endif
8282     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8283     ktestq(k2, k1);
8284     // Restore k1
8285     kmovql(k1, k3);
8286     jcc(Assembler::notZero, TRUE_LABEL);
8287 
8288     jmp(FALSE_LABEL);
8289 
8290     clear_vector_masking();   // closing of the stub context for programming mask registers
8291   } else {
8292     movl(result, len); // copy
8293 
8294     if (UseAVX == 2 && UseSSE >= 2) {
8295       // With AVX2, use 32-byte vector compare
8296       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8297 
8298       // Compare 32-byte vectors
8299       andl(result, 0x0000001f);  //   tail count (in bytes)
8300       andl(len, 0xffffffe0);   // vector count (in bytes)
8301       jccb(Assembler::zero, COMPARE_TAIL);
8302 
8303       lea(ary1, Address(ary1, len, Address::times_1));
8304       negptr(len);
8305 
8306       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8307       movdl(vec2, tmp1);
8308       vpbroadcastd(vec2, vec2);
8309 
8310       bind(COMPARE_WIDE_VECTORS);
8311       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8312       vptest(vec1, vec2);
8313       jccb(Assembler::notZero, TRUE_LABEL);
8314       addptr(len, 32);
8315       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8316 
8317       testl(result, result);
8318       jccb(Assembler::zero, FALSE_LABEL);
8319 
8320       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8321       vptest(vec1, vec2);
8322       jccb(Assembler::notZero, TRUE_LABEL);
8323       jmpb(FALSE_LABEL);
8324 
8325       bind(COMPARE_TAIL); // len is zero
8326       movl(len, result);
8327       // Fallthru to tail compare
8328     } else if (UseSSE42Intrinsics) {
8329       // With SSE4.2, use double quad vector compare
8330       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8331 
8332       // Compare 16-byte vectors
8333       andl(result, 0x0000000f);  //   tail count (in bytes)
8334       andl(len, 0xfffffff0);   // vector count (in bytes)
8335       jccb(Assembler::zero, COMPARE_TAIL);
8336 
8337       lea(ary1, Address(ary1, len, Address::times_1));
8338       negptr(len);
8339 
8340       movl(tmp1, 0x80808080);
8341       movdl(vec2, tmp1);
8342       pshufd(vec2, vec2, 0);
8343 
8344       bind(COMPARE_WIDE_VECTORS);
8345       movdqu(vec1, Address(ary1, len, Address::times_1));
8346       ptest(vec1, vec2);
8347       jccb(Assembler::notZero, TRUE_LABEL);
8348       addptr(len, 16);
8349       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8350 
8351       testl(result, result);
8352       jccb(Assembler::zero, FALSE_LABEL);
8353 
8354       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8355       ptest(vec1, vec2);
8356       jccb(Assembler::notZero, TRUE_LABEL);
8357       jmpb(FALSE_LABEL);
8358 
8359       bind(COMPARE_TAIL); // len is zero
8360       movl(len, result);
8361       // Fallthru to tail compare
8362     }
8363   }
8364   // Compare 4-byte vectors
8365   andl(len, 0xfffffffc); // vector count (in bytes)
8366   jccb(Assembler::zero, COMPARE_CHAR);
8367 
8368   lea(ary1, Address(ary1, len, Address::times_1));
8369   negptr(len);
8370 
8371   bind(COMPARE_VECTORS);
8372   movl(tmp1, Address(ary1, len, Address::times_1));
8373   andl(tmp1, 0x80808080);
8374   jccb(Assembler::notZero, TRUE_LABEL);
8375   addptr(len, 4);
8376   jcc(Assembler::notZero, COMPARE_VECTORS);
8377 
8378   // Compare trailing char (final 2 bytes), if any
8379   bind(COMPARE_CHAR);
8380   testl(result, 0x2);   // tail  char
8381   jccb(Assembler::zero, COMPARE_BYTE);
8382   load_unsigned_short(tmp1, Address(ary1, 0));
8383   andl(tmp1, 0x00008080);
8384   jccb(Assembler::notZero, TRUE_LABEL);
8385   subptr(result, 2);
8386   lea(ary1, Address(ary1, 2));
8387 
8388   bind(COMPARE_BYTE);
8389   testl(result, 0x1);   // tail  byte
8390   jccb(Assembler::zero, FALSE_LABEL);
8391   load_unsigned_byte(tmp1, Address(ary1, 0));
8392   andl(tmp1, 0x00000080);
8393   jccb(Assembler::notEqual, TRUE_LABEL);
8394   jmpb(FALSE_LABEL);
8395 
8396   bind(TRUE_LABEL);
8397   movl(result, 1);   // return true
8398   jmpb(DONE);
8399 
8400   bind(FALSE_LABEL);
8401   xorl(result, result); // return false
8402 
8403   // That's it
8404   bind(DONE);
8405   if (UseAVX >= 2 && UseSSE >= 2) {
8406     // clean upper bits of YMM registers
8407     vpxor(vec1, vec1);
8408     vpxor(vec2, vec2);
8409   }
8410 }
8411 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8412 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8413                                    Register limit, Register result, Register chr,
8414                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8415   ShortBranchVerifier sbv(this);
8416   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8417 
8418   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8419   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8420 
8421   if (is_array_equ) {
8422     // Check the input args
8423     cmpptr(ary1, ary2);
8424     jcc(Assembler::equal, TRUE_LABEL);
8425 
8426     // Need additional checks for arrays_equals.
8427     testptr(ary1, ary1);
8428     jcc(Assembler::zero, FALSE_LABEL);
8429     testptr(ary2, ary2);
8430     jcc(Assembler::zero, FALSE_LABEL);
8431 
8432     // Check the lengths
8433     movl(limit, Address(ary1, length_offset));
8434     cmpl(limit, Address(ary2, length_offset));
8435     jcc(Assembler::notEqual, FALSE_LABEL);
8436   }
8437 
8438   // count == 0
8439   testl(limit, limit);
8440   jcc(Assembler::zero, TRUE_LABEL);
8441 
8442   if (is_array_equ) {
8443     // Load array address
8444     lea(ary1, Address(ary1, base_offset));
8445     lea(ary2, Address(ary2, base_offset));
8446   }
8447 
8448   if (is_array_equ && is_char) {
8449     // arrays_equals when used for char[].
8450     shll(limit, 1);      // byte count != 0
8451   }
8452   movl(result, limit); // copy
8453 
8454   if (UseAVX >= 2) {
8455     // With AVX2, use 32-byte vector compare
8456     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8457 
8458     // Compare 32-byte vectors
8459     andl(result, 0x0000001f);  //   tail count (in bytes)
8460     andl(limit, 0xffffffe0);   // vector count (in bytes)
8461     jcc(Assembler::zero, COMPARE_TAIL);
8462 
8463     lea(ary1, Address(ary1, limit, Address::times_1));
8464     lea(ary2, Address(ary2, limit, Address::times_1));
8465     negptr(limit);
8466 
8467     bind(COMPARE_WIDE_VECTORS);
8468 
8469 #ifdef _LP64
8470     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8471       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8472 
8473       cmpl(limit, -64);
8474       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8475 
8476       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8477 
8478       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8479       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8480       kortestql(k7, k7);
8481       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8482       addptr(limit, 64);  // update since we already compared at this addr
8483       cmpl(limit, -64);
8484       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8485 
8486       // At this point we may still need to compare -limit+result bytes.
8487       // We could execute the next two instruction and just continue via non-wide path:
8488       //  cmpl(limit, 0);
8489       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8490       // But since we stopped at the points ary{1,2}+limit which are
8491       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8492       // (|limit| <= 32 and result < 32),
8493       // we may just compare the last 64 bytes.
8494       //
8495       addptr(result, -64);   // it is safe, bc we just came from this area
8496       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8497       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8498       kortestql(k7, k7);
8499       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8500 
8501       jmp(TRUE_LABEL);
8502 
8503       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8504 
8505     }//if (VM_Version::supports_avx512vlbw())
8506 #endif //_LP64
8507 
8508     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8509     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8510     vpxor(vec1, vec2);
8511 
8512     vptest(vec1, vec1);
8513     jcc(Assembler::notZero, FALSE_LABEL);
8514     addptr(limit, 32);
8515     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8516 
8517     testl(result, result);
8518     jcc(Assembler::zero, TRUE_LABEL);
8519 
8520     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8521     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8522     vpxor(vec1, vec2);
8523 
8524     vptest(vec1, vec1);
8525     jccb(Assembler::notZero, FALSE_LABEL);
8526     jmpb(TRUE_LABEL);
8527 
8528     bind(COMPARE_TAIL); // limit is zero
8529     movl(limit, result);
8530     // Fallthru to tail compare
8531   } else if (UseSSE42Intrinsics) {
8532     // With SSE4.2, use double quad vector compare
8533     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8534 
8535     // Compare 16-byte vectors
8536     andl(result, 0x0000000f);  //   tail count (in bytes)
8537     andl(limit, 0xfffffff0);   // vector count (in bytes)
8538     jcc(Assembler::zero, COMPARE_TAIL);
8539 
8540     lea(ary1, Address(ary1, limit, Address::times_1));
8541     lea(ary2, Address(ary2, limit, Address::times_1));
8542     negptr(limit);
8543 
8544     bind(COMPARE_WIDE_VECTORS);
8545     movdqu(vec1, Address(ary1, limit, Address::times_1));
8546     movdqu(vec2, Address(ary2, limit, Address::times_1));
8547     pxor(vec1, vec2);
8548 
8549     ptest(vec1, vec1);
8550     jcc(Assembler::notZero, FALSE_LABEL);
8551     addptr(limit, 16);
8552     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8553 
8554     testl(result, result);
8555     jcc(Assembler::zero, TRUE_LABEL);
8556 
8557     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8558     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8559     pxor(vec1, vec2);
8560 
8561     ptest(vec1, vec1);
8562     jccb(Assembler::notZero, FALSE_LABEL);
8563     jmpb(TRUE_LABEL);
8564 
8565     bind(COMPARE_TAIL); // limit is zero
8566     movl(limit, result);
8567     // Fallthru to tail compare
8568   }
8569 
8570   // Compare 4-byte vectors
8571   andl(limit, 0xfffffffc); // vector count (in bytes)
8572   jccb(Assembler::zero, COMPARE_CHAR);
8573 
8574   lea(ary1, Address(ary1, limit, Address::times_1));
8575   lea(ary2, Address(ary2, limit, Address::times_1));
8576   negptr(limit);
8577 
8578   bind(COMPARE_VECTORS);
8579   movl(chr, Address(ary1, limit, Address::times_1));
8580   cmpl(chr, Address(ary2, limit, Address::times_1));
8581   jccb(Assembler::notEqual, FALSE_LABEL);
8582   addptr(limit, 4);
8583   jcc(Assembler::notZero, COMPARE_VECTORS);
8584 
8585   // Compare trailing char (final 2 bytes), if any
8586   bind(COMPARE_CHAR);
8587   testl(result, 0x2);   // tail  char
8588   jccb(Assembler::zero, COMPARE_BYTE);
8589   load_unsigned_short(chr, Address(ary1, 0));
8590   load_unsigned_short(limit, Address(ary2, 0));
8591   cmpl(chr, limit);
8592   jccb(Assembler::notEqual, FALSE_LABEL);
8593 
8594   if (is_array_equ && is_char) {
8595     bind(COMPARE_BYTE);
8596   } else {
8597     lea(ary1, Address(ary1, 2));
8598     lea(ary2, Address(ary2, 2));
8599 
8600     bind(COMPARE_BYTE);
8601     testl(result, 0x1);   // tail  byte
8602     jccb(Assembler::zero, TRUE_LABEL);
8603     load_unsigned_byte(chr, Address(ary1, 0));
8604     load_unsigned_byte(limit, Address(ary2, 0));
8605     cmpl(chr, limit);
8606     jccb(Assembler::notEqual, FALSE_LABEL);
8607   }
8608   bind(TRUE_LABEL);
8609   movl(result, 1);   // return true
8610   jmpb(DONE);
8611 
8612   bind(FALSE_LABEL);
8613   xorl(result, result); // return false
8614 
8615   // That's it
8616   bind(DONE);
8617   if (UseAVX >= 2) {
8618     // clean upper bits of YMM registers
8619     vpxor(vec1, vec1);
8620     vpxor(vec2, vec2);
8621   }
8622 }
8623 
8624 #endif
8625 
8626 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8627                                    Register to, Register value, Register count,
8628                                    Register rtmp, XMMRegister xtmp) {
8629   ShortBranchVerifier sbv(this);
8630   assert_different_registers(to, value, count, rtmp);
8631   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8632   Label L_fill_2_bytes, L_fill_4_bytes;
8633 
8634   int shift = -1;
8635   switch (t) {
8636     case T_BYTE:
8637       shift = 2;
8638       break;
8639     case T_SHORT:
8640       shift = 1;
8641       break;
8642     case T_INT:
8643       shift = 0;
8644       break;
8645     default: ShouldNotReachHere();
8646   }
8647 
8648   if (t == T_BYTE) {
8649     andl(value, 0xff);
8650     movl(rtmp, value);
8651     shll(rtmp, 8);
8652     orl(value, rtmp);
8653   }
8654   if (t == T_SHORT) {
8655     andl(value, 0xffff);
8656   }
8657   if (t == T_BYTE || t == T_SHORT) {
8658     movl(rtmp, value);
8659     shll(rtmp, 16);
8660     orl(value, rtmp);
8661   }
8662 
8663   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8664   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8665   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8666     // align source address at 4 bytes address boundary
8667     if (t == T_BYTE) {
8668       // One byte misalignment happens only for byte arrays
8669       testptr(to, 1);
8670       jccb(Assembler::zero, L_skip_align1);
8671       movb(Address(to, 0), value);
8672       increment(to);
8673       decrement(count);
8674       BIND(L_skip_align1);
8675     }
8676     // Two bytes misalignment happens only for byte and short (char) arrays
8677     testptr(to, 2);
8678     jccb(Assembler::zero, L_skip_align2);
8679     movw(Address(to, 0), value);
8680     addptr(to, 2);
8681     subl(count, 1<<(shift-1));
8682     BIND(L_skip_align2);
8683   }
8684   if (UseSSE < 2) {
8685     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8686     // Fill 32-byte chunks
8687     subl(count, 8 << shift);
8688     jcc(Assembler::less, L_check_fill_8_bytes);
8689     align(16);
8690 
8691     BIND(L_fill_32_bytes_loop);
8692 
8693     for (int i = 0; i < 32; i += 4) {
8694       movl(Address(to, i), value);
8695     }
8696 
8697     addptr(to, 32);
8698     subl(count, 8 << shift);
8699     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8700     BIND(L_check_fill_8_bytes);
8701     addl(count, 8 << shift);
8702     jccb(Assembler::zero, L_exit);
8703     jmpb(L_fill_8_bytes);
8704 
8705     //
8706     // length is too short, just fill qwords
8707     //
8708     BIND(L_fill_8_bytes_loop);
8709     movl(Address(to, 0), value);
8710     movl(Address(to, 4), value);
8711     addptr(to, 8);
8712     BIND(L_fill_8_bytes);
8713     subl(count, 1 << (shift + 1));
8714     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8715     // fall through to fill 4 bytes
8716   } else {
8717     Label L_fill_32_bytes;
8718     if (!UseUnalignedLoadStores) {
8719       // align to 8 bytes, we know we are 4 byte aligned to start
8720       testptr(to, 4);
8721       jccb(Assembler::zero, L_fill_32_bytes);
8722       movl(Address(to, 0), value);
8723       addptr(to, 4);
8724       subl(count, 1<<shift);
8725     }
8726     BIND(L_fill_32_bytes);
8727     {
8728       assert( UseSSE >= 2, "supported cpu only" );
8729       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8730       if (UseAVX > 2) {
8731         movl(rtmp, 0xffff);
8732         kmovwl(k1, rtmp);
8733       }
8734       movdl(xtmp, value);
8735       if (UseAVX > 2 && UseUnalignedLoadStores) {
8736         // Fill 64-byte chunks
8737         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8738         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8739 
8740         subl(count, 16 << shift);
8741         jcc(Assembler::less, L_check_fill_32_bytes);
8742         align(16);
8743 
8744         BIND(L_fill_64_bytes_loop);
8745         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8746         addptr(to, 64);
8747         subl(count, 16 << shift);
8748         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8749 
8750         BIND(L_check_fill_32_bytes);
8751         addl(count, 8 << shift);
8752         jccb(Assembler::less, L_check_fill_8_bytes);
8753         vmovdqu(Address(to, 0), xtmp);
8754         addptr(to, 32);
8755         subl(count, 8 << shift);
8756 
8757         BIND(L_check_fill_8_bytes);
8758       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8759         // Fill 64-byte chunks
8760         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8761         vpbroadcastd(xtmp, xtmp);
8762 
8763         subl(count, 16 << shift);
8764         jcc(Assembler::less, L_check_fill_32_bytes);
8765         align(16);
8766 
8767         BIND(L_fill_64_bytes_loop);
8768         vmovdqu(Address(to, 0), xtmp);
8769         vmovdqu(Address(to, 32), xtmp);
8770         addptr(to, 64);
8771         subl(count, 16 << shift);
8772         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8773 
8774         BIND(L_check_fill_32_bytes);
8775         addl(count, 8 << shift);
8776         jccb(Assembler::less, L_check_fill_8_bytes);
8777         vmovdqu(Address(to, 0), xtmp);
8778         addptr(to, 32);
8779         subl(count, 8 << shift);
8780 
8781         BIND(L_check_fill_8_bytes);
8782         // clean upper bits of YMM registers
8783         movdl(xtmp, value);
8784         pshufd(xtmp, xtmp, 0);
8785       } else {
8786         // Fill 32-byte chunks
8787         pshufd(xtmp, xtmp, 0);
8788 
8789         subl(count, 8 << shift);
8790         jcc(Assembler::less, L_check_fill_8_bytes);
8791         align(16);
8792 
8793         BIND(L_fill_32_bytes_loop);
8794 
8795         if (UseUnalignedLoadStores) {
8796           movdqu(Address(to, 0), xtmp);
8797           movdqu(Address(to, 16), xtmp);
8798         } else {
8799           movq(Address(to, 0), xtmp);
8800           movq(Address(to, 8), xtmp);
8801           movq(Address(to, 16), xtmp);
8802           movq(Address(to, 24), xtmp);
8803         }
8804 
8805         addptr(to, 32);
8806         subl(count, 8 << shift);
8807         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8808 
8809         BIND(L_check_fill_8_bytes);
8810       }
8811       addl(count, 8 << shift);
8812       jccb(Assembler::zero, L_exit);
8813       jmpb(L_fill_8_bytes);
8814 
8815       //
8816       // length is too short, just fill qwords
8817       //
8818       BIND(L_fill_8_bytes_loop);
8819       movq(Address(to, 0), xtmp);
8820       addptr(to, 8);
8821       BIND(L_fill_8_bytes);
8822       subl(count, 1 << (shift + 1));
8823       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8824     }
8825   }
8826   // fill trailing 4 bytes
8827   BIND(L_fill_4_bytes);
8828   testl(count, 1<<shift);
8829   jccb(Assembler::zero, L_fill_2_bytes);
8830   movl(Address(to, 0), value);
8831   if (t == T_BYTE || t == T_SHORT) {
8832     addptr(to, 4);
8833     BIND(L_fill_2_bytes);
8834     // fill trailing 2 bytes
8835     testl(count, 1<<(shift-1));
8836     jccb(Assembler::zero, L_fill_byte);
8837     movw(Address(to, 0), value);
8838     if (t == T_BYTE) {
8839       addptr(to, 2);
8840       BIND(L_fill_byte);
8841       // fill trailing byte
8842       testl(count, 1);
8843       jccb(Assembler::zero, L_exit);
8844       movb(Address(to, 0), value);
8845     } else {
8846       BIND(L_fill_byte);
8847     }
8848   } else {
8849     BIND(L_fill_2_bytes);
8850   }
8851   BIND(L_exit);
8852 }
8853 
8854 // encode char[] to byte[] in ISO_8859_1
8855    //@HotSpotIntrinsicCandidate
8856    //private static int implEncodeISOArray(byte[] sa, int sp,
8857    //byte[] da, int dp, int len) {
8858    //  int i = 0;
8859    //  for (; i < len; i++) {
8860    //    char c = StringUTF16.getChar(sa, sp++);
8861    //    if (c > '\u00FF')
8862    //      break;
8863    //    da[dp++] = (byte)c;
8864    //  }
8865    //  return i;
8866    //}
8867 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8868   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8869   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8870   Register tmp5, Register result) {
8871 
8872   // rsi: src
8873   // rdi: dst
8874   // rdx: len
8875   // rcx: tmp5
8876   // rax: result
8877   ShortBranchVerifier sbv(this);
8878   assert_different_registers(src, dst, len, tmp5, result);
8879   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8880 
8881   // set result
8882   xorl(result, result);
8883   // check for zero length
8884   testl(len, len);
8885   jcc(Assembler::zero, L_done);
8886 
8887   movl(result, len);
8888 
8889   // Setup pointers
8890   lea(src, Address(src, len, Address::times_2)); // char[]
8891   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8892   negptr(len);
8893 
8894   if (UseSSE42Intrinsics || UseAVX >= 2) {
8895     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8896     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8897 
8898     if (UseAVX >= 2) {
8899       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8900       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8901       movdl(tmp1Reg, tmp5);
8902       vpbroadcastd(tmp1Reg, tmp1Reg);
8903       jmp(L_chars_32_check);
8904 
8905       bind(L_copy_32_chars);
8906       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8907       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8908       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8909       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8910       jccb(Assembler::notZero, L_copy_32_chars_exit);
8911       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8912       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8913       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8914 
8915       bind(L_chars_32_check);
8916       addptr(len, 32);
8917       jcc(Assembler::lessEqual, L_copy_32_chars);
8918 
8919       bind(L_copy_32_chars_exit);
8920       subptr(len, 16);
8921       jccb(Assembler::greater, L_copy_16_chars_exit);
8922 
8923     } else if (UseSSE42Intrinsics) {
8924       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8925       movdl(tmp1Reg, tmp5);
8926       pshufd(tmp1Reg, tmp1Reg, 0);
8927       jmpb(L_chars_16_check);
8928     }
8929 
8930     bind(L_copy_16_chars);
8931     if (UseAVX >= 2) {
8932       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8933       vptest(tmp2Reg, tmp1Reg);
8934       jcc(Assembler::notZero, L_copy_16_chars_exit);
8935       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8936       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8937     } else {
8938       if (UseAVX > 0) {
8939         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8940         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8941         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8942       } else {
8943         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8944         por(tmp2Reg, tmp3Reg);
8945         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8946         por(tmp2Reg, tmp4Reg);
8947       }
8948       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8949       jccb(Assembler::notZero, L_copy_16_chars_exit);
8950       packuswb(tmp3Reg, tmp4Reg);
8951     }
8952     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8953 
8954     bind(L_chars_16_check);
8955     addptr(len, 16);
8956     jcc(Assembler::lessEqual, L_copy_16_chars);
8957 
8958     bind(L_copy_16_chars_exit);
8959     if (UseAVX >= 2) {
8960       // clean upper bits of YMM registers
8961       vpxor(tmp2Reg, tmp2Reg);
8962       vpxor(tmp3Reg, tmp3Reg);
8963       vpxor(tmp4Reg, tmp4Reg);
8964       movdl(tmp1Reg, tmp5);
8965       pshufd(tmp1Reg, tmp1Reg, 0);
8966     }
8967     subptr(len, 8);
8968     jccb(Assembler::greater, L_copy_8_chars_exit);
8969 
8970     bind(L_copy_8_chars);
8971     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8972     ptest(tmp3Reg, tmp1Reg);
8973     jccb(Assembler::notZero, L_copy_8_chars_exit);
8974     packuswb(tmp3Reg, tmp1Reg);
8975     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8976     addptr(len, 8);
8977     jccb(Assembler::lessEqual, L_copy_8_chars);
8978 
8979     bind(L_copy_8_chars_exit);
8980     subptr(len, 8);
8981     jccb(Assembler::zero, L_done);
8982   }
8983 
8984   bind(L_copy_1_char);
8985   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8986   testl(tmp5, 0xff00);      // check if Unicode char
8987   jccb(Assembler::notZero, L_copy_1_char_exit);
8988   movb(Address(dst, len, Address::times_1, 0), tmp5);
8989   addptr(len, 1);
8990   jccb(Assembler::less, L_copy_1_char);
8991 
8992   bind(L_copy_1_char_exit);
8993   addptr(result, len); // len is negative count of not processed elements
8994 
8995   bind(L_done);
8996 }
8997 
8998 #ifdef _LP64
8999 /**
9000  * Helper for multiply_to_len().
9001  */
9002 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9003   addq(dest_lo, src1);
9004   adcq(dest_hi, 0);
9005   addq(dest_lo, src2);
9006   adcq(dest_hi, 0);
9007 }
9008 
9009 /**
9010  * Multiply 64 bit by 64 bit first loop.
9011  */
9012 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9013                                            Register y, Register y_idx, Register z,
9014                                            Register carry, Register product,
9015                                            Register idx, Register kdx) {
9016   //
9017   //  jlong carry, x[], y[], z[];
9018   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9019   //    huge_128 product = y[idx] * x[xstart] + carry;
9020   //    z[kdx] = (jlong)product;
9021   //    carry  = (jlong)(product >>> 64);
9022   //  }
9023   //  z[xstart] = carry;
9024   //
9025 
9026   Label L_first_loop, L_first_loop_exit;
9027   Label L_one_x, L_one_y, L_multiply;
9028 
9029   decrementl(xstart);
9030   jcc(Assembler::negative, L_one_x);
9031 
9032   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9033   rorq(x_xstart, 32); // convert big-endian to little-endian
9034 
9035   bind(L_first_loop);
9036   decrementl(idx);
9037   jcc(Assembler::negative, L_first_loop_exit);
9038   decrementl(idx);
9039   jcc(Assembler::negative, L_one_y);
9040   movq(y_idx, Address(y, idx, Address::times_4,  0));
9041   rorq(y_idx, 32); // convert big-endian to little-endian
9042   bind(L_multiply);
9043   movq(product, x_xstart);
9044   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9045   addq(product, carry);
9046   adcq(rdx, 0);
9047   subl(kdx, 2);
9048   movl(Address(z, kdx, Address::times_4,  4), product);
9049   shrq(product, 32);
9050   movl(Address(z, kdx, Address::times_4,  0), product);
9051   movq(carry, rdx);
9052   jmp(L_first_loop);
9053 
9054   bind(L_one_y);
9055   movl(y_idx, Address(y,  0));
9056   jmp(L_multiply);
9057 
9058   bind(L_one_x);
9059   movl(x_xstart, Address(x,  0));
9060   jmp(L_first_loop);
9061 
9062   bind(L_first_loop_exit);
9063 }
9064 
9065 /**
9066  * Multiply 64 bit by 64 bit and add 128 bit.
9067  */
9068 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9069                                             Register yz_idx, Register idx,
9070                                             Register carry, Register product, int offset) {
9071   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9072   //     z[kdx] = (jlong)product;
9073 
9074   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9075   rorq(yz_idx, 32); // convert big-endian to little-endian
9076   movq(product, x_xstart);
9077   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9078   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9079   rorq(yz_idx, 32); // convert big-endian to little-endian
9080 
9081   add2_with_carry(rdx, product, carry, yz_idx);
9082 
9083   movl(Address(z, idx, Address::times_4,  offset+4), product);
9084   shrq(product, 32);
9085   movl(Address(z, idx, Address::times_4,  offset), product);
9086 
9087 }
9088 
9089 /**
9090  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9091  */
9092 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9093                                              Register yz_idx, Register idx, Register jdx,
9094                                              Register carry, Register product,
9095                                              Register carry2) {
9096   //   jlong carry, x[], y[], z[];
9097   //   int kdx = ystart+1;
9098   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9099   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9100   //     z[kdx+idx+1] = (jlong)product;
9101   //     jlong carry2  = (jlong)(product >>> 64);
9102   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9103   //     z[kdx+idx] = (jlong)product;
9104   //     carry  = (jlong)(product >>> 64);
9105   //   }
9106   //   idx += 2;
9107   //   if (idx > 0) {
9108   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9109   //     z[kdx+idx] = (jlong)product;
9110   //     carry  = (jlong)(product >>> 64);
9111   //   }
9112   //
9113 
9114   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9115 
9116   movl(jdx, idx);
9117   andl(jdx, 0xFFFFFFFC);
9118   shrl(jdx, 2);
9119 
9120   bind(L_third_loop);
9121   subl(jdx, 1);
9122   jcc(Assembler::negative, L_third_loop_exit);
9123   subl(idx, 4);
9124 
9125   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9126   movq(carry2, rdx);
9127 
9128   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9129   movq(carry, rdx);
9130   jmp(L_third_loop);
9131 
9132   bind (L_third_loop_exit);
9133 
9134   andl (idx, 0x3);
9135   jcc(Assembler::zero, L_post_third_loop_done);
9136 
9137   Label L_check_1;
9138   subl(idx, 2);
9139   jcc(Assembler::negative, L_check_1);
9140 
9141   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9142   movq(carry, rdx);
9143 
9144   bind (L_check_1);
9145   addl (idx, 0x2);
9146   andl (idx, 0x1);
9147   subl(idx, 1);
9148   jcc(Assembler::negative, L_post_third_loop_done);
9149 
9150   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9151   movq(product, x_xstart);
9152   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9153   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9154 
9155   add2_with_carry(rdx, product, yz_idx, carry);
9156 
9157   movl(Address(z, idx, Address::times_4,  0), product);
9158   shrq(product, 32);
9159 
9160   shlq(rdx, 32);
9161   orq(product, rdx);
9162   movq(carry, product);
9163 
9164   bind(L_post_third_loop_done);
9165 }
9166 
9167 /**
9168  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9169  *
9170  */
9171 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9172                                                   Register carry, Register carry2,
9173                                                   Register idx, Register jdx,
9174                                                   Register yz_idx1, Register yz_idx2,
9175                                                   Register tmp, Register tmp3, Register tmp4) {
9176   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9177 
9178   //   jlong carry, x[], y[], z[];
9179   //   int kdx = ystart+1;
9180   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9181   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9182   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9183   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9184   //     carry  = (jlong)(tmp4 >>> 64);
9185   //     z[kdx+idx+1] = (jlong)tmp3;
9186   //     z[kdx+idx] = (jlong)tmp4;
9187   //   }
9188   //   idx += 2;
9189   //   if (idx > 0) {
9190   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9191   //     z[kdx+idx] = (jlong)yz_idx1;
9192   //     carry  = (jlong)(yz_idx1 >>> 64);
9193   //   }
9194   //
9195 
9196   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9197 
9198   movl(jdx, idx);
9199   andl(jdx, 0xFFFFFFFC);
9200   shrl(jdx, 2);
9201 
9202   bind(L_third_loop);
9203   subl(jdx, 1);
9204   jcc(Assembler::negative, L_third_loop_exit);
9205   subl(idx, 4);
9206 
9207   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9208   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9209   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9210   rorxq(yz_idx2, yz_idx2, 32);
9211 
9212   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9213   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9214 
9215   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9216   rorxq(yz_idx1, yz_idx1, 32);
9217   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9218   rorxq(yz_idx2, yz_idx2, 32);
9219 
9220   if (VM_Version::supports_adx()) {
9221     adcxq(tmp3, carry);
9222     adoxq(tmp3, yz_idx1);
9223 
9224     adcxq(tmp4, tmp);
9225     adoxq(tmp4, yz_idx2);
9226 
9227     movl(carry, 0); // does not affect flags
9228     adcxq(carry2, carry);
9229     adoxq(carry2, carry);
9230   } else {
9231     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9232     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9233   }
9234   movq(carry, carry2);
9235 
9236   movl(Address(z, idx, Address::times_4, 12), tmp3);
9237   shrq(tmp3, 32);
9238   movl(Address(z, idx, Address::times_4,  8), tmp3);
9239 
9240   movl(Address(z, idx, Address::times_4,  4), tmp4);
9241   shrq(tmp4, 32);
9242   movl(Address(z, idx, Address::times_4,  0), tmp4);
9243 
9244   jmp(L_third_loop);
9245 
9246   bind (L_third_loop_exit);
9247 
9248   andl (idx, 0x3);
9249   jcc(Assembler::zero, L_post_third_loop_done);
9250 
9251   Label L_check_1;
9252   subl(idx, 2);
9253   jcc(Assembler::negative, L_check_1);
9254 
9255   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9256   rorxq(yz_idx1, yz_idx1, 32);
9257   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9258   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9259   rorxq(yz_idx2, yz_idx2, 32);
9260 
9261   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9262 
9263   movl(Address(z, idx, Address::times_4,  4), tmp3);
9264   shrq(tmp3, 32);
9265   movl(Address(z, idx, Address::times_4,  0), tmp3);
9266   movq(carry, tmp4);
9267 
9268   bind (L_check_1);
9269   addl (idx, 0x2);
9270   andl (idx, 0x1);
9271   subl(idx, 1);
9272   jcc(Assembler::negative, L_post_third_loop_done);
9273   movl(tmp4, Address(y, idx, Address::times_4,  0));
9274   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9275   movl(tmp4, Address(z, idx, Address::times_4,  0));
9276 
9277   add2_with_carry(carry2, tmp3, tmp4, carry);
9278 
9279   movl(Address(z, idx, Address::times_4,  0), tmp3);
9280   shrq(tmp3, 32);
9281 
9282   shlq(carry2, 32);
9283   orq(tmp3, carry2);
9284   movq(carry, tmp3);
9285 
9286   bind(L_post_third_loop_done);
9287 }
9288 
9289 /**
9290  * Code for BigInteger::multiplyToLen() instrinsic.
9291  *
9292  * rdi: x
9293  * rax: xlen
9294  * rsi: y
9295  * rcx: ylen
9296  * r8:  z
9297  * r11: zlen
9298  * r12: tmp1
9299  * r13: tmp2
9300  * r14: tmp3
9301  * r15: tmp4
9302  * rbx: tmp5
9303  *
9304  */
9305 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9306                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9307   ShortBranchVerifier sbv(this);
9308   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9309 
9310   push(tmp1);
9311   push(tmp2);
9312   push(tmp3);
9313   push(tmp4);
9314   push(tmp5);
9315 
9316   push(xlen);
9317   push(zlen);
9318 
9319   const Register idx = tmp1;
9320   const Register kdx = tmp2;
9321   const Register xstart = tmp3;
9322 
9323   const Register y_idx = tmp4;
9324   const Register carry = tmp5;
9325   const Register product  = xlen;
9326   const Register x_xstart = zlen;  // reuse register
9327 
9328   // First Loop.
9329   //
9330   //  final static long LONG_MASK = 0xffffffffL;
9331   //  int xstart = xlen - 1;
9332   //  int ystart = ylen - 1;
9333   //  long carry = 0;
9334   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9335   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9336   //    z[kdx] = (int)product;
9337   //    carry = product >>> 32;
9338   //  }
9339   //  z[xstart] = (int)carry;
9340   //
9341 
9342   movl(idx, ylen);      // idx = ylen;
9343   movl(kdx, zlen);      // kdx = xlen+ylen;
9344   xorq(carry, carry);   // carry = 0;
9345 
9346   Label L_done;
9347 
9348   movl(xstart, xlen);
9349   decrementl(xstart);
9350   jcc(Assembler::negative, L_done);
9351 
9352   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9353 
9354   Label L_second_loop;
9355   testl(kdx, kdx);
9356   jcc(Assembler::zero, L_second_loop);
9357 
9358   Label L_carry;
9359   subl(kdx, 1);
9360   jcc(Assembler::zero, L_carry);
9361 
9362   movl(Address(z, kdx, Address::times_4,  0), carry);
9363   shrq(carry, 32);
9364   subl(kdx, 1);
9365 
9366   bind(L_carry);
9367   movl(Address(z, kdx, Address::times_4,  0), carry);
9368 
9369   // Second and third (nested) loops.
9370   //
9371   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9372   //   carry = 0;
9373   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9374   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9375   //                    (z[k] & LONG_MASK) + carry;
9376   //     z[k] = (int)product;
9377   //     carry = product >>> 32;
9378   //   }
9379   //   z[i] = (int)carry;
9380   // }
9381   //
9382   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9383 
9384   const Register jdx = tmp1;
9385 
9386   bind(L_second_loop);
9387   xorl(carry, carry);    // carry = 0;
9388   movl(jdx, ylen);       // j = ystart+1
9389 
9390   subl(xstart, 1);       // i = xstart-1;
9391   jcc(Assembler::negative, L_done);
9392 
9393   push (z);
9394 
9395   Label L_last_x;
9396   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9397   subl(xstart, 1);       // i = xstart-1;
9398   jcc(Assembler::negative, L_last_x);
9399 
9400   if (UseBMI2Instructions) {
9401     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9402     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9403   } else {
9404     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9405     rorq(x_xstart, 32);  // convert big-endian to little-endian
9406   }
9407 
9408   Label L_third_loop_prologue;
9409   bind(L_third_loop_prologue);
9410 
9411   push (x);
9412   push (xstart);
9413   push (ylen);
9414 
9415 
9416   if (UseBMI2Instructions) {
9417     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9418   } else { // !UseBMI2Instructions
9419     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9420   }
9421 
9422   pop(ylen);
9423   pop(xlen);
9424   pop(x);
9425   pop(z);
9426 
9427   movl(tmp3, xlen);
9428   addl(tmp3, 1);
9429   movl(Address(z, tmp3, Address::times_4,  0), carry);
9430   subl(tmp3, 1);
9431   jccb(Assembler::negative, L_done);
9432 
9433   shrq(carry, 32);
9434   movl(Address(z, tmp3, Address::times_4,  0), carry);
9435   jmp(L_second_loop);
9436 
9437   // Next infrequent code is moved outside loops.
9438   bind(L_last_x);
9439   if (UseBMI2Instructions) {
9440     movl(rdx, Address(x,  0));
9441   } else {
9442     movl(x_xstart, Address(x,  0));
9443   }
9444   jmp(L_third_loop_prologue);
9445 
9446   bind(L_done);
9447 
9448   pop(zlen);
9449   pop(xlen);
9450 
9451   pop(tmp5);
9452   pop(tmp4);
9453   pop(tmp3);
9454   pop(tmp2);
9455   pop(tmp1);
9456 }
9457 
9458 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9459   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9460   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9461   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9462   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9463   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9464   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9465   Label SAME_TILL_END, DONE;
9466   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9467 
9468   //scale is in rcx in both Win64 and Unix
9469   ShortBranchVerifier sbv(this);
9470 
9471   shlq(length);
9472   xorq(result, result);
9473 
9474   if ((UseAVX > 2) &&
9475       VM_Version::supports_avx512vlbw()) {
9476     set_vector_masking();  // opening of the stub context for programming mask registers
9477     cmpq(length, 64);
9478     jcc(Assembler::less, VECTOR32_TAIL);
9479     movq(tmp1, length);
9480     andq(tmp1, 0x3F);      // tail count
9481     andq(length, ~(0x3F)); //vector count
9482 
9483     bind(VECTOR64_LOOP);
9484     // AVX512 code to compare 64 byte vectors.
9485     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9486     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9487     kortestql(k7, k7);
9488     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9489     addq(result, 64);
9490     subq(length, 64);
9491     jccb(Assembler::notZero, VECTOR64_LOOP);
9492 
9493     //bind(VECTOR64_TAIL);
9494     testq(tmp1, tmp1);
9495     jcc(Assembler::zero, SAME_TILL_END);
9496 
9497     bind(VECTOR64_TAIL);
9498     // AVX512 code to compare upto 63 byte vectors.
9499     // Save k1
9500     kmovql(k3, k1);
9501     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9502     shlxq(tmp2, tmp2, tmp1);
9503     notq(tmp2);
9504     kmovql(k1, tmp2);
9505 
9506     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9507     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9508 
9509     ktestql(k7, k1);
9510     // Restore k1
9511     kmovql(k1, k3);
9512     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9513 
9514     bind(VECTOR64_NOT_EQUAL);
9515     kmovql(tmp1, k7);
9516     notq(tmp1);
9517     tzcntq(tmp1, tmp1);
9518     addq(result, tmp1);
9519     shrq(result);
9520     jmp(DONE);
9521     bind(VECTOR32_TAIL);
9522     clear_vector_masking();   // closing of the stub context for programming mask registers
9523   }
9524 
9525   cmpq(length, 8);
9526   jcc(Assembler::equal, VECTOR8_LOOP);
9527   jcc(Assembler::less, VECTOR4_TAIL);
9528 
9529   if (UseAVX >= 2) {
9530 
9531     cmpq(length, 16);
9532     jcc(Assembler::equal, VECTOR16_LOOP);
9533     jcc(Assembler::less, VECTOR8_LOOP);
9534 
9535     cmpq(length, 32);
9536     jccb(Assembler::less, VECTOR16_TAIL);
9537 
9538     subq(length, 32);
9539     bind(VECTOR32_LOOP);
9540     vmovdqu(rymm0, Address(obja, result));
9541     vmovdqu(rymm1, Address(objb, result));
9542     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9543     vptest(rymm2, rymm2);
9544     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9545     addq(result, 32);
9546     subq(length, 32);
9547     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9548     addq(length, 32);
9549     jcc(Assembler::equal, SAME_TILL_END);
9550     //falling through if less than 32 bytes left //close the branch here.
9551 
9552     bind(VECTOR16_TAIL);
9553     cmpq(length, 16);
9554     jccb(Assembler::less, VECTOR8_TAIL);
9555     bind(VECTOR16_LOOP);
9556     movdqu(rymm0, Address(obja, result));
9557     movdqu(rymm1, Address(objb, result));
9558     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9559     ptest(rymm2, rymm2);
9560     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9561     addq(result, 16);
9562     subq(length, 16);
9563     jcc(Assembler::equal, SAME_TILL_END);
9564     //falling through if less than 16 bytes left
9565   } else {//regular intrinsics
9566 
9567     cmpq(length, 16);
9568     jccb(Assembler::less, VECTOR8_TAIL);
9569 
9570     subq(length, 16);
9571     bind(VECTOR16_LOOP);
9572     movdqu(rymm0, Address(obja, result));
9573     movdqu(rymm1, Address(objb, result));
9574     pxor(rymm0, rymm1);
9575     ptest(rymm0, rymm0);
9576     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9577     addq(result, 16);
9578     subq(length, 16);
9579     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9580     addq(length, 16);
9581     jcc(Assembler::equal, SAME_TILL_END);
9582     //falling through if less than 16 bytes left
9583   }
9584 
9585   bind(VECTOR8_TAIL);
9586   cmpq(length, 8);
9587   jccb(Assembler::less, VECTOR4_TAIL);
9588   bind(VECTOR8_LOOP);
9589   movq(tmp1, Address(obja, result));
9590   movq(tmp2, Address(objb, result));
9591   xorq(tmp1, tmp2);
9592   testq(tmp1, tmp1);
9593   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9594   addq(result, 8);
9595   subq(length, 8);
9596   jcc(Assembler::equal, SAME_TILL_END);
9597   //falling through if less than 8 bytes left
9598 
9599   bind(VECTOR4_TAIL);
9600   cmpq(length, 4);
9601   jccb(Assembler::less, BYTES_TAIL);
9602   bind(VECTOR4_LOOP);
9603   movl(tmp1, Address(obja, result));
9604   xorl(tmp1, Address(objb, result));
9605   testl(tmp1, tmp1);
9606   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9607   addq(result, 4);
9608   subq(length, 4);
9609   jcc(Assembler::equal, SAME_TILL_END);
9610   //falling through if less than 4 bytes left
9611 
9612   bind(BYTES_TAIL);
9613   bind(BYTES_LOOP);
9614   load_unsigned_byte(tmp1, Address(obja, result));
9615   load_unsigned_byte(tmp2, Address(objb, result));
9616   xorl(tmp1, tmp2);
9617   testl(tmp1, tmp1);
9618   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9619   decq(length);
9620   jccb(Assembler::zero, SAME_TILL_END);
9621   incq(result);
9622   load_unsigned_byte(tmp1, Address(obja, result));
9623   load_unsigned_byte(tmp2, Address(objb, result));
9624   xorl(tmp1, tmp2);
9625   testl(tmp1, tmp1);
9626   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9627   decq(length);
9628   jccb(Assembler::zero, SAME_TILL_END);
9629   incq(result);
9630   load_unsigned_byte(tmp1, Address(obja, result));
9631   load_unsigned_byte(tmp2, Address(objb, result));
9632   xorl(tmp1, tmp2);
9633   testl(tmp1, tmp1);
9634   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9635   jmpb(SAME_TILL_END);
9636 
9637   if (UseAVX >= 2) {
9638     bind(VECTOR32_NOT_EQUAL);
9639     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9640     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9641     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9642     vpmovmskb(tmp1, rymm0);
9643     bsfq(tmp1, tmp1);
9644     addq(result, tmp1);
9645     shrq(result);
9646     jmpb(DONE);
9647   }
9648 
9649   bind(VECTOR16_NOT_EQUAL);
9650   if (UseAVX >= 2) {
9651     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9652     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9653     pxor(rymm0, rymm2);
9654   } else {
9655     pcmpeqb(rymm2, rymm2);
9656     pxor(rymm0, rymm1);
9657     pcmpeqb(rymm0, rymm1);
9658     pxor(rymm0, rymm2);
9659   }
9660   pmovmskb(tmp1, rymm0);
9661   bsfq(tmp1, tmp1);
9662   addq(result, tmp1);
9663   shrq(result);
9664   jmpb(DONE);
9665 
9666   bind(VECTOR8_NOT_EQUAL);
9667   bind(VECTOR4_NOT_EQUAL);
9668   bsfq(tmp1, tmp1);
9669   shrq(tmp1, 3);
9670   addq(result, tmp1);
9671   bind(BYTES_NOT_EQUAL);
9672   shrq(result);
9673   jmpb(DONE);
9674 
9675   bind(SAME_TILL_END);
9676   mov64(result, -1);
9677 
9678   bind(DONE);
9679 }
9680 
9681 //Helper functions for square_to_len()
9682 
9683 /**
9684  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9685  * Preserves x and z and modifies rest of the registers.
9686  */
9687 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9688   // Perform square and right shift by 1
9689   // Handle odd xlen case first, then for even xlen do the following
9690   // jlong carry = 0;
9691   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9692   //     huge_128 product = x[j:j+1] * x[j:j+1];
9693   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9694   //     z[i+2:i+3] = (jlong)(product >>> 1);
9695   //     carry = (jlong)product;
9696   // }
9697 
9698   xorq(tmp5, tmp5);     // carry
9699   xorq(rdxReg, rdxReg);
9700   xorl(tmp1, tmp1);     // index for x
9701   xorl(tmp4, tmp4);     // index for z
9702 
9703   Label L_first_loop, L_first_loop_exit;
9704 
9705   testl(xlen, 1);
9706   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9707 
9708   // Square and right shift by 1 the odd element using 32 bit multiply
9709   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9710   imulq(raxReg, raxReg);
9711   shrq(raxReg, 1);
9712   adcq(tmp5, 0);
9713   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9714   incrementl(tmp1);
9715   addl(tmp4, 2);
9716 
9717   // Square and  right shift by 1 the rest using 64 bit multiply
9718   bind(L_first_loop);
9719   cmpptr(tmp1, xlen);
9720   jccb(Assembler::equal, L_first_loop_exit);
9721 
9722   // Square
9723   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9724   rorq(raxReg, 32);    // convert big-endian to little-endian
9725   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9726 
9727   // Right shift by 1 and save carry
9728   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9729   rcrq(rdxReg, 1);
9730   rcrq(raxReg, 1);
9731   adcq(tmp5, 0);
9732 
9733   // Store result in z
9734   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9735   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9736 
9737   // Update indices for x and z
9738   addl(tmp1, 2);
9739   addl(tmp4, 4);
9740   jmp(L_first_loop);
9741 
9742   bind(L_first_loop_exit);
9743 }
9744 
9745 
9746 /**
9747  * Perform the following multiply add operation using BMI2 instructions
9748  * carry:sum = sum + op1*op2 + carry
9749  * op2 should be in rdx
9750  * op2 is preserved, all other registers are modified
9751  */
9752 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9753   // assert op2 is rdx
9754   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9755   addq(sum, carry);
9756   adcq(tmp2, 0);
9757   addq(sum, op1);
9758   adcq(tmp2, 0);
9759   movq(carry, tmp2);
9760 }
9761 
9762 /**
9763  * Perform the following multiply add operation:
9764  * carry:sum = sum + op1*op2 + carry
9765  * Preserves op1, op2 and modifies rest of registers
9766  */
9767 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9768   // rdx:rax = op1 * op2
9769   movq(raxReg, op2);
9770   mulq(op1);
9771 
9772   //  rdx:rax = sum + carry + rdx:rax
9773   addq(sum, carry);
9774   adcq(rdxReg, 0);
9775   addq(sum, raxReg);
9776   adcq(rdxReg, 0);
9777 
9778   // carry:sum = rdx:sum
9779   movq(carry, rdxReg);
9780 }
9781 
9782 /**
9783  * Add 64 bit long carry into z[] with carry propogation.
9784  * Preserves z and carry register values and modifies rest of registers.
9785  *
9786  */
9787 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9788   Label L_fourth_loop, L_fourth_loop_exit;
9789 
9790   movl(tmp1, 1);
9791   subl(zlen, 2);
9792   addq(Address(z, zlen, Address::times_4, 0), carry);
9793 
9794   bind(L_fourth_loop);
9795   jccb(Assembler::carryClear, L_fourth_loop_exit);
9796   subl(zlen, 2);
9797   jccb(Assembler::negative, L_fourth_loop_exit);
9798   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9799   jmp(L_fourth_loop);
9800   bind(L_fourth_loop_exit);
9801 }
9802 
9803 /**
9804  * Shift z[] left by 1 bit.
9805  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9806  *
9807  */
9808 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9809 
9810   Label L_fifth_loop, L_fifth_loop_exit;
9811 
9812   // Fifth loop
9813   // Perform primitiveLeftShift(z, zlen, 1)
9814 
9815   const Register prev_carry = tmp1;
9816   const Register new_carry = tmp4;
9817   const Register value = tmp2;
9818   const Register zidx = tmp3;
9819 
9820   // int zidx, carry;
9821   // long value;
9822   // carry = 0;
9823   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9824   //    (carry:value)  = (z[i] << 1) | carry ;
9825   //    z[i] = value;
9826   // }
9827 
9828   movl(zidx, zlen);
9829   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9830 
9831   bind(L_fifth_loop);
9832   decl(zidx);  // Use decl to preserve carry flag
9833   decl(zidx);
9834   jccb(Assembler::negative, L_fifth_loop_exit);
9835 
9836   if (UseBMI2Instructions) {
9837      movq(value, Address(z, zidx, Address::times_4, 0));
9838      rclq(value, 1);
9839      rorxq(value, value, 32);
9840      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9841   }
9842   else {
9843     // clear new_carry
9844     xorl(new_carry, new_carry);
9845 
9846     // Shift z[i] by 1, or in previous carry and save new carry
9847     movq(value, Address(z, zidx, Address::times_4, 0));
9848     shlq(value, 1);
9849     adcl(new_carry, 0);
9850 
9851     orq(value, prev_carry);
9852     rorq(value, 0x20);
9853     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9854 
9855     // Set previous carry = new carry
9856     movl(prev_carry, new_carry);
9857   }
9858   jmp(L_fifth_loop);
9859 
9860   bind(L_fifth_loop_exit);
9861 }
9862 
9863 
9864 /**
9865  * Code for BigInteger::squareToLen() intrinsic
9866  *
9867  * rdi: x
9868  * rsi: len
9869  * r8:  z
9870  * rcx: zlen
9871  * r12: tmp1
9872  * r13: tmp2
9873  * r14: tmp3
9874  * r15: tmp4
9875  * rbx: tmp5
9876  *
9877  */
9878 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) {
9879 
9880   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;
9881   push(tmp1);
9882   push(tmp2);
9883   push(tmp3);
9884   push(tmp4);
9885   push(tmp5);
9886 
9887   // First loop
9888   // Store the squares, right shifted one bit (i.e., divided by 2).
9889   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9890 
9891   // Add in off-diagonal sums.
9892   //
9893   // Second, third (nested) and fourth loops.
9894   // zlen +=2;
9895   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9896   //    carry = 0;
9897   //    long op2 = x[xidx:xidx+1];
9898   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9899   //       k -= 2;
9900   //       long op1 = x[j:j+1];
9901   //       long sum = z[k:k+1];
9902   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9903   //       z[k:k+1] = sum;
9904   //    }
9905   //    add_one_64(z, k, carry, tmp_regs);
9906   // }
9907 
9908   const Register carry = tmp5;
9909   const Register sum = tmp3;
9910   const Register op1 = tmp4;
9911   Register op2 = tmp2;
9912 
9913   push(zlen);
9914   push(len);
9915   addl(zlen,2);
9916   bind(L_second_loop);
9917   xorq(carry, carry);
9918   subl(zlen, 4);
9919   subl(len, 2);
9920   push(zlen);
9921   push(len);
9922   cmpl(len, 0);
9923   jccb(Assembler::lessEqual, L_second_loop_exit);
9924 
9925   // Multiply an array by one 64 bit long.
9926   if (UseBMI2Instructions) {
9927     op2 = rdxReg;
9928     movq(op2, Address(x, len, Address::times_4,  0));
9929     rorxq(op2, op2, 32);
9930   }
9931   else {
9932     movq(op2, Address(x, len, Address::times_4,  0));
9933     rorq(op2, 32);
9934   }
9935 
9936   bind(L_third_loop);
9937   decrementl(len);
9938   jccb(Assembler::negative, L_third_loop_exit);
9939   decrementl(len);
9940   jccb(Assembler::negative, L_last_x);
9941 
9942   movq(op1, Address(x, len, Address::times_4,  0));
9943   rorq(op1, 32);
9944 
9945   bind(L_multiply);
9946   subl(zlen, 2);
9947   movq(sum, Address(z, zlen, Address::times_4,  0));
9948 
9949   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9950   if (UseBMI2Instructions) {
9951     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9952   }
9953   else {
9954     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9955   }
9956 
9957   movq(Address(z, zlen, Address::times_4, 0), sum);
9958 
9959   jmp(L_third_loop);
9960   bind(L_third_loop_exit);
9961 
9962   // Fourth loop
9963   // Add 64 bit long carry into z with carry propogation.
9964   // Uses offsetted zlen.
9965   add_one_64(z, zlen, carry, tmp1);
9966 
9967   pop(len);
9968   pop(zlen);
9969   jmp(L_second_loop);
9970 
9971   // Next infrequent code is moved outside loops.
9972   bind(L_last_x);
9973   movl(op1, Address(x, 0));
9974   jmp(L_multiply);
9975 
9976   bind(L_second_loop_exit);
9977   pop(len);
9978   pop(zlen);
9979   pop(len);
9980   pop(zlen);
9981 
9982   // Fifth loop
9983   // Shift z left 1 bit.
9984   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9985 
9986   // z[zlen-1] |= x[len-1] & 1;
9987   movl(tmp3, Address(x, len, Address::times_4, -4));
9988   andl(tmp3, 1);
9989   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9990 
9991   pop(tmp5);
9992   pop(tmp4);
9993   pop(tmp3);
9994   pop(tmp2);
9995   pop(tmp1);
9996 }
9997 
9998 /**
9999  * Helper function for mul_add()
10000  * Multiply the in[] by int k and add to out[] starting at offset offs using
10001  * 128 bit by 32 bit multiply and return the carry in tmp5.
10002  * Only quad int aligned length of in[] is operated on in this function.
10003  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10004  * This function preserves out, in and k registers.
10005  * len and offset point to the appropriate index in "in" & "out" correspondingly
10006  * tmp5 has the carry.
10007  * other registers are temporary and are modified.
10008  *
10009  */
10010 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10011   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10012   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10013 
10014   Label L_first_loop, L_first_loop_exit;
10015 
10016   movl(tmp1, len);
10017   shrl(tmp1, 2);
10018 
10019   bind(L_first_loop);
10020   subl(tmp1, 1);
10021   jccb(Assembler::negative, L_first_loop_exit);
10022 
10023   subl(len, 4);
10024   subl(offset, 4);
10025 
10026   Register op2 = tmp2;
10027   const Register sum = tmp3;
10028   const Register op1 = tmp4;
10029   const Register carry = tmp5;
10030 
10031   if (UseBMI2Instructions) {
10032     op2 = rdxReg;
10033   }
10034 
10035   movq(op1, Address(in, len, Address::times_4,  8));
10036   rorq(op1, 32);
10037   movq(sum, Address(out, offset, Address::times_4,  8));
10038   rorq(sum, 32);
10039   if (UseBMI2Instructions) {
10040     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10041   }
10042   else {
10043     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10044   }
10045   // Store back in big endian from little endian
10046   rorq(sum, 0x20);
10047   movq(Address(out, offset, Address::times_4,  8), sum);
10048 
10049   movq(op1, Address(in, len, Address::times_4,  0));
10050   rorq(op1, 32);
10051   movq(sum, Address(out, offset, Address::times_4,  0));
10052   rorq(sum, 32);
10053   if (UseBMI2Instructions) {
10054     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10055   }
10056   else {
10057     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10058   }
10059   // Store back in big endian from little endian
10060   rorq(sum, 0x20);
10061   movq(Address(out, offset, Address::times_4,  0), sum);
10062 
10063   jmp(L_first_loop);
10064   bind(L_first_loop_exit);
10065 }
10066 
10067 /**
10068  * Code for BigInteger::mulAdd() intrinsic
10069  *
10070  * rdi: out
10071  * rsi: in
10072  * r11: offs (out.length - offset)
10073  * rcx: len
10074  * r8:  k
10075  * r12: tmp1
10076  * r13: tmp2
10077  * r14: tmp3
10078  * r15: tmp4
10079  * rbx: tmp5
10080  * Multiply the in[] by word k and add to out[], return the carry in rax
10081  */
10082 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10083    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10084    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10085 
10086   Label L_carry, L_last_in, L_done;
10087 
10088 // carry = 0;
10089 // for (int j=len-1; j >= 0; j--) {
10090 //    long product = (in[j] & LONG_MASK) * kLong +
10091 //                   (out[offs] & LONG_MASK) + carry;
10092 //    out[offs--] = (int)product;
10093 //    carry = product >>> 32;
10094 // }
10095 //
10096   push(tmp1);
10097   push(tmp2);
10098   push(tmp3);
10099   push(tmp4);
10100   push(tmp5);
10101 
10102   Register op2 = tmp2;
10103   const Register sum = tmp3;
10104   const Register op1 = tmp4;
10105   const Register carry =  tmp5;
10106 
10107   if (UseBMI2Instructions) {
10108     op2 = rdxReg;
10109     movl(op2, k);
10110   }
10111   else {
10112     movl(op2, k);
10113   }
10114 
10115   xorq(carry, carry);
10116 
10117   //First loop
10118 
10119   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10120   //The carry is in tmp5
10121   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10122 
10123   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10124   decrementl(len);
10125   jccb(Assembler::negative, L_carry);
10126   decrementl(len);
10127   jccb(Assembler::negative, L_last_in);
10128 
10129   movq(op1, Address(in, len, Address::times_4,  0));
10130   rorq(op1, 32);
10131 
10132   subl(offs, 2);
10133   movq(sum, Address(out, offs, Address::times_4,  0));
10134   rorq(sum, 32);
10135 
10136   if (UseBMI2Instructions) {
10137     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10138   }
10139   else {
10140     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10141   }
10142 
10143   // Store back in big endian from little endian
10144   rorq(sum, 0x20);
10145   movq(Address(out, offs, Address::times_4,  0), sum);
10146 
10147   testl(len, len);
10148   jccb(Assembler::zero, L_carry);
10149 
10150   //Multiply the last in[] entry, if any
10151   bind(L_last_in);
10152   movl(op1, Address(in, 0));
10153   movl(sum, Address(out, offs, Address::times_4,  -4));
10154 
10155   movl(raxReg, k);
10156   mull(op1); //tmp4 * eax -> edx:eax
10157   addl(sum, carry);
10158   adcl(rdxReg, 0);
10159   addl(sum, raxReg);
10160   adcl(rdxReg, 0);
10161   movl(carry, rdxReg);
10162 
10163   movl(Address(out, offs, Address::times_4,  -4), sum);
10164 
10165   bind(L_carry);
10166   //return tmp5/carry as carry in rax
10167   movl(rax, carry);
10168 
10169   bind(L_done);
10170   pop(tmp5);
10171   pop(tmp4);
10172   pop(tmp3);
10173   pop(tmp2);
10174   pop(tmp1);
10175 }
10176 #endif
10177 
10178 /**
10179  * Emits code to update CRC-32 with a byte value according to constants in table
10180  *
10181  * @param [in,out]crc   Register containing the crc.
10182  * @param [in]val       Register containing the byte to fold into the CRC.
10183  * @param [in]table     Register containing the table of crc constants.
10184  *
10185  * uint32_t crc;
10186  * val = crc_table[(val ^ crc) & 0xFF];
10187  * crc = val ^ (crc >> 8);
10188  *
10189  */
10190 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10191   xorl(val, crc);
10192   andl(val, 0xFF);
10193   shrl(crc, 8); // unsigned shift
10194   xorl(crc, Address(table, val, Address::times_4, 0));
10195 }
10196 
10197 /**
10198  * Fold 128-bit data chunk
10199  */
10200 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10201   if (UseAVX > 0) {
10202     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10203     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10204     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10205     pxor(xcrc, xtmp);
10206   } else {
10207     movdqa(xtmp, xcrc);
10208     pclmulhdq(xtmp, xK);   // [123:64]
10209     pclmulldq(xcrc, xK);   // [63:0]
10210     pxor(xcrc, xtmp);
10211     movdqu(xtmp, Address(buf, offset));
10212     pxor(xcrc, xtmp);
10213   }
10214 }
10215 
10216 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10217   if (UseAVX > 0) {
10218     vpclmulhdq(xtmp, xK, xcrc);
10219     vpclmulldq(xcrc, xK, xcrc);
10220     pxor(xcrc, xbuf);
10221     pxor(xcrc, xtmp);
10222   } else {
10223     movdqa(xtmp, xcrc);
10224     pclmulhdq(xtmp, xK);
10225     pclmulldq(xcrc, xK);
10226     pxor(xcrc, xbuf);
10227     pxor(xcrc, xtmp);
10228   }
10229 }
10230 
10231 /**
10232  * 8-bit folds to compute 32-bit CRC
10233  *
10234  * uint64_t xcrc;
10235  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10236  */
10237 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10238   movdl(tmp, xcrc);
10239   andl(tmp, 0xFF);
10240   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10241   psrldq(xcrc, 1); // unsigned shift one byte
10242   pxor(xcrc, xtmp);
10243 }
10244 
10245 /**
10246  * uint32_t crc;
10247  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10248  */
10249 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10250   movl(tmp, crc);
10251   andl(tmp, 0xFF);
10252   shrl(crc, 8);
10253   xorl(crc, Address(table, tmp, Address::times_4, 0));
10254 }
10255 
10256 /**
10257  * @param crc   register containing existing CRC (32-bit)
10258  * @param buf   register pointing to input byte buffer (byte*)
10259  * @param len   register containing number of bytes
10260  * @param table register that will contain address of CRC table
10261  * @param tmp   scratch register
10262  */
10263 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10264   assert_different_registers(crc, buf, len, table, tmp, rax);
10265 
10266   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10267   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10268 
10269   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10270   // context for the registers used, where all instructions below are using 128-bit mode
10271   // On EVEX without VL and BW, these instructions will all be AVX.
10272   if (VM_Version::supports_avx512vlbw()) {
10273     movl(tmp, 0xffff);
10274     kmovwl(k1, tmp);
10275   }
10276 
10277   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10278   notl(crc); // ~crc
10279   cmpl(len, 16);
10280   jcc(Assembler::less, L_tail);
10281 
10282   // Align buffer to 16 bytes
10283   movl(tmp, buf);
10284   andl(tmp, 0xF);
10285   jccb(Assembler::zero, L_aligned);
10286   subl(tmp,  16);
10287   addl(len, tmp);
10288 
10289   align(4);
10290   BIND(L_align_loop);
10291   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10292   update_byte_crc32(crc, rax, table);
10293   increment(buf);
10294   incrementl(tmp);
10295   jccb(Assembler::less, L_align_loop);
10296 
10297   BIND(L_aligned);
10298   movl(tmp, len); // save
10299   shrl(len, 4);
10300   jcc(Assembler::zero, L_tail_restore);
10301 
10302   // Fold crc into first bytes of vector
10303   movdqa(xmm1, Address(buf, 0));
10304   movdl(rax, xmm1);
10305   xorl(crc, rax);
10306   if (VM_Version::supports_sse4_1()) {
10307     pinsrd(xmm1, crc, 0);
10308   } else {
10309     pinsrw(xmm1, crc, 0);
10310     shrl(crc, 16);
10311     pinsrw(xmm1, crc, 1);
10312   }
10313   addptr(buf, 16);
10314   subl(len, 4); // len > 0
10315   jcc(Assembler::less, L_fold_tail);
10316 
10317   movdqa(xmm2, Address(buf,  0));
10318   movdqa(xmm3, Address(buf, 16));
10319   movdqa(xmm4, Address(buf, 32));
10320   addptr(buf, 48);
10321   subl(len, 3);
10322   jcc(Assembler::lessEqual, L_fold_512b);
10323 
10324   // Fold total 512 bits of polynomial on each iteration,
10325   // 128 bits per each of 4 parallel streams.
10326   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10327 
10328   align(32);
10329   BIND(L_fold_512b_loop);
10330   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10331   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10332   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10333   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10334   addptr(buf, 64);
10335   subl(len, 4);
10336   jcc(Assembler::greater, L_fold_512b_loop);
10337 
10338   // Fold 512 bits to 128 bits.
10339   BIND(L_fold_512b);
10340   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10341   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10342   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10343   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10344 
10345   // Fold the rest of 128 bits data chunks
10346   BIND(L_fold_tail);
10347   addl(len, 3);
10348   jccb(Assembler::lessEqual, L_fold_128b);
10349   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10350 
10351   BIND(L_fold_tail_loop);
10352   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10353   addptr(buf, 16);
10354   decrementl(len);
10355   jccb(Assembler::greater, L_fold_tail_loop);
10356 
10357   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10358   BIND(L_fold_128b);
10359   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10360   if (UseAVX > 0) {
10361     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10362     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10363     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10364   } else {
10365     movdqa(xmm2, xmm0);
10366     pclmulqdq(xmm2, xmm1, 0x1);
10367     movdqa(xmm3, xmm0);
10368     pand(xmm3, xmm2);
10369     pclmulqdq(xmm0, xmm3, 0x1);
10370   }
10371   psrldq(xmm1, 8);
10372   psrldq(xmm2, 4);
10373   pxor(xmm0, xmm1);
10374   pxor(xmm0, xmm2);
10375 
10376   // 8 8-bit folds to compute 32-bit CRC.
10377   for (int j = 0; j < 4; j++) {
10378     fold_8bit_crc32(xmm0, table, xmm1, rax);
10379   }
10380   movdl(crc, xmm0); // mov 32 bits to general register
10381   for (int j = 0; j < 4; j++) {
10382     fold_8bit_crc32(crc, table, rax);
10383   }
10384 
10385   BIND(L_tail_restore);
10386   movl(len, tmp); // restore
10387   BIND(L_tail);
10388   andl(len, 0xf);
10389   jccb(Assembler::zero, L_exit);
10390 
10391   // Fold the rest of bytes
10392   align(4);
10393   BIND(L_tail_loop);
10394   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10395   update_byte_crc32(crc, rax, table);
10396   increment(buf);
10397   decrementl(len);
10398   jccb(Assembler::greater, L_tail_loop);
10399 
10400   BIND(L_exit);
10401   notl(crc); // ~c
10402 }
10403 
10404 #ifdef _LP64
10405 // S. Gueron / Information Processing Letters 112 (2012) 184
10406 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10407 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10408 // Output: the 64-bit carry-less product of B * CONST
10409 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10410                                      Register tmp1, Register tmp2, Register tmp3) {
10411   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10412   if (n > 0) {
10413     addq(tmp3, n * 256 * 8);
10414   }
10415   //    Q1 = TABLEExt[n][B & 0xFF];
10416   movl(tmp1, in);
10417   andl(tmp1, 0x000000FF);
10418   shll(tmp1, 3);
10419   addq(tmp1, tmp3);
10420   movq(tmp1, Address(tmp1, 0));
10421 
10422   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10423   movl(tmp2, in);
10424   shrl(tmp2, 8);
10425   andl(tmp2, 0x000000FF);
10426   shll(tmp2, 3);
10427   addq(tmp2, tmp3);
10428   movq(tmp2, Address(tmp2, 0));
10429 
10430   shlq(tmp2, 8);
10431   xorq(tmp1, tmp2);
10432 
10433   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10434   movl(tmp2, in);
10435   shrl(tmp2, 16);
10436   andl(tmp2, 0x000000FF);
10437   shll(tmp2, 3);
10438   addq(tmp2, tmp3);
10439   movq(tmp2, Address(tmp2, 0));
10440 
10441   shlq(tmp2, 16);
10442   xorq(tmp1, tmp2);
10443 
10444   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10445   shrl(in, 24);
10446   andl(in, 0x000000FF);
10447   shll(in, 3);
10448   addq(in, tmp3);
10449   movq(in, Address(in, 0));
10450 
10451   shlq(in, 24);
10452   xorq(in, tmp1);
10453   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10454 }
10455 
10456 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10457                                       Register in_out,
10458                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10459                                       XMMRegister w_xtmp2,
10460                                       Register tmp1,
10461                                       Register n_tmp2, Register n_tmp3) {
10462   if (is_pclmulqdq_supported) {
10463     movdl(w_xtmp1, in_out); // modified blindly
10464 
10465     movl(tmp1, const_or_pre_comp_const_index);
10466     movdl(w_xtmp2, tmp1);
10467     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10468 
10469     movdq(in_out, w_xtmp1);
10470   } else {
10471     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10472   }
10473 }
10474 
10475 // Recombination Alternative 2: No bit-reflections
10476 // T1 = (CRC_A * U1) << 1
10477 // T2 = (CRC_B * U2) << 1
10478 // C1 = T1 >> 32
10479 // C2 = T2 >> 32
10480 // T1 = T1 & 0xFFFFFFFF
10481 // T2 = T2 & 0xFFFFFFFF
10482 // T1 = CRC32(0, T1)
10483 // T2 = CRC32(0, T2)
10484 // C1 = C1 ^ T1
10485 // C2 = C2 ^ T2
10486 // CRC = C1 ^ C2 ^ CRC_C
10487 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,
10488                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10489                                      Register tmp1, Register tmp2,
10490                                      Register n_tmp3) {
10491   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10492   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10493   shlq(in_out, 1);
10494   movl(tmp1, in_out);
10495   shrq(in_out, 32);
10496   xorl(tmp2, tmp2);
10497   crc32(tmp2, tmp1, 4);
10498   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10499   shlq(in1, 1);
10500   movl(tmp1, in1);
10501   shrq(in1, 32);
10502   xorl(tmp2, tmp2);
10503   crc32(tmp2, tmp1, 4);
10504   xorl(in1, tmp2);
10505   xorl(in_out, in1);
10506   xorl(in_out, in2);
10507 }
10508 
10509 // Set N to predefined value
10510 // Subtract from a lenght of a buffer
10511 // execute in a loop:
10512 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10513 // for i = 1 to N do
10514 //  CRC_A = CRC32(CRC_A, A[i])
10515 //  CRC_B = CRC32(CRC_B, B[i])
10516 //  CRC_C = CRC32(CRC_C, C[i])
10517 // end for
10518 // Recombine
10519 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,
10520                                        Register in_out1, Register in_out2, Register in_out3,
10521                                        Register tmp1, Register tmp2, Register tmp3,
10522                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10523                                        Register tmp4, Register tmp5,
10524                                        Register n_tmp6) {
10525   Label L_processPartitions;
10526   Label L_processPartition;
10527   Label L_exit;
10528 
10529   bind(L_processPartitions);
10530   cmpl(in_out1, 3 * size);
10531   jcc(Assembler::less, L_exit);
10532     xorl(tmp1, tmp1);
10533     xorl(tmp2, tmp2);
10534     movq(tmp3, in_out2);
10535     addq(tmp3, size);
10536 
10537     bind(L_processPartition);
10538       crc32(in_out3, Address(in_out2, 0), 8);
10539       crc32(tmp1, Address(in_out2, size), 8);
10540       crc32(tmp2, Address(in_out2, size * 2), 8);
10541       addq(in_out2, 8);
10542       cmpq(in_out2, tmp3);
10543       jcc(Assembler::less, L_processPartition);
10544     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10545             w_xtmp1, w_xtmp2, w_xtmp3,
10546             tmp4, tmp5,
10547             n_tmp6);
10548     addq(in_out2, 2 * size);
10549     subl(in_out1, 3 * size);
10550     jmp(L_processPartitions);
10551 
10552   bind(L_exit);
10553 }
10554 #else
10555 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10556                                      Register tmp1, Register tmp2, Register tmp3,
10557                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10558   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10559   if (n > 0) {
10560     addl(tmp3, n * 256 * 8);
10561   }
10562   //    Q1 = TABLEExt[n][B & 0xFF];
10563   movl(tmp1, in_out);
10564   andl(tmp1, 0x000000FF);
10565   shll(tmp1, 3);
10566   addl(tmp1, tmp3);
10567   movq(xtmp1, Address(tmp1, 0));
10568 
10569   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10570   movl(tmp2, in_out);
10571   shrl(tmp2, 8);
10572   andl(tmp2, 0x000000FF);
10573   shll(tmp2, 3);
10574   addl(tmp2, tmp3);
10575   movq(xtmp2, Address(tmp2, 0));
10576 
10577   psllq(xtmp2, 8);
10578   pxor(xtmp1, xtmp2);
10579 
10580   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10581   movl(tmp2, in_out);
10582   shrl(tmp2, 16);
10583   andl(tmp2, 0x000000FF);
10584   shll(tmp2, 3);
10585   addl(tmp2, tmp3);
10586   movq(xtmp2, Address(tmp2, 0));
10587 
10588   psllq(xtmp2, 16);
10589   pxor(xtmp1, xtmp2);
10590 
10591   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10592   shrl(in_out, 24);
10593   andl(in_out, 0x000000FF);
10594   shll(in_out, 3);
10595   addl(in_out, tmp3);
10596   movq(xtmp2, Address(in_out, 0));
10597 
10598   psllq(xtmp2, 24);
10599   pxor(xtmp1, xtmp2); // Result in CXMM
10600   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10601 }
10602 
10603 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10604                                       Register in_out,
10605                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10606                                       XMMRegister w_xtmp2,
10607                                       Register tmp1,
10608                                       Register n_tmp2, Register n_tmp3) {
10609   if (is_pclmulqdq_supported) {
10610     movdl(w_xtmp1, in_out);
10611 
10612     movl(tmp1, const_or_pre_comp_const_index);
10613     movdl(w_xtmp2, tmp1);
10614     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10615     // Keep result in XMM since GPR is 32 bit in length
10616   } else {
10617     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10618   }
10619 }
10620 
10621 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,
10622                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10623                                      Register tmp1, Register tmp2,
10624                                      Register n_tmp3) {
10625   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10626   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10627 
10628   psllq(w_xtmp1, 1);
10629   movdl(tmp1, w_xtmp1);
10630   psrlq(w_xtmp1, 32);
10631   movdl(in_out, w_xtmp1);
10632 
10633   xorl(tmp2, tmp2);
10634   crc32(tmp2, tmp1, 4);
10635   xorl(in_out, tmp2);
10636 
10637   psllq(w_xtmp2, 1);
10638   movdl(tmp1, w_xtmp2);
10639   psrlq(w_xtmp2, 32);
10640   movdl(in1, w_xtmp2);
10641 
10642   xorl(tmp2, tmp2);
10643   crc32(tmp2, tmp1, 4);
10644   xorl(in1, tmp2);
10645   xorl(in_out, in1);
10646   xorl(in_out, in2);
10647 }
10648 
10649 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,
10650                                        Register in_out1, Register in_out2, Register in_out3,
10651                                        Register tmp1, Register tmp2, Register tmp3,
10652                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10653                                        Register tmp4, Register tmp5,
10654                                        Register n_tmp6) {
10655   Label L_processPartitions;
10656   Label L_processPartition;
10657   Label L_exit;
10658 
10659   bind(L_processPartitions);
10660   cmpl(in_out1, 3 * size);
10661   jcc(Assembler::less, L_exit);
10662     xorl(tmp1, tmp1);
10663     xorl(tmp2, tmp2);
10664     movl(tmp3, in_out2);
10665     addl(tmp3, size);
10666 
10667     bind(L_processPartition);
10668       crc32(in_out3, Address(in_out2, 0), 4);
10669       crc32(tmp1, Address(in_out2, size), 4);
10670       crc32(tmp2, Address(in_out2, size*2), 4);
10671       crc32(in_out3, Address(in_out2, 0+4), 4);
10672       crc32(tmp1, Address(in_out2, size+4), 4);
10673       crc32(tmp2, Address(in_out2, size*2+4), 4);
10674       addl(in_out2, 8);
10675       cmpl(in_out2, tmp3);
10676       jcc(Assembler::less, L_processPartition);
10677 
10678         push(tmp3);
10679         push(in_out1);
10680         push(in_out2);
10681         tmp4 = tmp3;
10682         tmp5 = in_out1;
10683         n_tmp6 = in_out2;
10684 
10685       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10686             w_xtmp1, w_xtmp2, w_xtmp3,
10687             tmp4, tmp5,
10688             n_tmp6);
10689 
10690         pop(in_out2);
10691         pop(in_out1);
10692         pop(tmp3);
10693 
10694     addl(in_out2, 2 * size);
10695     subl(in_out1, 3 * size);
10696     jmp(L_processPartitions);
10697 
10698   bind(L_exit);
10699 }
10700 #endif //LP64
10701 
10702 #ifdef _LP64
10703 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10704 // Input: A buffer I of L bytes.
10705 // Output: the CRC32C value of the buffer.
10706 // Notations:
10707 // Write L = 24N + r, with N = floor (L/24).
10708 // r = L mod 24 (0 <= r < 24).
10709 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10710 // N quadwords, and R consists of r bytes.
10711 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10712 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10713 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10714 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10715 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10716                                           Register tmp1, Register tmp2, Register tmp3,
10717                                           Register tmp4, Register tmp5, Register tmp6,
10718                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10719                                           bool is_pclmulqdq_supported) {
10720   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10721   Label L_wordByWord;
10722   Label L_byteByByteProlog;
10723   Label L_byteByByte;
10724   Label L_exit;
10725 
10726   if (is_pclmulqdq_supported ) {
10727     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10728     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10729 
10730     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10731     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10732 
10733     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10734     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10735     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10736   } else {
10737     const_or_pre_comp_const_index[0] = 1;
10738     const_or_pre_comp_const_index[1] = 0;
10739 
10740     const_or_pre_comp_const_index[2] = 3;
10741     const_or_pre_comp_const_index[3] = 2;
10742 
10743     const_or_pre_comp_const_index[4] = 5;
10744     const_or_pre_comp_const_index[5] = 4;
10745    }
10746   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10747                     in2, in1, in_out,
10748                     tmp1, tmp2, tmp3,
10749                     w_xtmp1, w_xtmp2, w_xtmp3,
10750                     tmp4, tmp5,
10751                     tmp6);
10752   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10753                     in2, in1, in_out,
10754                     tmp1, tmp2, tmp3,
10755                     w_xtmp1, w_xtmp2, w_xtmp3,
10756                     tmp4, tmp5,
10757                     tmp6);
10758   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10759                     in2, in1, in_out,
10760                     tmp1, tmp2, tmp3,
10761                     w_xtmp1, w_xtmp2, w_xtmp3,
10762                     tmp4, tmp5,
10763                     tmp6);
10764   movl(tmp1, in2);
10765   andl(tmp1, 0x00000007);
10766   negl(tmp1);
10767   addl(tmp1, in2);
10768   addq(tmp1, in1);
10769 
10770   BIND(L_wordByWord);
10771   cmpq(in1, tmp1);
10772   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10773     crc32(in_out, Address(in1, 0), 4);
10774     addq(in1, 4);
10775     jmp(L_wordByWord);
10776 
10777   BIND(L_byteByByteProlog);
10778   andl(in2, 0x00000007);
10779   movl(tmp2, 1);
10780 
10781   BIND(L_byteByByte);
10782   cmpl(tmp2, in2);
10783   jccb(Assembler::greater, L_exit);
10784     crc32(in_out, Address(in1, 0), 1);
10785     incq(in1);
10786     incl(tmp2);
10787     jmp(L_byteByByte);
10788 
10789   BIND(L_exit);
10790 }
10791 #else
10792 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10793                                           Register tmp1, Register  tmp2, Register tmp3,
10794                                           Register tmp4, Register  tmp5, Register tmp6,
10795                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10796                                           bool is_pclmulqdq_supported) {
10797   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10798   Label L_wordByWord;
10799   Label L_byteByByteProlog;
10800   Label L_byteByByte;
10801   Label L_exit;
10802 
10803   if (is_pclmulqdq_supported) {
10804     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10805     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10806 
10807     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10808     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10809 
10810     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10811     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10812   } else {
10813     const_or_pre_comp_const_index[0] = 1;
10814     const_or_pre_comp_const_index[1] = 0;
10815 
10816     const_or_pre_comp_const_index[2] = 3;
10817     const_or_pre_comp_const_index[3] = 2;
10818 
10819     const_or_pre_comp_const_index[4] = 5;
10820     const_or_pre_comp_const_index[5] = 4;
10821   }
10822   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10823                     in2, in1, in_out,
10824                     tmp1, tmp2, tmp3,
10825                     w_xtmp1, w_xtmp2, w_xtmp3,
10826                     tmp4, tmp5,
10827                     tmp6);
10828   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10829                     in2, in1, in_out,
10830                     tmp1, tmp2, tmp3,
10831                     w_xtmp1, w_xtmp2, w_xtmp3,
10832                     tmp4, tmp5,
10833                     tmp6);
10834   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10835                     in2, in1, in_out,
10836                     tmp1, tmp2, tmp3,
10837                     w_xtmp1, w_xtmp2, w_xtmp3,
10838                     tmp4, tmp5,
10839                     tmp6);
10840   movl(tmp1, in2);
10841   andl(tmp1, 0x00000007);
10842   negl(tmp1);
10843   addl(tmp1, in2);
10844   addl(tmp1, in1);
10845 
10846   BIND(L_wordByWord);
10847   cmpl(in1, tmp1);
10848   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10849     crc32(in_out, Address(in1,0), 4);
10850     addl(in1, 4);
10851     jmp(L_wordByWord);
10852 
10853   BIND(L_byteByByteProlog);
10854   andl(in2, 0x00000007);
10855   movl(tmp2, 1);
10856 
10857   BIND(L_byteByByte);
10858   cmpl(tmp2, in2);
10859   jccb(Assembler::greater, L_exit);
10860     movb(tmp1, Address(in1, 0));
10861     crc32(in_out, tmp1, 1);
10862     incl(in1);
10863     incl(tmp2);
10864     jmp(L_byteByByte);
10865 
10866   BIND(L_exit);
10867 }
10868 #endif // LP64
10869 #undef BIND
10870 #undef BLOCK_COMMENT
10871 
10872 // Compress char[] array to byte[].
10873 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10874 //   @HotSpotIntrinsicCandidate
10875 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10876 //     for (int i = 0; i < len; i++) {
10877 //       int c = src[srcOff++];
10878 //       if (c >>> 8 != 0) {
10879 //         return 0;
10880 //       }
10881 //       dst[dstOff++] = (byte)c;
10882 //     }
10883 //     return len;
10884 //   }
10885 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10886   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10887   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10888   Register tmp5, Register result) {
10889   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10890 
10891   // rsi: src
10892   // rdi: dst
10893   // rdx: len
10894   // rcx: tmp5
10895   // rax: result
10896 
10897   // rsi holds start addr of source char[] to be compressed
10898   // rdi holds start addr of destination byte[]
10899   // rdx holds length
10900 
10901   assert(len != result, "");
10902 
10903   // save length for return
10904   push(len);
10905 
10906   if ((UseAVX > 2) && // AVX512
10907     VM_Version::supports_avx512vlbw() &&
10908     VM_Version::supports_bmi2()) {
10909 
10910     set_vector_masking();  // opening of the stub context for programming mask registers
10911 
10912     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10913 
10914     // alignement
10915     Label post_alignement;
10916 
10917     // if length of the string is less than 16, handle it in an old fashioned
10918     // way
10919     testl(len, -32);
10920     jcc(Assembler::zero, below_threshold);
10921 
10922     // First check whether a character is compressable ( <= 0xFF).
10923     // Create mask to test for Unicode chars inside zmm vector
10924     movl(result, 0x00FF);
10925     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10926 
10927     // Save k1
10928     kmovql(k3, k1);
10929 
10930     testl(len, -64);
10931     jcc(Assembler::zero, post_alignement);
10932 
10933     movl(tmp5, dst);
10934     andl(tmp5, (32 - 1));
10935     negl(tmp5);
10936     andl(tmp5, (32 - 1));
10937 
10938     // bail out when there is nothing to be done
10939     testl(tmp5, 0xFFFFFFFF);
10940     jcc(Assembler::zero, post_alignement);
10941 
10942     // ~(~0 << len), where len is the # of remaining elements to process
10943     movl(result, 0xFFFFFFFF);
10944     shlxl(result, result, tmp5);
10945     notl(result);
10946     kmovdl(k1, result);
10947 
10948     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10949     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10950     ktestd(k2, k1);
10951     jcc(Assembler::carryClear, restore_k1_return_zero);
10952 
10953     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10954 
10955     addptr(src, tmp5);
10956     addptr(src, tmp5);
10957     addptr(dst, tmp5);
10958     subl(len, tmp5);
10959 
10960     bind(post_alignement);
10961     // end of alignement
10962 
10963     movl(tmp5, len);
10964     andl(tmp5, (32 - 1));    // tail count (in chars)
10965     andl(len, ~(32 - 1));    // vector count (in chars)
10966     jcc(Assembler::zero, copy_loop_tail);
10967 
10968     lea(src, Address(src, len, Address::times_2));
10969     lea(dst, Address(dst, len, Address::times_1));
10970     negptr(len);
10971 
10972     bind(copy_32_loop);
10973     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10974     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10975     kortestdl(k2, k2);
10976     jcc(Assembler::carryClear, restore_k1_return_zero);
10977 
10978     // All elements in current processed chunk are valid candidates for
10979     // compression. Write a truncated byte elements to the memory.
10980     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10981     addptr(len, 32);
10982     jcc(Assembler::notZero, copy_32_loop);
10983 
10984     bind(copy_loop_tail);
10985     // bail out when there is nothing to be done
10986     testl(tmp5, 0xFFFFFFFF);
10987     // Restore k1
10988     kmovql(k1, k3);
10989     jcc(Assembler::zero, return_length);
10990 
10991     movl(len, tmp5);
10992 
10993     // ~(~0 << len), where len is the # of remaining elements to process
10994     movl(result, 0xFFFFFFFF);
10995     shlxl(result, result, len);
10996     notl(result);
10997 
10998     kmovdl(k1, result);
10999 
11000     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11001     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11002     ktestd(k2, k1);
11003     jcc(Assembler::carryClear, restore_k1_return_zero);
11004 
11005     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11006     // Restore k1
11007     kmovql(k1, k3);
11008     jmp(return_length);
11009 
11010     bind(restore_k1_return_zero);
11011     // Restore k1
11012     kmovql(k1, k3);
11013     jmp(return_zero);
11014 
11015     clear_vector_masking();   // closing of the stub context for programming mask registers
11016   }
11017   if (UseSSE42Intrinsics) {
11018     Label copy_32_loop, copy_16, copy_tail;
11019 
11020     bind(below_threshold);
11021 
11022     movl(result, len);
11023 
11024     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11025 
11026     // vectored compression
11027     andl(len, 0xfffffff0);    // vector count (in chars)
11028     andl(result, 0x0000000f);    // tail count (in chars)
11029     testl(len, len);
11030     jccb(Assembler::zero, copy_16);
11031 
11032     // compress 16 chars per iter
11033     movdl(tmp1Reg, tmp5);
11034     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11035     pxor(tmp4Reg, tmp4Reg);
11036 
11037     lea(src, Address(src, len, Address::times_2));
11038     lea(dst, Address(dst, len, Address::times_1));
11039     negptr(len);
11040 
11041     bind(copy_32_loop);
11042     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11043     por(tmp4Reg, tmp2Reg);
11044     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11045     por(tmp4Reg, tmp3Reg);
11046     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11047     jcc(Assembler::notZero, return_zero);
11048     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11049     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11050     addptr(len, 16);
11051     jcc(Assembler::notZero, copy_32_loop);
11052 
11053     // compress next vector of 8 chars (if any)
11054     bind(copy_16);
11055     movl(len, result);
11056     andl(len, 0xfffffff8);    // vector count (in chars)
11057     andl(result, 0x00000007);    // tail count (in chars)
11058     testl(len, len);
11059     jccb(Assembler::zero, copy_tail);
11060 
11061     movdl(tmp1Reg, tmp5);
11062     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11063     pxor(tmp3Reg, tmp3Reg);
11064 
11065     movdqu(tmp2Reg, Address(src, 0));
11066     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11067     jccb(Assembler::notZero, return_zero);
11068     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11069     movq(Address(dst, 0), tmp2Reg);
11070     addptr(src, 16);
11071     addptr(dst, 8);
11072 
11073     bind(copy_tail);
11074     movl(len, result);
11075   }
11076   // compress 1 char per iter
11077   testl(len, len);
11078   jccb(Assembler::zero, return_length);
11079   lea(src, Address(src, len, Address::times_2));
11080   lea(dst, Address(dst, len, Address::times_1));
11081   negptr(len);
11082 
11083   bind(copy_chars_loop);
11084   load_unsigned_short(result, Address(src, len, Address::times_2));
11085   testl(result, 0xff00);      // check if Unicode char
11086   jccb(Assembler::notZero, return_zero);
11087   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11088   increment(len);
11089   jcc(Assembler::notZero, copy_chars_loop);
11090 
11091   // if compression succeeded, return length
11092   bind(return_length);
11093   pop(result);
11094   jmpb(done);
11095 
11096   // if compression failed, return 0
11097   bind(return_zero);
11098   xorl(result, result);
11099   addptr(rsp, wordSize);
11100 
11101   bind(done);
11102 }
11103 
11104 // Inflate byte[] array to char[].
11105 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11106 //   @HotSpotIntrinsicCandidate
11107 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11108 //     for (int i = 0; i < len; i++) {
11109 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11110 //     }
11111 //   }
11112 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11113   XMMRegister tmp1, Register tmp2) {
11114   Label copy_chars_loop, done, below_threshold;
11115   // rsi: src
11116   // rdi: dst
11117   // rdx: len
11118   // rcx: tmp2
11119 
11120   // rsi holds start addr of source byte[] to be inflated
11121   // rdi holds start addr of destination char[]
11122   // rdx holds length
11123   assert_different_registers(src, dst, len, tmp2);
11124 
11125   if ((UseAVX > 2) && // AVX512
11126     VM_Version::supports_avx512vlbw() &&
11127     VM_Version::supports_bmi2()) {
11128 
11129     set_vector_masking();  // opening of the stub context for programming mask registers
11130 
11131     Label copy_32_loop, copy_tail;
11132     Register tmp3_aliased = len;
11133 
11134     // if length of the string is less than 16, handle it in an old fashioned
11135     // way
11136     testl(len, -16);
11137     jcc(Assembler::zero, below_threshold);
11138 
11139     // In order to use only one arithmetic operation for the main loop we use
11140     // this pre-calculation
11141     movl(tmp2, len);
11142     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11143     andl(len, -32);     // vector count
11144     jccb(Assembler::zero, copy_tail);
11145 
11146     lea(src, Address(src, len, Address::times_1));
11147     lea(dst, Address(dst, len, Address::times_2));
11148     negptr(len);
11149 
11150 
11151     // inflate 32 chars per iter
11152     bind(copy_32_loop);
11153     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11154     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11155     addptr(len, 32);
11156     jcc(Assembler::notZero, copy_32_loop);
11157 
11158     bind(copy_tail);
11159     // bail out when there is nothing to be done
11160     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11161     jcc(Assembler::zero, done);
11162 
11163     // Save k1
11164     kmovql(k2, k1);
11165 
11166     // ~(~0 << length), where length is the # of remaining elements to process
11167     movl(tmp3_aliased, -1);
11168     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11169     notl(tmp3_aliased);
11170     kmovdl(k1, tmp3_aliased);
11171     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11172     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11173 
11174     // Restore k1
11175     kmovql(k1, k2);
11176     jmp(done);
11177 
11178     clear_vector_masking();   // closing of the stub context for programming mask registers
11179   }
11180   if (UseSSE42Intrinsics) {
11181     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11182 
11183     movl(tmp2, len);
11184 
11185     if (UseAVX > 1) {
11186       andl(tmp2, (16 - 1));
11187       andl(len, -16);
11188       jccb(Assembler::zero, copy_new_tail);
11189     } else {
11190       andl(tmp2, 0x00000007);   // tail count (in chars)
11191       andl(len, 0xfffffff8);    // vector count (in chars)
11192       jccb(Assembler::zero, copy_tail);
11193     }
11194 
11195     // vectored inflation
11196     lea(src, Address(src, len, Address::times_1));
11197     lea(dst, Address(dst, len, Address::times_2));
11198     negptr(len);
11199 
11200     if (UseAVX > 1) {
11201       bind(copy_16_loop);
11202       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11203       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11204       addptr(len, 16);
11205       jcc(Assembler::notZero, copy_16_loop);
11206 
11207       bind(below_threshold);
11208       bind(copy_new_tail);
11209       if ((UseAVX > 2) &&
11210         VM_Version::supports_avx512vlbw() &&
11211         VM_Version::supports_bmi2()) {
11212         movl(tmp2, len);
11213       } else {
11214         movl(len, tmp2);
11215       }
11216       andl(tmp2, 0x00000007);
11217       andl(len, 0xFFFFFFF8);
11218       jccb(Assembler::zero, copy_tail);
11219 
11220       pmovzxbw(tmp1, Address(src, 0));
11221       movdqu(Address(dst, 0), tmp1);
11222       addptr(src, 8);
11223       addptr(dst, 2 * 8);
11224 
11225       jmp(copy_tail, true);
11226     }
11227 
11228     // inflate 8 chars per iter
11229     bind(copy_8_loop);
11230     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11231     movdqu(Address(dst, len, Address::times_2), tmp1);
11232     addptr(len, 8);
11233     jcc(Assembler::notZero, copy_8_loop);
11234 
11235     bind(copy_tail);
11236     movl(len, tmp2);
11237 
11238     cmpl(len, 4);
11239     jccb(Assembler::less, copy_bytes);
11240 
11241     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11242     pmovzxbw(tmp1, tmp1);
11243     movq(Address(dst, 0), tmp1);
11244     subptr(len, 4);
11245     addptr(src, 4);
11246     addptr(dst, 8);
11247 
11248     bind(copy_bytes);
11249   }
11250   testl(len, len);
11251   jccb(Assembler::zero, done);
11252   lea(src, Address(src, len, Address::times_1));
11253   lea(dst, Address(dst, len, Address::times_2));
11254   negptr(len);
11255 
11256   // inflate 1 char per iter
11257   bind(copy_chars_loop);
11258   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11259   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11260   increment(len);
11261   jcc(Assembler::notZero, copy_chars_loop);
11262 
11263   bind(done);
11264 }
11265 
11266 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11267   switch (cond) {
11268     // Note some conditions are synonyms for others
11269     case Assembler::zero:         return Assembler::notZero;
11270     case Assembler::notZero:      return Assembler::zero;
11271     case Assembler::less:         return Assembler::greaterEqual;
11272     case Assembler::lessEqual:    return Assembler::greater;
11273     case Assembler::greater:      return Assembler::lessEqual;
11274     case Assembler::greaterEqual: return Assembler::less;
11275     case Assembler::below:        return Assembler::aboveEqual;
11276     case Assembler::belowEqual:   return Assembler::above;
11277     case Assembler::above:        return Assembler::belowEqual;
11278     case Assembler::aboveEqual:   return Assembler::below;
11279     case Assembler::overflow:     return Assembler::noOverflow;
11280     case Assembler::noOverflow:   return Assembler::overflow;
11281     case Assembler::negative:     return Assembler::positive;
11282     case Assembler::positive:     return Assembler::negative;
11283     case Assembler::parity:       return Assembler::noParity;
11284     case Assembler::noParity:     return Assembler::parity;
11285   }
11286   ShouldNotReachHere(); return Assembler::overflow;
11287 }
11288 
11289 SkipIfEqual::SkipIfEqual(
11290     MacroAssembler* masm, const bool* flag_addr, bool value) {
11291   _masm = masm;
11292   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11293   _masm->jcc(Assembler::equal, _label);
11294 }
11295 
11296 SkipIfEqual::~SkipIfEqual() {
11297   _masm->bind(_label);
11298 }
11299 
11300 // 32-bit Windows has its own fast-path implementation
11301 // of get_thread
11302 #if !defined(WIN32) || defined(_LP64)
11303 
11304 // This is simply a call to Thread::current()
11305 void MacroAssembler::get_thread(Register thread) {
11306   if (thread != rax) {
11307     push(rax);
11308   }
11309   LP64_ONLY(push(rdi);)
11310   LP64_ONLY(push(rsi);)
11311   push(rdx);
11312   push(rcx);
11313 #ifdef _LP64
11314   push(r8);
11315   push(r9);
11316   push(r10);
11317   push(r11);
11318 #endif
11319 
11320   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11321 
11322 #ifdef _LP64
11323   pop(r11);
11324   pop(r10);
11325   pop(r9);
11326   pop(r8);
11327 #endif
11328   pop(rcx);
11329   pop(rdx);
11330   LP64_ONLY(pop(rsi);)
11331   LP64_ONLY(pop(rdi);)
11332   if (thread != rax) {
11333     mov(thread, rax);
11334     pop(rax);
11335   }
11336 }
11337 
11338 #endif