1 /*
   2  * Copyright (c) 1997, 2018, 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 "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/cardTableModRefBS.hpp"
  31 #include "gc/shared/collectedHeap.inline.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "memory/universe.hpp"
  35 #include "oops/klass.inline.hpp"
  36 #include "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 #include "gc/z/zGlobals.hpp"
  52 #endif // INCLUDE_ALL_GCS
  53 #include "crc32c.h"
  54 #ifdef COMPILER2
  55 #include "opto/intrinsicnode.hpp"
  56 #endif
  57 
  58 #ifdef PRODUCT
  59 #define BLOCK_COMMENT(str) /* nothing */
  60 #define STOP(error) stop(error)
  61 #else
  62 #define BLOCK_COMMENT(str) block_comment(str)
  63 #define STOP(error) block_comment(error); stop(error)
  64 #endif
  65 
  66 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  67 
  68 #ifdef ASSERT
  69 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  70 #endif
  71 
  72 static Assembler::Condition reverse[] = {
  73     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  74     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  75     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  76     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  77     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  78     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  79     Assembler::above          /* belowEqual    = 0x6 */ ,
  80     Assembler::belowEqual     /* above         = 0x7 */ ,
  81     Assembler::positive       /* negative      = 0x8 */ ,
  82     Assembler::negative       /* positive      = 0x9 */ ,
  83     Assembler::noParity       /* parity        = 0xa */ ,
  84     Assembler::parity         /* noParity      = 0xb */ ,
  85     Assembler::greaterEqual   /* less          = 0xc */ ,
  86     Assembler::less           /* greaterEqual  = 0xd */ ,
  87     Assembler::greater        /* lessEqual     = 0xe */ ,
  88     Assembler::lessEqual      /* greater       = 0xf, */
  89 
  90 };
  91 
  92 
  93 // Implementation of MacroAssembler
  94 
  95 // First all the versions that have distinct versions depending on 32/64 bit
  96 // Unless the difference is trivial (1 line or so).
  97 
  98 #ifndef _LP64
  99 
 100 // 32bit versions
 101 
 102 Address MacroAssembler::as_Address(AddressLiteral adr) {
 103   return Address(adr.target(), adr.rspec());
 104 }
 105 
 106 Address MacroAssembler::as_Address(ArrayAddress adr) {
 107   return Address::make_array(adr);
 108 }
 109 
 110 void MacroAssembler::call_VM_leaf_base(address entry_point,
 111                                        int number_of_arguments) {
 112   call(RuntimeAddress(entry_point));
 113   increment(rsp, number_of_arguments * wordSize);
 114 }
 115 
 116 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 117   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 121   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 125   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 126 }
 127 
 128 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 129   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 130 }
 131 
 132 void MacroAssembler::extend_sign(Register hi, Register lo) {
 133   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 134   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 135     cdql();
 136   } else {
 137     movl(hi, lo);
 138     sarl(hi, 31);
 139   }
 140 }
 141 
 142 void MacroAssembler::jC2(Register tmp, Label& L) {
 143   // set parity bit if FPU flag C2 is set (via rax)
 144   save_rax(tmp);
 145   fwait(); fnstsw_ax();
 146   sahf();
 147   restore_rax(tmp);
 148   // branch
 149   jcc(Assembler::parity, L);
 150 }
 151 
 152 void MacroAssembler::jnC2(Register tmp, Label& L) {
 153   // set parity bit if FPU flag C2 is set (via rax)
 154   save_rax(tmp);
 155   fwait(); fnstsw_ax();
 156   sahf();
 157   restore_rax(tmp);
 158   // branch
 159   jcc(Assembler::noParity, L);
 160 }
 161 
 162 // 32bit can do a case table jump in one instruction but we no longer allow the base
 163 // to be installed in the Address class
 164 void MacroAssembler::jump(ArrayAddress entry) {
 165   jmp(as_Address(entry));
 166 }
 167 
 168 // Note: y_lo will be destroyed
 169 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 170   // Long compare for Java (semantics as described in JVM spec.)
 171   Label high, low, done;
 172 
 173   cmpl(x_hi, y_hi);
 174   jcc(Assembler::less, low);
 175   jcc(Assembler::greater, high);
 176   // x_hi is the return register
 177   xorl(x_hi, x_hi);
 178   cmpl(x_lo, y_lo);
 179   jcc(Assembler::below, low);
 180   jcc(Assembler::equal, done);
 181 
 182   bind(high);
 183   xorl(x_hi, x_hi);
 184   increment(x_hi);
 185   jmp(done);
 186 
 187   bind(low);
 188   xorl(x_hi, x_hi);
 189   decrementl(x_hi);
 190 
 191   bind(done);
 192 }
 193 
 194 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 195     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 196 }
 197 
 198 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 199   // leal(dst, as_Address(adr));
 200   // see note in movl as to why we must use a move
 201   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 202 }
 203 
 204 void MacroAssembler::leave() {
 205   mov(rsp, rbp);
 206   pop(rbp);
 207 }
 208 
 209 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 210   // Multiplication of two Java long values stored on the stack
 211   // as illustrated below. Result is in rdx:rax.
 212   //
 213   // rsp ---> [  ??  ] \               \
 214   //            ....    | y_rsp_offset  |
 215   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 216   //          [ y_hi ]                  | (in bytes)
 217   //            ....                    |
 218   //          [ x_lo ]                 /
 219   //          [ x_hi ]
 220   //            ....
 221   //
 222   // Basic idea: lo(result) = lo(x_lo * y_lo)
 223   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 224   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 225   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 226   Label quick;
 227   // load x_hi, y_hi and check if quick
 228   // multiplication is possible
 229   movl(rbx, x_hi);
 230   movl(rcx, y_hi);
 231   movl(rax, rbx);
 232   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 233   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 234   // do full multiplication
 235   // 1st step
 236   mull(y_lo);                                    // x_hi * y_lo
 237   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 238   // 2nd step
 239   movl(rax, x_lo);
 240   mull(rcx);                                     // x_lo * y_hi
 241   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 242   // 3rd step
 243   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 244   movl(rax, x_lo);
 245   mull(y_lo);                                    // x_lo * y_lo
 246   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 247 }
 248 
 249 void MacroAssembler::lneg(Register hi, Register lo) {
 250   negl(lo);
 251   adcl(hi, 0);
 252   negl(hi);
 253 }
 254 
 255 void MacroAssembler::lshl(Register hi, Register lo) {
 256   // Java shift left long support (semantics as described in JVM spec., p.305)
 257   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 258   // shift value is in rcx !
 259   assert(hi != rcx, "must not use rcx");
 260   assert(lo != rcx, "must not use rcx");
 261   const Register s = rcx;                        // shift count
 262   const int      n = BitsPerWord;
 263   Label L;
 264   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 265   cmpl(s, n);                                    // if (s < n)
 266   jcc(Assembler::less, L);                       // else (s >= n)
 267   movl(hi, lo);                                  // x := x << n
 268   xorl(lo, lo);
 269   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 270   bind(L);                                       // s (mod n) < n
 271   shldl(hi, lo);                                 // x := x << s
 272   shll(lo);
 273 }
 274 
 275 
 276 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 277   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 278   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 279   assert(hi != rcx, "must not use rcx");
 280   assert(lo != rcx, "must not use rcx");
 281   const Register s = rcx;                        // shift count
 282   const int      n = BitsPerWord;
 283   Label L;
 284   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 285   cmpl(s, n);                                    // if (s < n)
 286   jcc(Assembler::less, L);                       // else (s >= n)
 287   movl(lo, hi);                                  // x := x >> n
 288   if (sign_extension) sarl(hi, 31);
 289   else                xorl(hi, hi);
 290   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 291   bind(L);                                       // s (mod n) < n
 292   shrdl(lo, hi);                                 // x := x >> s
 293   if (sign_extension) sarl(hi);
 294   else                shrl(hi);
 295 }
 296 
 297 void MacroAssembler::movoop(Register dst, jobject obj) {
 298   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::movoop(Address dst, jobject obj) {
 302   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 306   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 307 }
 308 
 309 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 310   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 311 }
 312 
 313 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 314   // scratch register is not used,
 315   // it is defined to match parameters of 64-bit version of this method.
 316   if (src.is_lval()) {
 317     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 318   } else {
 319     movl(dst, as_Address(src));
 320   }
 321 }
 322 
 323 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 324   movl(as_Address(dst), src);
 325 }
 326 
 327 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 328   movl(dst, as_Address(src));
 329 }
 330 
 331 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 332 void MacroAssembler::movptr(Address dst, intptr_t src) {
 333   movl(dst, src);
 334 }
 335 
 336 
 337 void MacroAssembler::pop_callee_saved_registers() {
 338   pop(rcx);
 339   pop(rdx);
 340   pop(rdi);
 341   pop(rsi);
 342 }
 343 
 344 void MacroAssembler::pop_fTOS() {
 345   fld_d(Address(rsp, 0));
 346   addl(rsp, 2 * wordSize);
 347 }
 348 
 349 void MacroAssembler::push_callee_saved_registers() {
 350   push(rsi);
 351   push(rdi);
 352   push(rdx);
 353   push(rcx);
 354 }
 355 
 356 void MacroAssembler::push_fTOS() {
 357   subl(rsp, 2 * wordSize);
 358   fstp_d(Address(rsp, 0));
 359 }
 360 
 361 
 362 void MacroAssembler::pushoop(jobject obj) {
 363   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 364 }
 365 
 366 void MacroAssembler::pushklass(Metadata* obj) {
 367   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 368 }
 369 
 370 void MacroAssembler::pushptr(AddressLiteral src) {
 371   if (src.is_lval()) {
 372     push_literal32((int32_t)src.target(), src.rspec());
 373   } else {
 374     pushl(as_Address(src));
 375   }
 376 }
 377 
 378 void MacroAssembler::set_word_if_not_zero(Register dst) {
 379   xorl(dst, dst);
 380   set_byte_if_not_zero(dst);
 381 }
 382 
 383 static void pass_arg0(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg1(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 static void pass_arg2(MacroAssembler* masm, Register arg) {
 392   masm->push(arg);
 393 }
 394 
 395 static void pass_arg3(MacroAssembler* masm, Register arg) {
 396   masm->push(arg);
 397 }
 398 
 399 #ifndef PRODUCT
 400 extern "C" void findpc(intptr_t x);
 401 #endif
 402 
 403 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 404   // In order to get locks to work, we need to fake a in_VM state
 405   JavaThread* thread = JavaThread::current();
 406   JavaThreadState saved_state = thread->thread_state();
 407   thread->set_thread_state(_thread_in_vm);
 408   if (ShowMessageBoxOnError) {
 409     JavaThread* thread = JavaThread::current();
 410     JavaThreadState saved_state = thread->thread_state();
 411     thread->set_thread_state(_thread_in_vm);
 412     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 413       ttyLocker ttyl;
 414       BytecodeCounter::print();
 415     }
 416     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 417     // This is the value of eip which points to where verify_oop will return.
 418     if (os::message_box(msg, "Execution stopped, print registers?")) {
 419       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 420       BREAKPOINT;
 421     }
 422   } else {
 423     ttyLocker ttyl;
 424     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 425   }
 426   // Don't assert holding the ttyLock
 427     assert(false, "DEBUG MESSAGE: %s", msg);
 428   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 429 }
 430 
 431 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 432   ttyLocker ttyl;
 433   FlagSetting fs(Debugging, true);
 434   tty->print_cr("eip = 0x%08x", eip);
 435 #ifndef PRODUCT
 436   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 437     tty->cr();
 438     findpc(eip);
 439     tty->cr();
 440   }
 441 #endif
 442 #define PRINT_REG(rax) \
 443   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 444   PRINT_REG(rax);
 445   PRINT_REG(rbx);
 446   PRINT_REG(rcx);
 447   PRINT_REG(rdx);
 448   PRINT_REG(rdi);
 449   PRINT_REG(rsi);
 450   PRINT_REG(rbp);
 451   PRINT_REG(rsp);
 452 #undef PRINT_REG
 453   // Print some words near top of staack.
 454   int* dump_sp = (int*) rsp;
 455   for (int col1 = 0; col1 < 8; col1++) {
 456     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 457     os::print_location(tty, *dump_sp++);
 458   }
 459   for (int row = 0; row < 16; row++) {
 460     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 461     for (int col = 0; col < 8; col++) {
 462       tty->print(" 0x%08x", *dump_sp++);
 463     }
 464     tty->cr();
 465   }
 466   // Print some instructions around pc:
 467   Disassembler::decode((address)eip-64, (address)eip);
 468   tty->print_cr("--------");
 469   Disassembler::decode((address)eip, (address)eip+32);
 470 }
 471 
 472 void MacroAssembler::stop(const char* msg) {
 473   ExternalAddress message((address)msg);
 474   // push address of message
 475   pushptr(message.addr());
 476   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 477   pusha();                                            // push registers
 478   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 479   hlt();
 480 }
 481 
 482 void MacroAssembler::warn(const char* msg) {
 483   push_CPU_state();
 484 
 485   ExternalAddress message((address) msg);
 486   // push address of message
 487   pushptr(message.addr());
 488 
 489   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 490   addl(rsp, wordSize);       // discard argument
 491   pop_CPU_state();
 492 }
 493 
 494 void MacroAssembler::print_state() {
 495   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 496   pusha();                                            // push registers
 497 
 498   push_CPU_state();
 499   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 500   pop_CPU_state();
 501 
 502   popa();
 503   addl(rsp, wordSize);
 504 }
 505 
 506 #else // _LP64
 507 
 508 // 64 bit versions
 509 
 510 Address MacroAssembler::as_Address(AddressLiteral adr) {
 511   // amd64 always does this as a pc-rel
 512   // we can be absolute or disp based on the instruction type
 513   // jmp/call are displacements others are absolute
 514   assert(!adr.is_lval(), "must be rval");
 515   assert(reachable(adr), "must be");
 516   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 517 
 518 }
 519 
 520 Address MacroAssembler::as_Address(ArrayAddress adr) {
 521   AddressLiteral base = adr.base();
 522   lea(rscratch1, base);
 523   Address index = adr.index();
 524   assert(index._disp == 0, "must not have disp"); // maybe it can?
 525   Address array(rscratch1, index._index, index._scale, index._disp);
 526   return array;
 527 }
 528 
 529 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 530   Label L, E;
 531 
 532 #ifdef _WIN64
 533   // Windows always allocates space for it's register args
 534   assert(num_args <= 4, "only register arguments supported");
 535   subq(rsp,  frame::arg_reg_save_area_bytes);
 536 #endif
 537 
 538   // Align stack if necessary
 539   testl(rsp, 15);
 540   jcc(Assembler::zero, L);
 541 
 542   subq(rsp, 8);
 543   {
 544     call(RuntimeAddress(entry_point));
 545   }
 546   addq(rsp, 8);
 547   jmp(E);
 548 
 549   bind(L);
 550   {
 551     call(RuntimeAddress(entry_point));
 552   }
 553 
 554   bind(E);
 555 
 556 #ifdef _WIN64
 557   // restore stack pointer
 558   addq(rsp, frame::arg_reg_save_area_bytes);
 559 #endif
 560 
 561 }
 562 
 563 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 564   assert(!src2.is_lval(), "should use cmpptr");
 565 
 566   if (reachable(src2)) {
 567     cmpq(src1, as_Address(src2));
 568   } else {
 569     lea(rscratch1, src2);
 570     Assembler::cmpq(src1, Address(rscratch1, 0));
 571   }
 572 }
 573 
 574 int MacroAssembler::corrected_idivq(Register reg) {
 575   // Full implementation of Java ldiv and lrem; checks for special
 576   // case as described in JVM spec., p.243 & p.271.  The function
 577   // returns the (pc) offset of the idivl instruction - may be needed
 578   // for implicit exceptions.
 579   //
 580   //         normal case                           special case
 581   //
 582   // input : rax: dividend                         min_long
 583   //         reg: divisor   (may not be eax/edx)   -1
 584   //
 585   // output: rax: quotient  (= rax idiv reg)       min_long
 586   //         rdx: remainder (= rax irem reg)       0
 587   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 588   static const int64_t min_long = 0x8000000000000000;
 589   Label normal_case, special_case;
 590 
 591   // check for special case
 592   cmp64(rax, ExternalAddress((address) &min_long));
 593   jcc(Assembler::notEqual, normal_case);
 594   xorl(rdx, rdx); // prepare rdx for possible special case (where
 595                   // remainder = 0)
 596   cmpq(reg, -1);
 597   jcc(Assembler::equal, special_case);
 598 
 599   // handle normal case
 600   bind(normal_case);
 601   cdqq();
 602   int idivq_offset = offset();
 603   idivq(reg);
 604 
 605   // normal and special case exit
 606   bind(special_case);
 607 
 608   return idivq_offset;
 609 }
 610 
 611 void MacroAssembler::decrementq(Register reg, int value) {
 612   if (value == min_jint) { subq(reg, value); return; }
 613   if (value <  0) { incrementq(reg, -value); return; }
 614   if (value == 0) {                        ; return; }
 615   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 616   /* else */      { subq(reg, value)       ; return; }
 617 }
 618 
 619 void MacroAssembler::decrementq(Address dst, int value) {
 620   if (value == min_jint) { subq(dst, value); return; }
 621   if (value <  0) { incrementq(dst, -value); return; }
 622   if (value == 0) {                        ; return; }
 623   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 624   /* else */      { subq(dst, value)       ; return; }
 625 }
 626 
 627 void MacroAssembler::incrementq(AddressLiteral dst) {
 628   if (reachable(dst)) {
 629     incrementq(as_Address(dst));
 630   } else {
 631     lea(rscratch1, dst);
 632     incrementq(Address(rscratch1, 0));
 633   }
 634 }
 635 
 636 void MacroAssembler::incrementq(Register reg, int value) {
 637   if (value == min_jint) { addq(reg, value); return; }
 638   if (value <  0) { decrementq(reg, -value); return; }
 639   if (value == 0) {                        ; return; }
 640   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 641   /* else */      { addq(reg, value)       ; return; }
 642 }
 643 
 644 void MacroAssembler::incrementq(Address dst, int value) {
 645   if (value == min_jint) { addq(dst, value); return; }
 646   if (value <  0) { decrementq(dst, -value); return; }
 647   if (value == 0) {                        ; return; }
 648   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 649   /* else */      { addq(dst, value)       ; return; }
 650 }
 651 
 652 // 32bit can do a case table jump in one instruction but we no longer allow the base
 653 // to be installed in the Address class
 654 void MacroAssembler::jump(ArrayAddress entry) {
 655   lea(rscratch1, entry.base());
 656   Address dispatch = entry.index();
 657   assert(dispatch._base == noreg, "must be");
 658   dispatch._base = rscratch1;
 659   jmp(dispatch);
 660 }
 661 
 662 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 663   ShouldNotReachHere(); // 64bit doesn't use two regs
 664   cmpq(x_lo, y_lo);
 665 }
 666 
 667 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 668     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 669 }
 670 
 671 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 672   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 673   movptr(dst, rscratch1);
 674 }
 675 
 676 void MacroAssembler::leave() {
 677   // %%% is this really better? Why not on 32bit too?
 678   emit_int8((unsigned char)0xC9); // LEAVE
 679 }
 680 
 681 void MacroAssembler::lneg(Register hi, Register lo) {
 682   ShouldNotReachHere(); // 64bit doesn't use two regs
 683   negq(lo);
 684 }
 685 
 686 void MacroAssembler::movoop(Register dst, jobject obj) {
 687   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 688 }
 689 
 690 void MacroAssembler::movoop(Address dst, jobject obj) {
 691   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 692   movq(dst, rscratch1);
 693 }
 694 
 695 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 696   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 697 }
 698 
 699 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 700   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 701   movq(dst, rscratch1);
 702 }
 703 
 704 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 705   if (src.is_lval()) {
 706     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 707   } else {
 708     if (reachable(src)) {
 709       movq(dst, as_Address(src));
 710     } else {
 711       lea(scratch, src);
 712       movq(dst, Address(scratch, 0));
 713     }
 714   }
 715 }
 716 
 717 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 718   movq(as_Address(dst), src);
 719 }
 720 
 721 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 722   movq(dst, as_Address(src));
 723 }
 724 
 725 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 726 void MacroAssembler::movptr(Address dst, intptr_t src) {
 727   mov64(rscratch1, src);
 728   movq(dst, rscratch1);
 729 }
 730 
 731 // These are mostly for initializing NULL
 732 void MacroAssembler::movptr(Address dst, int32_t src) {
 733   movslq(dst, src);
 734 }
 735 
 736 void MacroAssembler::movptr(Register dst, int32_t src) {
 737   mov64(dst, (intptr_t)src);
 738 }
 739 
 740 void MacroAssembler::pushoop(jobject obj) {
 741   movoop(rscratch1, obj);
 742   push(rscratch1);
 743 }
 744 
 745 void MacroAssembler::pushklass(Metadata* obj) {
 746   mov_metadata(rscratch1, obj);
 747   push(rscratch1);
 748 }
 749 
 750 void MacroAssembler::pushptr(AddressLiteral src) {
 751   lea(rscratch1, src);
 752   if (src.is_lval()) {
 753     push(rscratch1);
 754   } else {
 755     pushq(Address(rscratch1, 0));
 756   }
 757 }
 758 
 759 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 760   // we must set sp to zero to clear frame
 761   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 762   // must clear fp, so that compiled frames are not confused; it is
 763   // possible that we need it only for debugging
 764   if (clear_fp) {
 765     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 766   }
 767 
 768   // Always clear the pc because it could have been set by make_walkable()
 769   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 770   vzeroupper();
 771 }
 772 
 773 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 774                                          Register last_java_fp,
 775                                          address  last_java_pc) {
 776   vzeroupper();
 777   // determine last_java_sp register
 778   if (!last_java_sp->is_valid()) {
 779     last_java_sp = rsp;
 780   }
 781 
 782   // last_java_fp is optional
 783   if (last_java_fp->is_valid()) {
 784     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 785            last_java_fp);
 786   }
 787 
 788   // last_java_pc is optional
 789   if (last_java_pc != NULL) {
 790     Address java_pc(r15_thread,
 791                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 792     lea(rscratch1, InternalAddress(last_java_pc));
 793     movptr(java_pc, rscratch1);
 794   }
 795 
 796   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 797 }
 798 
 799 static void pass_arg0(MacroAssembler* masm, Register arg) {
 800   if (c_rarg0 != arg ) {
 801     masm->mov(c_rarg0, arg);
 802   }
 803 }
 804 
 805 static void pass_arg1(MacroAssembler* masm, Register arg) {
 806   if (c_rarg1 != arg ) {
 807     masm->mov(c_rarg1, arg);
 808   }
 809 }
 810 
 811 static void pass_arg2(MacroAssembler* masm, Register arg) {
 812   if (c_rarg2 != arg ) {
 813     masm->mov(c_rarg2, arg);
 814   }
 815 }
 816 
 817 static void pass_arg3(MacroAssembler* masm, Register arg) {
 818   if (c_rarg3 != arg ) {
 819     masm->mov(c_rarg3, arg);
 820   }
 821 }
 822 
 823 void MacroAssembler::stop(const char* msg) {
 824   address rip = pc();
 825   pusha(); // get regs on stack
 826   lea(c_rarg0, ExternalAddress((address) msg));
 827   lea(c_rarg1, InternalAddress(rip));
 828   movq(c_rarg2, rsp); // pass pointer to regs array
 829   andq(rsp, -16); // align stack as required by ABI
 830   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 831   hlt();
 832 }
 833 
 834 void MacroAssembler::warn(const char* msg) {
 835   push(rbp);
 836   movq(rbp, rsp);
 837   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 838   push_CPU_state();   // keeps alignment at 16 bytes
 839   lea(c_rarg0, ExternalAddress((address) msg));
 840   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 841   call(rax);
 842   pop_CPU_state();
 843   mov(rsp, rbp);
 844   pop(rbp);
 845 }
 846 
 847 void MacroAssembler::print_state() {
 848   address rip = pc();
 849   pusha();            // get regs on stack
 850   push(rbp);
 851   movq(rbp, rsp);
 852   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 853   push_CPU_state();   // keeps alignment at 16 bytes
 854 
 855   lea(c_rarg0, InternalAddress(rip));
 856   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 857   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 858 
 859   pop_CPU_state();
 860   mov(rsp, rbp);
 861   pop(rbp);
 862   popa();
 863 }
 864 
 865 #ifndef PRODUCT
 866 extern "C" void findpc(intptr_t x);
 867 #endif
 868 
 869 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 870   // In order to get locks to work, we need to fake a in_VM state
 871   if (ShowMessageBoxOnError) {
 872     JavaThread* thread = JavaThread::current();
 873     JavaThreadState saved_state = thread->thread_state();
 874     thread->set_thread_state(_thread_in_vm);
 875 #ifndef PRODUCT
 876     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 877       ttyLocker ttyl;
 878       BytecodeCounter::print();
 879     }
 880 #endif
 881     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 882     // XXX correct this offset for amd64
 883     // This is the value of eip which points to where verify_oop will return.
 884     if (os::message_box(msg, "Execution stopped, print registers?")) {
 885       print_state64(pc, regs);
 886       BREAKPOINT;
 887       assert(false, "start up GDB");
 888     }
 889     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 890   } else {
 891     ttyLocker ttyl;
 892     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 893                     msg);
 894     assert(false, "DEBUG MESSAGE: %s", msg);
 895   }
 896 }
 897 
 898 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 899   ttyLocker ttyl;
 900   FlagSetting fs(Debugging, true);
 901   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 902 #ifndef PRODUCT
 903   tty->cr();
 904   findpc(pc);
 905   tty->cr();
 906 #endif
 907 #define PRINT_REG(rax, value) \
 908   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 909   PRINT_REG(rax, regs[15]);
 910   PRINT_REG(rbx, regs[12]);
 911   PRINT_REG(rcx, regs[14]);
 912   PRINT_REG(rdx, regs[13]);
 913   PRINT_REG(rdi, regs[8]);
 914   PRINT_REG(rsi, regs[9]);
 915   PRINT_REG(rbp, regs[10]);
 916   PRINT_REG(rsp, regs[11]);
 917   PRINT_REG(r8 , regs[7]);
 918   PRINT_REG(r9 , regs[6]);
 919   PRINT_REG(r10, regs[5]);
 920   PRINT_REG(r11, regs[4]);
 921   PRINT_REG(r12, regs[3]);
 922   PRINT_REG(r13, regs[2]);
 923   PRINT_REG(r14, regs[1]);
 924   PRINT_REG(r15, regs[0]);
 925 #undef PRINT_REG
 926   // Print some words near top of staack.
 927   int64_t* rsp = (int64_t*) regs[11];
 928   int64_t* dump_sp = rsp;
 929   for (int col1 = 0; col1 < 8; col1++) {
 930     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 931     os::print_location(tty, *dump_sp++);
 932   }
 933   for (int row = 0; row < 25; row++) {
 934     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 935     for (int col = 0; col < 4; col++) {
 936       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 937     }
 938     tty->cr();
 939   }
 940   // Print some instructions around pc:
 941   Disassembler::decode((address)pc-64, (address)pc);
 942   tty->print_cr("--------");
 943   Disassembler::decode((address)pc, (address)pc+32);
 944 }
 945 
 946 #endif // _LP64
 947 
 948 // Now versions that are common to 32/64 bit
 949 
 950 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 951   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 952 }
 953 
 954 void MacroAssembler::addptr(Register dst, Register src) {
 955   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 956 }
 957 
 958 void MacroAssembler::addptr(Address dst, Register src) {
 959   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 960 }
 961 
 962 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 963   if (reachable(src)) {
 964     Assembler::addsd(dst, as_Address(src));
 965   } else {
 966     lea(rscratch1, src);
 967     Assembler::addsd(dst, Address(rscratch1, 0));
 968   }
 969 }
 970 
 971 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 972   if (reachable(src)) {
 973     addss(dst, as_Address(src));
 974   } else {
 975     lea(rscratch1, src);
 976     addss(dst, Address(rscratch1, 0));
 977   }
 978 }
 979 
 980 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 981   if (reachable(src)) {
 982     Assembler::addpd(dst, as_Address(src));
 983   } else {
 984     lea(rscratch1, src);
 985     Assembler::addpd(dst, Address(rscratch1, 0));
 986   }
 987 }
 988 
 989 void MacroAssembler::align(int modulus) {
 990   align(modulus, offset());
 991 }
 992 
 993 void MacroAssembler::align(int modulus, int target) {
 994   if (target % modulus != 0) {
 995     nop(modulus - (target % modulus));
 996   }
 997 }
 998 
 999 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1000   // Used in sign-masking with aligned address.
1001   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1002   if (reachable(src)) {
1003     Assembler::andpd(dst, as_Address(src));
1004   } else {
1005     lea(rscratch1, src);
1006     Assembler::andpd(dst, Address(rscratch1, 0));
1007   }
1008 }
1009 
1010 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1011   // Used in sign-masking with aligned address.
1012   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1013   if (reachable(src)) {
1014     Assembler::andps(dst, as_Address(src));
1015   } else {
1016     lea(rscratch1, src);
1017     Assembler::andps(dst, Address(rscratch1, 0));
1018   }
1019 }
1020 
1021 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1022   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1023 }
1024 
1025 void MacroAssembler::atomic_incl(Address counter_addr) {
1026   if (os::is_MP())
1027     lock();
1028   incrementl(counter_addr);
1029 }
1030 
1031 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1032   if (reachable(counter_addr)) {
1033     atomic_incl(as_Address(counter_addr));
1034   } else {
1035     lea(scr, counter_addr);
1036     atomic_incl(Address(scr, 0));
1037   }
1038 }
1039 
1040 #ifdef _LP64
1041 void MacroAssembler::atomic_incq(Address counter_addr) {
1042   if (os::is_MP())
1043     lock();
1044   incrementq(counter_addr);
1045 }
1046 
1047 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1048   if (reachable(counter_addr)) {
1049     atomic_incq(as_Address(counter_addr));
1050   } else {
1051     lea(scr, counter_addr);
1052     atomic_incq(Address(scr, 0));
1053   }
1054 }
1055 #endif
1056 
1057 // Writes to stack successive pages until offset reached to check for
1058 // stack overflow + shadow pages.  This clobbers tmp.
1059 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1060   movptr(tmp, rsp);
1061   // Bang stack for total size given plus shadow page size.
1062   // Bang one page at a time because large size can bang beyond yellow and
1063   // red zones.
1064   Label loop;
1065   bind(loop);
1066   movl(Address(tmp, (-os::vm_page_size())), size );
1067   subptr(tmp, os::vm_page_size());
1068   subl(size, os::vm_page_size());
1069   jcc(Assembler::greater, loop);
1070 
1071   // Bang down shadow pages too.
1072   // At this point, (tmp-0) is the last address touched, so don't
1073   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1074   // was post-decremented.)  Skip this address by starting at i=1, and
1075   // touch a few more pages below.  N.B.  It is important to touch all
1076   // the way down including all pages in the shadow zone.
1077   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1078     // this could be any sized move but this is can be a debugging crumb
1079     // so the bigger the better.
1080     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1081   }
1082 }
1083 
1084 void MacroAssembler::reserved_stack_check() {
1085     // testing if reserved zone needs to be enabled
1086     Label no_reserved_zone_enabling;
1087     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1088     NOT_LP64(get_thread(rsi);)
1089 
1090     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1091     jcc(Assembler::below, no_reserved_zone_enabling);
1092 
1093     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1094     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1095     should_not_reach_here();
1096 
1097     bind(no_reserved_zone_enabling);
1098 }
1099 
1100 int MacroAssembler::biased_locking_enter(Register lock_reg,
1101                                          Register obj_reg,
1102                                          Register swap_reg,
1103                                          Register tmp_reg,
1104                                          bool swap_reg_contains_mark,
1105                                          Label& done,
1106                                          Label* slow_case,
1107                                          BiasedLockingCounters* counters) {
1108   assert(UseBiasedLocking, "why call this otherwise?");
1109   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1110   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1111   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1112   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1113   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1114   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1115 
1116   if (PrintBiasedLockingStatistics && counters == NULL) {
1117     counters = BiasedLocking::counters();
1118   }
1119   // Biased locking
1120   // See whether the lock is currently biased toward our thread and
1121   // whether the epoch is still valid
1122   // Note that the runtime guarantees sufficient alignment of JavaThread
1123   // pointers to allow age to be placed into low bits
1124   // First check to see whether biasing is even enabled for this object
1125   Label cas_label;
1126   int null_check_offset = -1;
1127   if (!swap_reg_contains_mark) {
1128     null_check_offset = offset();
1129     movptr(swap_reg, mark_addr);
1130   }
1131   movptr(tmp_reg, swap_reg);
1132   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1133   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1134   jcc(Assembler::notEqual, cas_label);
1135   // The bias pattern is present in the object's header. Need to check
1136   // whether the bias owner and the epoch are both still current.
1137 #ifndef _LP64
1138   // Note that because there is no current thread register on x86_32 we
1139   // need to store off the mark word we read out of the object to
1140   // avoid reloading it and needing to recheck invariants below. This
1141   // store is unfortunate but it makes the overall code shorter and
1142   // simpler.
1143   movptr(saved_mark_addr, swap_reg);
1144 #endif
1145   if (swap_reg_contains_mark) {
1146     null_check_offset = offset();
1147   }
1148   load_prototype_header(tmp_reg, obj_reg);
1149 #ifdef _LP64
1150   orptr(tmp_reg, r15_thread);
1151   xorptr(tmp_reg, swap_reg);
1152   Register header_reg = tmp_reg;
1153 #else
1154   xorptr(tmp_reg, swap_reg);
1155   get_thread(swap_reg);
1156   xorptr(swap_reg, tmp_reg);
1157   Register header_reg = swap_reg;
1158 #endif
1159   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1160   if (counters != NULL) {
1161     cond_inc32(Assembler::zero,
1162                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1163   }
1164   jcc(Assembler::equal, done);
1165 
1166   Label try_revoke_bias;
1167   Label try_rebias;
1168 
1169   // At this point we know that the header has the bias pattern and
1170   // that we are not the bias owner in the current epoch. We need to
1171   // figure out more details about the state of the header in order to
1172   // know what operations can be legally performed on the object's
1173   // header.
1174 
1175   // If the low three bits in the xor result aren't clear, that means
1176   // the prototype header is no longer biased and we have to revoke
1177   // the bias on this object.
1178   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1179   jccb(Assembler::notZero, try_revoke_bias);
1180 
1181   // Biasing is still enabled for this data type. See whether the
1182   // epoch of the current bias is still valid, meaning that the epoch
1183   // bits of the mark word are equal to the epoch bits of the
1184   // prototype header. (Note that the prototype header's epoch bits
1185   // only change at a safepoint.) If not, attempt to rebias the object
1186   // toward the current thread. Note that we must be absolutely sure
1187   // that the current epoch is invalid in order to do this because
1188   // otherwise the manipulations it performs on the mark word are
1189   // illegal.
1190   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1191   jccb(Assembler::notZero, try_rebias);
1192 
1193   // The epoch of the current bias is still valid but we know nothing
1194   // about the owner; it might be set or it might be clear. Try to
1195   // acquire the bias of the object using an atomic operation. If this
1196   // fails we will go in to the runtime to revoke the object's bias.
1197   // Note that we first construct the presumed unbiased header so we
1198   // don't accidentally blow away another thread's valid bias.
1199   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1200   andptr(swap_reg,
1201          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1202 #ifdef _LP64
1203   movptr(tmp_reg, swap_reg);
1204   orptr(tmp_reg, r15_thread);
1205 #else
1206   get_thread(tmp_reg);
1207   orptr(tmp_reg, swap_reg);
1208 #endif
1209   if (os::is_MP()) {
1210     lock();
1211   }
1212   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1213   // If the biasing toward our thread failed, this means that
1214   // another thread succeeded in biasing it toward itself and we
1215   // need to revoke that bias. The revocation will occur in the
1216   // interpreter runtime in the slow case.
1217   if (counters != NULL) {
1218     cond_inc32(Assembler::zero,
1219                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1220   }
1221   if (slow_case != NULL) {
1222     jcc(Assembler::notZero, *slow_case);
1223   }
1224   jmp(done);
1225 
1226   bind(try_rebias);
1227   // At this point we know the epoch has expired, meaning that the
1228   // current "bias owner", if any, is actually invalid. Under these
1229   // circumstances _only_, we are allowed to use the current header's
1230   // value as the comparison value when doing the cas to acquire the
1231   // bias in the current epoch. In other words, we allow transfer of
1232   // the bias from one thread to another directly in this situation.
1233   //
1234   // FIXME: due to a lack of registers we currently blow away the age
1235   // bits in this situation. Should attempt to preserve them.
1236   load_prototype_header(tmp_reg, obj_reg);
1237 #ifdef _LP64
1238   orptr(tmp_reg, r15_thread);
1239 #else
1240   get_thread(swap_reg);
1241   orptr(tmp_reg, swap_reg);
1242   movptr(swap_reg, saved_mark_addr);
1243 #endif
1244   if (os::is_MP()) {
1245     lock();
1246   }
1247   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1248   // If the biasing toward our thread failed, then another thread
1249   // succeeded in biasing it toward itself and we need to revoke that
1250   // bias. The revocation will occur in the runtime in the slow case.
1251   if (counters != NULL) {
1252     cond_inc32(Assembler::zero,
1253                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1254   }
1255   if (slow_case != NULL) {
1256     jcc(Assembler::notZero, *slow_case);
1257   }
1258   jmp(done);
1259 
1260   bind(try_revoke_bias);
1261   // The prototype mark in the klass doesn't have the bias bit set any
1262   // more, indicating that objects of this data type are not supposed
1263   // to be biased any more. We are going to try to reset the mark of
1264   // this object to the prototype value and fall through to the
1265   // CAS-based locking scheme. Note that if our CAS fails, it means
1266   // that another thread raced us for the privilege of revoking the
1267   // bias of this particular object, so it's okay to continue in the
1268   // normal locking code.
1269   //
1270   // FIXME: due to a lack of registers we currently blow away the age
1271   // bits in this situation. Should attempt to preserve them.
1272   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1273   load_prototype_header(tmp_reg, obj_reg);
1274   if (os::is_MP()) {
1275     lock();
1276   }
1277   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1278   // Fall through to the normal CAS-based lock, because no matter what
1279   // the result of the above CAS, some thread must have succeeded in
1280   // removing the bias bit from the object's header.
1281   if (counters != NULL) {
1282     cond_inc32(Assembler::zero,
1283                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1284   }
1285 
1286   bind(cas_label);
1287 
1288   return null_check_offset;
1289 }
1290 
1291 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1292   assert(UseBiasedLocking, "why call this otherwise?");
1293 
1294   // Check for biased locking unlock case, which is a no-op
1295   // Note: we do not have to check the thread ID for two reasons.
1296   // First, the interpreter checks for IllegalMonitorStateException at
1297   // a higher level. Second, if the bias was revoked while we held the
1298   // lock, the object could not be rebiased toward another thread, so
1299   // the bias bit would be clear.
1300   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1301   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1302   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1303   jcc(Assembler::equal, done);
1304 }
1305 
1306 #ifdef COMPILER2
1307 
1308 #if INCLUDE_RTM_OPT
1309 
1310 // Update rtm_counters based on abort status
1311 // input: abort_status
1312 //        rtm_counters (RTMLockingCounters*)
1313 // flags are killed
1314 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1315 
1316   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1317   if (PrintPreciseRTMLockingStatistics) {
1318     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1319       Label check_abort;
1320       testl(abort_status, (1<<i));
1321       jccb(Assembler::equal, check_abort);
1322       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1323       bind(check_abort);
1324     }
1325   }
1326 }
1327 
1328 // Branch if (random & (count-1) != 0), count is 2^n
1329 // tmp, scr and flags are killed
1330 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1331   assert(tmp == rax, "");
1332   assert(scr == rdx, "");
1333   rdtsc(); // modifies EDX:EAX
1334   andptr(tmp, count-1);
1335   jccb(Assembler::notZero, brLabel);
1336 }
1337 
1338 // Perform abort ratio calculation, set no_rtm bit if high ratio
1339 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1340 // tmpReg, rtm_counters_Reg and flags are killed
1341 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1342                                                  Register rtm_counters_Reg,
1343                                                  RTMLockingCounters* rtm_counters,
1344                                                  Metadata* method_data) {
1345   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1346 
1347   if (RTMLockingCalculationDelay > 0) {
1348     // Delay calculation
1349     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1350     testptr(tmpReg, tmpReg);
1351     jccb(Assembler::equal, L_done);
1352   }
1353   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1354   //   Aborted transactions = abort_count * 100
1355   //   All transactions = total_count *  RTMTotalCountIncrRate
1356   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1357 
1358   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1359   cmpptr(tmpReg, RTMAbortThreshold);
1360   jccb(Assembler::below, L_check_always_rtm2);
1361   imulptr(tmpReg, tmpReg, 100);
1362 
1363   Register scrReg = rtm_counters_Reg;
1364   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1365   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1366   imulptr(scrReg, scrReg, RTMAbortRatio);
1367   cmpptr(tmpReg, scrReg);
1368   jccb(Assembler::below, L_check_always_rtm1);
1369   if (method_data != NULL) {
1370     // set rtm_state to "no rtm" in MDO
1371     mov_metadata(tmpReg, method_data);
1372     if (os::is_MP()) {
1373       lock();
1374     }
1375     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1376   }
1377   jmpb(L_done);
1378   bind(L_check_always_rtm1);
1379   // Reload RTMLockingCounters* address
1380   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1381   bind(L_check_always_rtm2);
1382   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1383   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1384   jccb(Assembler::below, L_done);
1385   if (method_data != NULL) {
1386     // set rtm_state to "always rtm" in MDO
1387     mov_metadata(tmpReg, method_data);
1388     if (os::is_MP()) {
1389       lock();
1390     }
1391     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1392   }
1393   bind(L_done);
1394 }
1395 
1396 // Update counters and perform abort ratio calculation
1397 // input:  abort_status_Reg
1398 // rtm_counters_Reg, flags are killed
1399 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1400                                    Register rtm_counters_Reg,
1401                                    RTMLockingCounters* rtm_counters,
1402                                    Metadata* method_data,
1403                                    bool profile_rtm) {
1404 
1405   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1406   // update rtm counters based on rax value at abort
1407   // reads abort_status_Reg, updates flags
1408   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1409   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1410   if (profile_rtm) {
1411     // Save abort status because abort_status_Reg is used by following code.
1412     if (RTMRetryCount > 0) {
1413       push(abort_status_Reg);
1414     }
1415     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1416     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1417     // restore abort status
1418     if (RTMRetryCount > 0) {
1419       pop(abort_status_Reg);
1420     }
1421   }
1422 }
1423 
1424 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1425 // inputs: retry_count_Reg
1426 //       : abort_status_Reg
1427 // output: retry_count_Reg decremented by 1
1428 // flags are killed
1429 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1430   Label doneRetry;
1431   assert(abort_status_Reg == rax, "");
1432   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1433   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1434   // if reason is in 0x6 and retry count != 0 then retry
1435   andptr(abort_status_Reg, 0x6);
1436   jccb(Assembler::zero, doneRetry);
1437   testl(retry_count_Reg, retry_count_Reg);
1438   jccb(Assembler::zero, doneRetry);
1439   pause();
1440   decrementl(retry_count_Reg);
1441   jmp(retryLabel);
1442   bind(doneRetry);
1443 }
1444 
1445 // Spin and retry if lock is busy,
1446 // inputs: box_Reg (monitor address)
1447 //       : retry_count_Reg
1448 // output: retry_count_Reg decremented by 1
1449 //       : clear z flag if retry count exceeded
1450 // tmp_Reg, scr_Reg, flags are killed
1451 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1452                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1453   Label SpinLoop, SpinExit, doneRetry;
1454   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1455 
1456   testl(retry_count_Reg, retry_count_Reg);
1457   jccb(Assembler::zero, doneRetry);
1458   decrementl(retry_count_Reg);
1459   movptr(scr_Reg, RTMSpinLoopCount);
1460 
1461   bind(SpinLoop);
1462   pause();
1463   decrementl(scr_Reg);
1464   jccb(Assembler::lessEqual, SpinExit);
1465   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1466   testptr(tmp_Reg, tmp_Reg);
1467   jccb(Assembler::notZero, SpinLoop);
1468 
1469   bind(SpinExit);
1470   jmp(retryLabel);
1471   bind(doneRetry);
1472   incrementl(retry_count_Reg); // clear z flag
1473 }
1474 
1475 // Use RTM for normal stack locks
1476 // Input: objReg (object to lock)
1477 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1478                                        Register retry_on_abort_count_Reg,
1479                                        RTMLockingCounters* stack_rtm_counters,
1480                                        Metadata* method_data, bool profile_rtm,
1481                                        Label& DONE_LABEL, Label& IsInflated) {
1482   assert(UseRTMForStackLocks, "why call this otherwise?");
1483   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1484   assert(tmpReg == rax, "");
1485   assert(scrReg == rdx, "");
1486   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1487 
1488   if (RTMRetryCount > 0) {
1489     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1490     bind(L_rtm_retry);
1491   }
1492   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1493   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1494   jcc(Assembler::notZero, IsInflated);
1495 
1496   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1497     Label L_noincrement;
1498     if (RTMTotalCountIncrRate > 1) {
1499       // tmpReg, scrReg and flags are killed
1500       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1501     }
1502     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1503     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1504     bind(L_noincrement);
1505   }
1506   xbegin(L_on_abort);
1507   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1508   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1509   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1510   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1511 
1512   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1513   if (UseRTMXendForLockBusy) {
1514     xend();
1515     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1516     jmp(L_decrement_retry);
1517   }
1518   else {
1519     xabort(0);
1520   }
1521   bind(L_on_abort);
1522   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1523     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1524   }
1525   bind(L_decrement_retry);
1526   if (RTMRetryCount > 0) {
1527     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1528     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1529   }
1530 }
1531 
1532 // Use RTM for inflating locks
1533 // inputs: objReg (object to lock)
1534 //         boxReg (on-stack box address (displaced header location) - KILLED)
1535 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1536 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1537                                           Register scrReg, Register retry_on_busy_count_Reg,
1538                                           Register retry_on_abort_count_Reg,
1539                                           RTMLockingCounters* rtm_counters,
1540                                           Metadata* method_data, bool profile_rtm,
1541                                           Label& DONE_LABEL) {
1542   assert(UseRTMLocking, "why call this otherwise?");
1543   assert(tmpReg == rax, "");
1544   assert(scrReg == rdx, "");
1545   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1546   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1547 
1548   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1549   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1550   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1551 
1552   if (RTMRetryCount > 0) {
1553     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1554     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1555     bind(L_rtm_retry);
1556   }
1557   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1558     Label L_noincrement;
1559     if (RTMTotalCountIncrRate > 1) {
1560       // tmpReg, scrReg and flags are killed
1561       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1562     }
1563     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1564     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1565     bind(L_noincrement);
1566   }
1567   xbegin(L_on_abort);
1568   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1569   movptr(tmpReg, Address(tmpReg, owner_offset));
1570   testptr(tmpReg, tmpReg);
1571   jcc(Assembler::zero, DONE_LABEL);
1572   if (UseRTMXendForLockBusy) {
1573     xend();
1574     jmp(L_decrement_retry);
1575   }
1576   else {
1577     xabort(0);
1578   }
1579   bind(L_on_abort);
1580   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1581   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1582     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1583   }
1584   if (RTMRetryCount > 0) {
1585     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1586     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1587   }
1588 
1589   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1590   testptr(tmpReg, tmpReg) ;
1591   jccb(Assembler::notZero, L_decrement_retry) ;
1592 
1593   // Appears unlocked - try to swing _owner from null to non-null.
1594   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1595 #ifdef _LP64
1596   Register threadReg = r15_thread;
1597 #else
1598   get_thread(scrReg);
1599   Register threadReg = scrReg;
1600 #endif
1601   if (os::is_MP()) {
1602     lock();
1603   }
1604   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1605 
1606   if (RTMRetryCount > 0) {
1607     // success done else retry
1608     jccb(Assembler::equal, DONE_LABEL) ;
1609     bind(L_decrement_retry);
1610     // Spin and retry if lock is busy.
1611     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1612   }
1613   else {
1614     bind(L_decrement_retry);
1615   }
1616 }
1617 
1618 #endif //  INCLUDE_RTM_OPT
1619 
1620 // Fast_Lock and Fast_Unlock used by C2
1621 
1622 // Because the transitions from emitted code to the runtime
1623 // monitorenter/exit helper stubs are so slow it's critical that
1624 // we inline both the stack-locking fast-path and the inflated fast path.
1625 //
1626 // See also: cmpFastLock and cmpFastUnlock.
1627 //
1628 // What follows is a specialized inline transliteration of the code
1629 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1630 // another option would be to emit TrySlowEnter and TrySlowExit methods
1631 // at startup-time.  These methods would accept arguments as
1632 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1633 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1634 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1635 // In practice, however, the # of lock sites is bounded and is usually small.
1636 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1637 // if the processor uses simple bimodal branch predictors keyed by EIP
1638 // Since the helper routines would be called from multiple synchronization
1639 // sites.
1640 //
1641 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1642 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1643 // to those specialized methods.  That'd give us a mostly platform-independent
1644 // implementation that the JITs could optimize and inline at their pleasure.
1645 // Done correctly, the only time we'd need to cross to native could would be
1646 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1647 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1648 // (b) explicit barriers or fence operations.
1649 //
1650 // TODO:
1651 //
1652 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1653 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1654 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1655 //    the lock operators would typically be faster than reifying Self.
1656 //
1657 // *  Ideally I'd define the primitives as:
1658 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1659 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1660 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1661 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1662 //    Furthermore the register assignments are overconstrained, possibly resulting in
1663 //    sub-optimal code near the synchronization site.
1664 //
1665 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1666 //    Alternately, use a better sp-proximity test.
1667 //
1668 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1669 //    Either one is sufficient to uniquely identify a thread.
1670 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1671 //
1672 // *  Intrinsify notify() and notifyAll() for the common cases where the
1673 //    object is locked by the calling thread but the waitlist is empty.
1674 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1675 //
1676 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1677 //    But beware of excessive branch density on AMD Opterons.
1678 //
1679 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1680 //    or failure of the fast-path.  If the fast-path fails then we pass
1681 //    control to the slow-path, typically in C.  In Fast_Lock and
1682 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1683 //    will emit a conditional branch immediately after the node.
1684 //    So we have branches to branches and lots of ICC.ZF games.
1685 //    Instead, it might be better to have C2 pass a "FailureLabel"
1686 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1687 //    will drop through the node.  ICC.ZF is undefined at exit.
1688 //    In the case of failure, the node will branch directly to the
1689 //    FailureLabel
1690 
1691 
1692 // obj: object to lock
1693 // box: on-stack box address (displaced header location) - KILLED
1694 // rax,: tmp -- KILLED
1695 // scr: tmp -- KILLED
1696 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1697                                Register scrReg, Register cx1Reg, Register cx2Reg,
1698                                BiasedLockingCounters* counters,
1699                                RTMLockingCounters* rtm_counters,
1700                                RTMLockingCounters* stack_rtm_counters,
1701                                Metadata* method_data,
1702                                bool use_rtm, bool profile_rtm) {
1703   // Ensure the register assignments are disjoint
1704   assert(tmpReg == rax, "");
1705 
1706   if (use_rtm) {
1707     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1708   } else {
1709     assert(cx1Reg == noreg, "");
1710     assert(cx2Reg == noreg, "");
1711     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1712   }
1713 
1714   if (counters != NULL) {
1715     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1716   }
1717   if (EmitSync & 1) {
1718       // set box->dhw = markOopDesc::unused_mark()
1719       // Force all sync thru slow-path: slow_enter() and slow_exit()
1720       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1721       cmpptr (rsp, (int32_t)NULL_WORD);
1722   } else {
1723     // Possible cases that we'll encounter in fast_lock
1724     // ------------------------------------------------
1725     // * Inflated
1726     //    -- unlocked
1727     //    -- Locked
1728     //       = by self
1729     //       = by other
1730     // * biased
1731     //    -- by Self
1732     //    -- by other
1733     // * neutral
1734     // * stack-locked
1735     //    -- by self
1736     //       = sp-proximity test hits
1737     //       = sp-proximity test generates false-negative
1738     //    -- by other
1739     //
1740 
1741     Label IsInflated, DONE_LABEL;
1742 
1743     // it's stack-locked, biased or neutral
1744     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1745     // order to reduce the number of conditional branches in the most common cases.
1746     // Beware -- there's a subtle invariant that fetch of the markword
1747     // at [FETCH], below, will never observe a biased encoding (*101b).
1748     // If this invariant is not held we risk exclusion (safety) failure.
1749     if (UseBiasedLocking && !UseOptoBiasInlining) {
1750       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1751     }
1752 
1753 #if INCLUDE_RTM_OPT
1754     if (UseRTMForStackLocks && use_rtm) {
1755       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1756                         stack_rtm_counters, method_data, profile_rtm,
1757                         DONE_LABEL, IsInflated);
1758     }
1759 #endif // INCLUDE_RTM_OPT
1760 
1761     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1762     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1763     jccb(Assembler::notZero, IsInflated);
1764 
1765     // Attempt stack-locking ...
1766     orptr (tmpReg, markOopDesc::unlocked_value);
1767     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1768     if (os::is_MP()) {
1769       lock();
1770     }
1771     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1772     if (counters != NULL) {
1773       cond_inc32(Assembler::equal,
1774                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1775     }
1776     jcc(Assembler::equal, DONE_LABEL);           // Success
1777 
1778     // Recursive locking.
1779     // The object is stack-locked: markword contains stack pointer to BasicLock.
1780     // Locked by current thread if difference with current SP is less than one page.
1781     subptr(tmpReg, rsp);
1782     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1783     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1784     movptr(Address(boxReg, 0), tmpReg);
1785     if (counters != NULL) {
1786       cond_inc32(Assembler::equal,
1787                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1788     }
1789     jmp(DONE_LABEL);
1790 
1791     bind(IsInflated);
1792     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1793 
1794 #if INCLUDE_RTM_OPT
1795     // Use the same RTM locking code in 32- and 64-bit VM.
1796     if (use_rtm) {
1797       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1798                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1799     } else {
1800 #endif // INCLUDE_RTM_OPT
1801 
1802 #ifndef _LP64
1803     // The object is inflated.
1804 
1805     // boxReg refers to the on-stack BasicLock in the current frame.
1806     // We'd like to write:
1807     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1808     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1809     // additional latency as we have another ST in the store buffer that must drain.
1810 
1811     if (EmitSync & 8192) {
1812        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1813        get_thread (scrReg);
1814        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1815        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1816        if (os::is_MP()) {
1817          lock();
1818        }
1819        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1820     } else
1821     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1822        // register juggle because we need tmpReg for cmpxchgptr below
1823        movptr(scrReg, boxReg);
1824        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1825 
1826        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1827        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1828           // prefetchw [eax + Offset(_owner)-2]
1829           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1830        }
1831 
1832        if ((EmitSync & 64) == 0) {
1833          // Optimistic form: consider XORL tmpReg,tmpReg
1834          movptr(tmpReg, NULL_WORD);
1835        } else {
1836          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1837          // Test-And-CAS instead of CAS
1838          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1839          testptr(tmpReg, tmpReg);                   // Locked ?
1840          jccb  (Assembler::notZero, DONE_LABEL);
1841        }
1842 
1843        // Appears unlocked - try to swing _owner from null to non-null.
1844        // Ideally, I'd manifest "Self" with get_thread and then attempt
1845        // to CAS the register containing Self into m->Owner.
1846        // But we don't have enough registers, so instead we can either try to CAS
1847        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1848        // we later store "Self" into m->Owner.  Transiently storing a stack address
1849        // (rsp or the address of the box) into  m->owner is harmless.
1850        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1851        if (os::is_MP()) {
1852          lock();
1853        }
1854        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1855        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1856        // If we weren't able to swing _owner from NULL to the BasicLock
1857        // then take the slow path.
1858        jccb  (Assembler::notZero, DONE_LABEL);
1859        // update _owner from BasicLock to thread
1860        get_thread (scrReg);                    // beware: clobbers ICCs
1861        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1862        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1863 
1864        // If the CAS fails we can either retry or pass control to the slow-path.
1865        // We use the latter tactic.
1866        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1867        // If the CAS was successful ...
1868        //   Self has acquired the lock
1869        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1870        // Intentional fall-through into DONE_LABEL ...
1871     } else {
1872        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1873        movptr(boxReg, tmpReg);
1874 
1875        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1876        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1877           // prefetchw [eax + Offset(_owner)-2]
1878           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1879        }
1880 
1881        if ((EmitSync & 64) == 0) {
1882          // Optimistic form
1883          xorptr  (tmpReg, tmpReg);
1884        } else {
1885          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1886          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1887          testptr(tmpReg, tmpReg);                   // Locked ?
1888          jccb  (Assembler::notZero, DONE_LABEL);
1889        }
1890 
1891        // Appears unlocked - try to swing _owner from null to non-null.
1892        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1893        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1894        get_thread (scrReg);
1895        if (os::is_MP()) {
1896          lock();
1897        }
1898        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1899 
1900        // If the CAS fails we can either retry or pass control to the slow-path.
1901        // We use the latter tactic.
1902        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1903        // If the CAS was successful ...
1904        //   Self has acquired the lock
1905        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1906        // Intentional fall-through into DONE_LABEL ...
1907     }
1908 #else // _LP64
1909     // It's inflated
1910     movq(scrReg, tmpReg);
1911     xorq(tmpReg, tmpReg);
1912 
1913     if (os::is_MP()) {
1914       lock();
1915     }
1916     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1917     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1918     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1919     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1920     // Intentional fall-through into DONE_LABEL ...
1921     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1922 #endif // _LP64
1923 #if INCLUDE_RTM_OPT
1924     } // use_rtm()
1925 #endif
1926     // DONE_LABEL is a hot target - we'd really like to place it at the
1927     // start of cache line by padding with NOPs.
1928     // See the AMD and Intel software optimization manuals for the
1929     // most efficient "long" NOP encodings.
1930     // Unfortunately none of our alignment mechanisms suffice.
1931     bind(DONE_LABEL);
1932 
1933     // At DONE_LABEL the icc ZFlag is set as follows ...
1934     // Fast_Unlock uses the same protocol.
1935     // ZFlag == 1 -> Success
1936     // ZFlag == 0 -> Failure - force control through the slow-path
1937   }
1938 }
1939 
1940 // obj: object to unlock
1941 // box: box address (displaced header location), killed.  Must be EAX.
1942 // tmp: killed, cannot be obj nor box.
1943 //
1944 // Some commentary on balanced locking:
1945 //
1946 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1947 // Methods that don't have provably balanced locking are forced to run in the
1948 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1949 // The interpreter provides two properties:
1950 // I1:  At return-time the interpreter automatically and quietly unlocks any
1951 //      objects acquired the current activation (frame).  Recall that the
1952 //      interpreter maintains an on-stack list of locks currently held by
1953 //      a frame.
1954 // I2:  If a method attempts to unlock an object that is not held by the
1955 //      the frame the interpreter throws IMSX.
1956 //
1957 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1958 // B() doesn't have provably balanced locking so it runs in the interpreter.
1959 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1960 // is still locked by A().
1961 //
1962 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1963 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1964 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1965 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1966 // Arguably given that the spec legislates the JNI case as undefined our implementation
1967 // could reasonably *avoid* checking owner in Fast_Unlock().
1968 // In the interest of performance we elide m->Owner==Self check in unlock.
1969 // A perfectly viable alternative is to elide the owner check except when
1970 // Xcheck:jni is enabled.
1971 
1972 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1973   assert(boxReg == rax, "");
1974   assert_different_registers(objReg, boxReg, tmpReg);
1975 
1976   if (EmitSync & 4) {
1977     // Disable - inhibit all inlining.  Force control through the slow-path
1978     cmpptr (rsp, 0);
1979   } else {
1980     Label DONE_LABEL, Stacked, CheckSucc;
1981 
1982     // Critically, the biased locking test must have precedence over
1983     // and appear before the (box->dhw == 0) recursive stack-lock test.
1984     if (UseBiasedLocking && !UseOptoBiasInlining) {
1985        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1986     }
1987 
1988 #if INCLUDE_RTM_OPT
1989     if (UseRTMForStackLocks && use_rtm) {
1990       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1991       Label L_regular_unlock;
1992       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1993       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1994       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1995       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1996       xend();                                       // otherwise end...
1997       jmp(DONE_LABEL);                              // ... and we're done
1998       bind(L_regular_unlock);
1999     }
2000 #endif
2001 
2002     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2003     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2004     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2005     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2006     jccb  (Assembler::zero, Stacked);
2007 
2008     // It's inflated.
2009 #if INCLUDE_RTM_OPT
2010     if (use_rtm) {
2011       Label L_regular_inflated_unlock;
2012       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2013       movptr(boxReg, Address(tmpReg, owner_offset));
2014       testptr(boxReg, boxReg);
2015       jccb(Assembler::notZero, L_regular_inflated_unlock);
2016       xend();
2017       jmpb(DONE_LABEL);
2018       bind(L_regular_inflated_unlock);
2019     }
2020 #endif
2021 
2022     // Despite our balanced locking property we still check that m->_owner == Self
2023     // as java routines or native JNI code called by this thread might
2024     // have released the lock.
2025     // Refer to the comments in synchronizer.cpp for how we might encode extra
2026     // state in _succ so we can avoid fetching EntryList|cxq.
2027     //
2028     // I'd like to add more cases in fast_lock() and fast_unlock() --
2029     // such as recursive enter and exit -- but we have to be wary of
2030     // I$ bloat, T$ effects and BP$ effects.
2031     //
2032     // If there's no contention try a 1-0 exit.  That is, exit without
2033     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2034     // we detect and recover from the race that the 1-0 exit admits.
2035     //
2036     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2037     // before it STs null into _owner, releasing the lock.  Updates
2038     // to data protected by the critical section must be visible before
2039     // we drop the lock (and thus before any other thread could acquire
2040     // the lock and observe the fields protected by the lock).
2041     // IA32's memory-model is SPO, so STs are ordered with respect to
2042     // each other and there's no need for an explicit barrier (fence).
2043     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2044 #ifndef _LP64
2045     get_thread (boxReg);
2046     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2047       // prefetchw [ebx + Offset(_owner)-2]
2048       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2049     }
2050 
2051     // Note that we could employ various encoding schemes to reduce
2052     // the number of loads below (currently 4) to just 2 or 3.
2053     // Refer to the comments in synchronizer.cpp.
2054     // In practice the chain of fetches doesn't seem to impact performance, however.
2055     xorptr(boxReg, boxReg);
2056     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2057        // Attempt to reduce branch density - AMD's branch predictor.
2058        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2059        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2060        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2061        jccb  (Assembler::notZero, DONE_LABEL);
2062        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2063        jmpb  (DONE_LABEL);
2064     } else {
2065        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2066        jccb  (Assembler::notZero, DONE_LABEL);
2067        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2068        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2069        jccb  (Assembler::notZero, CheckSucc);
2070        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2071        jmpb  (DONE_LABEL);
2072     }
2073 
2074     // The Following code fragment (EmitSync & 65536) improves the performance of
2075     // contended applications and contended synchronization microbenchmarks.
2076     // Unfortunately the emission of the code - even though not executed - causes regressions
2077     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2078     // with an equal number of never-executed NOPs results in the same regression.
2079     // We leave it off by default.
2080 
2081     if ((EmitSync & 65536) != 0) {
2082        Label LSuccess, LGoSlowPath ;
2083 
2084        bind  (CheckSucc);
2085 
2086        // Optional pre-test ... it's safe to elide this
2087        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2088        jccb(Assembler::zero, LGoSlowPath);
2089 
2090        // We have a classic Dekker-style idiom:
2091        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2092        // There are a number of ways to implement the barrier:
2093        // (1) lock:andl &m->_owner, 0
2094        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2095        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2096        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2097        // (2) If supported, an explicit MFENCE is appealing.
2098        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2099        //     particularly if the write-buffer is full as might be the case if
2100        //     if stores closely precede the fence or fence-equivalent instruction.
2101        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2102        //     as the situation has changed with Nehalem and Shanghai.
2103        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2104        //     The $lines underlying the top-of-stack should be in M-state.
2105        //     The locked add instruction is serializing, of course.
2106        // (4) Use xchg, which is serializing
2107        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2108        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2109        //     The integer condition codes will tell us if succ was 0.
2110        //     Since _succ and _owner should reside in the same $line and
2111        //     we just stored into _owner, it's likely that the $line
2112        //     remains in M-state for the lock:orl.
2113        //
2114        // We currently use (3), although it's likely that switching to (2)
2115        // is correct for the future.
2116 
2117        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2118        if (os::is_MP()) {
2119          lock(); addptr(Address(rsp, 0), 0);
2120        }
2121        // Ratify _succ remains non-null
2122        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2123        jccb  (Assembler::notZero, LSuccess);
2124 
2125        xorptr(boxReg, boxReg);                  // box is really EAX
2126        if (os::is_MP()) { lock(); }
2127        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2128        // There's no successor so we tried to regrab the lock with the
2129        // placeholder value. If that didn't work, then another thread
2130        // grabbed the lock so we're done (and exit was a success).
2131        jccb  (Assembler::notEqual, LSuccess);
2132        // Since we're low on registers we installed rsp as a placeholding in _owner.
2133        // Now install Self over rsp.  This is safe as we're transitioning from
2134        // non-null to non=null
2135        get_thread (boxReg);
2136        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2137        // Intentional fall-through into LGoSlowPath ...
2138 
2139        bind  (LGoSlowPath);
2140        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2141        jmpb  (DONE_LABEL);
2142 
2143        bind  (LSuccess);
2144        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2145        jmpb  (DONE_LABEL);
2146     }
2147 
2148     bind (Stacked);
2149     // It's not inflated and it's not recursively stack-locked and it's not biased.
2150     // It must be stack-locked.
2151     // Try to reset the header to displaced header.
2152     // The "box" value on the stack is stable, so we can reload
2153     // and be assured we observe the same value as above.
2154     movptr(tmpReg, Address(boxReg, 0));
2155     if (os::is_MP()) {
2156       lock();
2157     }
2158     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2159     // Intention fall-thru into DONE_LABEL
2160 
2161     // DONE_LABEL is a hot target - we'd really like to place it at the
2162     // start of cache line by padding with NOPs.
2163     // See the AMD and Intel software optimization manuals for the
2164     // most efficient "long" NOP encodings.
2165     // Unfortunately none of our alignment mechanisms suffice.
2166     if ((EmitSync & 65536) == 0) {
2167        bind (CheckSucc);
2168     }
2169 #else // _LP64
2170     // It's inflated
2171     if (EmitSync & 1024) {
2172       // Emit code to check that _owner == Self
2173       // We could fold the _owner test into subsequent code more efficiently
2174       // than using a stand-alone check, but since _owner checking is off by
2175       // default we don't bother. We also might consider predicating the
2176       // _owner==Self check on Xcheck:jni or running on a debug build.
2177       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2178       xorptr(boxReg, r15_thread);
2179     } else {
2180       xorptr(boxReg, boxReg);
2181     }
2182     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2183     jccb  (Assembler::notZero, DONE_LABEL);
2184     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2185     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2186     jccb  (Assembler::notZero, CheckSucc);
2187     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2188     jmpb  (DONE_LABEL);
2189 
2190     if ((EmitSync & 65536) == 0) {
2191       // Try to avoid passing control into the slow_path ...
2192       Label LSuccess, LGoSlowPath ;
2193       bind  (CheckSucc);
2194 
2195       // The following optional optimization can be elided if necessary
2196       // Effectively: if (succ == null) goto SlowPath
2197       // The code reduces the window for a race, however,
2198       // and thus benefits performance.
2199       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2200       jccb  (Assembler::zero, LGoSlowPath);
2201 
2202       xorptr(boxReg, boxReg);
2203       if ((EmitSync & 16) && os::is_MP()) {
2204         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2205       } else {
2206         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2207         if (os::is_MP()) {
2208           // Memory barrier/fence
2209           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2210           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2211           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2212           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2213           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2214           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2215           lock(); addl(Address(rsp, 0), 0);
2216         }
2217       }
2218       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2219       jccb  (Assembler::notZero, LSuccess);
2220 
2221       // Rare inopportune interleaving - race.
2222       // The successor vanished in the small window above.
2223       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2224       // We need to ensure progress and succession.
2225       // Try to reacquire the lock.
2226       // If that fails then the new owner is responsible for succession and this
2227       // thread needs to take no further action and can exit via the fast path (success).
2228       // If the re-acquire succeeds then pass control into the slow path.
2229       // As implemented, this latter mode is horrible because we generated more
2230       // coherence traffic on the lock *and* artifically extended the critical section
2231       // length while by virtue of passing control into the slow path.
2232 
2233       // box is really RAX -- the following CMPXCHG depends on that binding
2234       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2235       if (os::is_MP()) { lock(); }
2236       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2237       // There's no successor so we tried to regrab the lock.
2238       // If that didn't work, then another thread grabbed the
2239       // lock so we're done (and exit was a success).
2240       jccb  (Assembler::notEqual, LSuccess);
2241       // Intentional fall-through into slow-path
2242 
2243       bind  (LGoSlowPath);
2244       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2245       jmpb  (DONE_LABEL);
2246 
2247       bind  (LSuccess);
2248       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2249       jmpb  (DONE_LABEL);
2250     }
2251 
2252     bind  (Stacked);
2253     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2254     if (os::is_MP()) { lock(); }
2255     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2256 
2257     if (EmitSync & 65536) {
2258        bind (CheckSucc);
2259     }
2260 #endif
2261     bind(DONE_LABEL);
2262   }
2263 }
2264 #endif // COMPILER2
2265 
2266 void MacroAssembler::c2bool(Register x) {
2267   // implements x == 0 ? 0 : 1
2268   // note: must only look at least-significant byte of x
2269   //       since C-style booleans are stored in one byte
2270   //       only! (was bug)
2271   andl(x, 0xFF);
2272   setb(Assembler::notZero, x);
2273 }
2274 
2275 // Wouldn't need if AddressLiteral version had new name
2276 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2277   Assembler::call(L, rtype);
2278 }
2279 
2280 void MacroAssembler::call(Register entry) {
2281   Assembler::call(entry);
2282 }
2283 
2284 void MacroAssembler::call(AddressLiteral entry) {
2285   if (reachable(entry)) {
2286     Assembler::call_literal(entry.target(), entry.rspec());
2287   } else {
2288     lea(rscratch1, entry);
2289     Assembler::call(rscratch1);
2290   }
2291 }
2292 
2293 void MacroAssembler::ic_call(address entry, jint method_index) {
2294   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2295   movptr(rax, (intptr_t)Universe::non_oop_word());
2296   call(AddressLiteral(entry, rh));
2297 }
2298 
2299 // Implementation of call_VM versions
2300 
2301 void MacroAssembler::call_VM(Register oop_result,
2302                              address entry_point,
2303                              bool check_exceptions) {
2304   Label C, E;
2305   call(C, relocInfo::none);
2306   jmp(E);
2307 
2308   bind(C);
2309   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2310   ret(0);
2311 
2312   bind(E);
2313 }
2314 
2315 void MacroAssembler::call_VM(Register oop_result,
2316                              address entry_point,
2317                              Register arg_1,
2318                              bool check_exceptions) {
2319   Label C, E;
2320   call(C, relocInfo::none);
2321   jmp(E);
2322 
2323   bind(C);
2324   pass_arg1(this, arg_1);
2325   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2326   ret(0);
2327 
2328   bind(E);
2329 }
2330 
2331 void MacroAssembler::call_VM(Register oop_result,
2332                              address entry_point,
2333                              Register arg_1,
2334                              Register arg_2,
2335                              bool check_exceptions) {
2336   Label C, E;
2337   call(C, relocInfo::none);
2338   jmp(E);
2339 
2340   bind(C);
2341 
2342   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2343 
2344   pass_arg2(this, arg_2);
2345   pass_arg1(this, arg_1);
2346   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2347   ret(0);
2348 
2349   bind(E);
2350 }
2351 
2352 void MacroAssembler::call_VM(Register oop_result,
2353                              address entry_point,
2354                              Register arg_1,
2355                              Register arg_2,
2356                              Register arg_3,
2357                              bool check_exceptions) {
2358   Label C, E;
2359   call(C, relocInfo::none);
2360   jmp(E);
2361 
2362   bind(C);
2363 
2364   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2365   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2366   pass_arg3(this, arg_3);
2367 
2368   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2369   pass_arg2(this, arg_2);
2370 
2371   pass_arg1(this, arg_1);
2372   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2373   ret(0);
2374 
2375   bind(E);
2376 }
2377 
2378 void MacroAssembler::call_VM(Register oop_result,
2379                              Register last_java_sp,
2380                              address entry_point,
2381                              int number_of_arguments,
2382                              bool check_exceptions) {
2383   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2384   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2385 }
2386 
2387 void MacroAssembler::call_VM(Register oop_result,
2388                              Register last_java_sp,
2389                              address entry_point,
2390                              Register arg_1,
2391                              bool check_exceptions) {
2392   pass_arg1(this, arg_1);
2393   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2394 }
2395 
2396 void MacroAssembler::call_VM(Register oop_result,
2397                              Register last_java_sp,
2398                              address entry_point,
2399                              Register arg_1,
2400                              Register arg_2,
2401                              bool check_exceptions) {
2402 
2403   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2404   pass_arg2(this, arg_2);
2405   pass_arg1(this, arg_1);
2406   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2407 }
2408 
2409 void MacroAssembler::call_VM(Register oop_result,
2410                              Register last_java_sp,
2411                              address entry_point,
2412                              Register arg_1,
2413                              Register arg_2,
2414                              Register arg_3,
2415                              bool check_exceptions) {
2416   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2417   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2418   pass_arg3(this, arg_3);
2419   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2420   pass_arg2(this, arg_2);
2421   pass_arg1(this, arg_1);
2422   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2423 }
2424 
2425 void MacroAssembler::super_call_VM(Register oop_result,
2426                                    Register last_java_sp,
2427                                    address entry_point,
2428                                    int number_of_arguments,
2429                                    bool check_exceptions) {
2430   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2431   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2432 }
2433 
2434 void MacroAssembler::super_call_VM(Register oop_result,
2435                                    Register last_java_sp,
2436                                    address entry_point,
2437                                    Register arg_1,
2438                                    bool check_exceptions) {
2439   pass_arg1(this, arg_1);
2440   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2441 }
2442 
2443 void MacroAssembler::super_call_VM(Register oop_result,
2444                                    Register last_java_sp,
2445                                    address entry_point,
2446                                    Register arg_1,
2447                                    Register arg_2,
2448                                    bool check_exceptions) {
2449 
2450   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2451   pass_arg2(this, arg_2);
2452   pass_arg1(this, arg_1);
2453   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2454 }
2455 
2456 void MacroAssembler::super_call_VM(Register oop_result,
2457                                    Register last_java_sp,
2458                                    address entry_point,
2459                                    Register arg_1,
2460                                    Register arg_2,
2461                                    Register arg_3,
2462                                    bool check_exceptions) {
2463   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2464   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2465   pass_arg3(this, arg_3);
2466   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2467   pass_arg2(this, arg_2);
2468   pass_arg1(this, arg_1);
2469   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2470 }
2471 
2472 void MacroAssembler::call_VM_base(Register oop_result,
2473                                   Register java_thread,
2474                                   Register last_java_sp,
2475                                   address  entry_point,
2476                                   int      number_of_arguments,
2477                                   bool     check_exceptions) {
2478   // determine java_thread register
2479   if (!java_thread->is_valid()) {
2480 #ifdef _LP64
2481     java_thread = r15_thread;
2482 #else
2483     java_thread = rdi;
2484     get_thread(java_thread);
2485 #endif // LP64
2486   }
2487   // determine last_java_sp register
2488   if (!last_java_sp->is_valid()) {
2489     last_java_sp = rsp;
2490   }
2491   // debugging support
2492   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2493   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2494 #ifdef ASSERT
2495   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2496   // r12 is the heapbase.
2497   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2498 #endif // ASSERT
2499 
2500   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2501   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2502 
2503   // push java thread (becomes first argument of C function)
2504 
2505   NOT_LP64(push(java_thread); number_of_arguments++);
2506   LP64_ONLY(mov(c_rarg0, r15_thread));
2507 
2508   // set last Java frame before call
2509   assert(last_java_sp != rbp, "can't use ebp/rbp");
2510 
2511   // Only interpreter should have to set fp
2512   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2513 
2514   // do the call, remove parameters
2515   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2516 
2517   // restore the thread (cannot use the pushed argument since arguments
2518   // may be overwritten by C code generated by an optimizing compiler);
2519   // however can use the register value directly if it is callee saved.
2520   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2521     // rdi & rsi (also r15) are callee saved -> nothing to do
2522 #ifdef ASSERT
2523     guarantee(java_thread != rax, "change this code");
2524     push(rax);
2525     { Label L;
2526       get_thread(rax);
2527       cmpptr(java_thread, rax);
2528       jcc(Assembler::equal, L);
2529       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2530       bind(L);
2531     }
2532     pop(rax);
2533 #endif
2534   } else {
2535     get_thread(java_thread);
2536   }
2537   // reset last Java frame
2538   // Only interpreter should have to clear fp
2539   reset_last_Java_frame(java_thread, true);
2540 
2541    // C++ interp handles this in the interpreter
2542   check_and_handle_popframe(java_thread);
2543   check_and_handle_earlyret(java_thread);
2544 
2545   if (check_exceptions) {
2546     // check for pending exceptions (java_thread is set upon return)
2547     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2548 #ifndef _LP64
2549     jump_cc(Assembler::notEqual,
2550             RuntimeAddress(StubRoutines::forward_exception_entry()));
2551 #else
2552     // This used to conditionally jump to forward_exception however it is
2553     // possible if we relocate that the branch will not reach. So we must jump
2554     // around so we can always reach
2555 
2556     Label ok;
2557     jcc(Assembler::equal, ok);
2558     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2559     bind(ok);
2560 #endif // LP64
2561   }
2562 
2563   // get oop result if there is one and reset the value in the thread
2564   if (oop_result->is_valid()) {
2565     get_vm_result(oop_result, java_thread);
2566   }
2567 }
2568 
2569 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2570 
2571   // Calculate the value for last_Java_sp
2572   // somewhat subtle. call_VM does an intermediate call
2573   // which places a return address on the stack just under the
2574   // stack pointer as the user finsihed with it. This allows
2575   // use to retrieve last_Java_pc from last_Java_sp[-1].
2576   // On 32bit we then have to push additional args on the stack to accomplish
2577   // the actual requested call. On 64bit call_VM only can use register args
2578   // so the only extra space is the return address that call_VM created.
2579   // This hopefully explains the calculations here.
2580 
2581 #ifdef _LP64
2582   // We've pushed one address, correct last_Java_sp
2583   lea(rax, Address(rsp, wordSize));
2584 #else
2585   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2586 #endif // LP64
2587 
2588   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2589 
2590 }
2591 
2592 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2593 void MacroAssembler::call_VM_leaf0(address entry_point) {
2594   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2595 }
2596 
2597 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2598   call_VM_leaf_base(entry_point, number_of_arguments);
2599 }
2600 
2601 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2602   pass_arg0(this, arg_0);
2603   call_VM_leaf(entry_point, 1);
2604 }
2605 
2606 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2607 
2608   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2609   pass_arg1(this, arg_1);
2610   pass_arg0(this, arg_0);
2611   call_VM_leaf(entry_point, 2);
2612 }
2613 
2614 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2615   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2616   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2617   pass_arg2(this, arg_2);
2618   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2619   pass_arg1(this, arg_1);
2620   pass_arg0(this, arg_0);
2621   call_VM_leaf(entry_point, 3);
2622 }
2623 
2624 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2625   pass_arg0(this, arg_0);
2626   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2627 }
2628 
2629 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2630 
2631   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2632   pass_arg1(this, arg_1);
2633   pass_arg0(this, arg_0);
2634   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2635 }
2636 
2637 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2638   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2639   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2640   pass_arg2(this, arg_2);
2641   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2642   pass_arg1(this, arg_1);
2643   pass_arg0(this, arg_0);
2644   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2645 }
2646 
2647 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2648   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2649   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2650   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2651   pass_arg3(this, arg_3);
2652   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2653   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2654   pass_arg2(this, arg_2);
2655   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2656   pass_arg1(this, arg_1);
2657   pass_arg0(this, arg_0);
2658   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2659 }
2660 
2661 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2662   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2663   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2664   verify_oop(oop_result, "broken oop in call_VM_base");
2665 }
2666 
2667 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2668   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2669   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2670 }
2671 
2672 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2673 }
2674 
2675 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2676 }
2677 
2678 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2679   if (reachable(src1)) {
2680     cmpl(as_Address(src1), imm);
2681   } else {
2682     lea(rscratch1, src1);
2683     cmpl(Address(rscratch1, 0), imm);
2684   }
2685 }
2686 
2687 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2688   assert(!src2.is_lval(), "use cmpptr");
2689   if (reachable(src2)) {
2690     cmpl(src1, as_Address(src2));
2691   } else {
2692     lea(rscratch1, src2);
2693     cmpl(src1, Address(rscratch1, 0));
2694   }
2695 }
2696 
2697 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2698   Assembler::cmpl(src1, imm);
2699 }
2700 
2701 void MacroAssembler::cmp32(Register src1, Address src2) {
2702   Assembler::cmpl(src1, src2);
2703 }
2704 
2705 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2706   ucomisd(opr1, opr2);
2707 
2708   Label L;
2709   if (unordered_is_less) {
2710     movl(dst, -1);
2711     jcc(Assembler::parity, L);
2712     jcc(Assembler::below , L);
2713     movl(dst, 0);
2714     jcc(Assembler::equal , L);
2715     increment(dst);
2716   } else { // unordered is greater
2717     movl(dst, 1);
2718     jcc(Assembler::parity, L);
2719     jcc(Assembler::above , L);
2720     movl(dst, 0);
2721     jcc(Assembler::equal , L);
2722     decrementl(dst);
2723   }
2724   bind(L);
2725 }
2726 
2727 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2728   ucomiss(opr1, opr2);
2729 
2730   Label L;
2731   if (unordered_is_less) {
2732     movl(dst, -1);
2733     jcc(Assembler::parity, L);
2734     jcc(Assembler::below , L);
2735     movl(dst, 0);
2736     jcc(Assembler::equal , L);
2737     increment(dst);
2738   } else { // unordered is greater
2739     movl(dst, 1);
2740     jcc(Assembler::parity, L);
2741     jcc(Assembler::above , L);
2742     movl(dst, 0);
2743     jcc(Assembler::equal , L);
2744     decrementl(dst);
2745   }
2746   bind(L);
2747 }
2748 
2749 
2750 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2751   if (reachable(src1)) {
2752     cmpb(as_Address(src1), imm);
2753   } else {
2754     lea(rscratch1, src1);
2755     cmpb(Address(rscratch1, 0), imm);
2756   }
2757 }
2758 
2759 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2760 #ifdef _LP64
2761   if (src2.is_lval()) {
2762     movptr(rscratch1, src2);
2763     Assembler::cmpq(src1, rscratch1);
2764   } else if (reachable(src2)) {
2765     cmpq(src1, as_Address(src2));
2766   } else {
2767     lea(rscratch1, src2);
2768     Assembler::cmpq(src1, Address(rscratch1, 0));
2769   }
2770 #else
2771   if (src2.is_lval()) {
2772     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2773   } else {
2774     cmpl(src1, as_Address(src2));
2775   }
2776 #endif // _LP64
2777 }
2778 
2779 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2780   assert(src2.is_lval(), "not a mem-mem compare");
2781 #ifdef _LP64
2782   // moves src2's literal address
2783   movptr(rscratch1, src2);
2784   Assembler::cmpq(src1, rscratch1);
2785 #else
2786   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2787 #endif // _LP64
2788 }
2789 
2790 void MacroAssembler::cmpoop(Register src1, Register src2) {
2791   cmpptr(src1, src2);
2792 }
2793 
2794 void MacroAssembler::cmpoop(Register src1, Address src2) {
2795   cmpptr(src1, src2);
2796 }
2797 
2798 #ifdef _LP64
2799 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2800   movoop(rscratch1, src2);
2801   cmpptr(src1, rscratch1);
2802 }
2803 #endif
2804 
2805 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2806   if (reachable(adr)) {
2807     if (os::is_MP())
2808       lock();
2809     cmpxchgptr(reg, as_Address(adr));
2810   } else {
2811     lea(rscratch1, adr);
2812     if (os::is_MP())
2813       lock();
2814     cmpxchgptr(reg, Address(rscratch1, 0));
2815   }
2816 }
2817 
2818 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2819   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2820 }
2821 
2822 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2823   if (reachable(src)) {
2824     Assembler::comisd(dst, as_Address(src));
2825   } else {
2826     lea(rscratch1, src);
2827     Assembler::comisd(dst, Address(rscratch1, 0));
2828   }
2829 }
2830 
2831 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2832   if (reachable(src)) {
2833     Assembler::comiss(dst, as_Address(src));
2834   } else {
2835     lea(rscratch1, src);
2836     Assembler::comiss(dst, Address(rscratch1, 0));
2837   }
2838 }
2839 
2840 
2841 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2842   Condition negated_cond = negate_condition(cond);
2843   Label L;
2844   jcc(negated_cond, L);
2845   pushf(); // Preserve flags
2846   atomic_incl(counter_addr);
2847   popf();
2848   bind(L);
2849 }
2850 
2851 int MacroAssembler::corrected_idivl(Register reg) {
2852   // Full implementation of Java idiv and irem; checks for
2853   // special case as described in JVM spec., p.243 & p.271.
2854   // The function returns the (pc) offset of the idivl
2855   // instruction - may be needed for implicit exceptions.
2856   //
2857   //         normal case                           special case
2858   //
2859   // input : rax,: dividend                         min_int
2860   //         reg: divisor   (may not be rax,/rdx)   -1
2861   //
2862   // output: rax,: quotient  (= rax, idiv reg)       min_int
2863   //         rdx: remainder (= rax, irem reg)       0
2864   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2865   const int min_int = 0x80000000;
2866   Label normal_case, special_case;
2867 
2868   // check for special case
2869   cmpl(rax, min_int);
2870   jcc(Assembler::notEqual, normal_case);
2871   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2872   cmpl(reg, -1);
2873   jcc(Assembler::equal, special_case);
2874 
2875   // handle normal case
2876   bind(normal_case);
2877   cdql();
2878   int idivl_offset = offset();
2879   idivl(reg);
2880 
2881   // normal and special case exit
2882   bind(special_case);
2883 
2884   return idivl_offset;
2885 }
2886 
2887 
2888 
2889 void MacroAssembler::decrementl(Register reg, int value) {
2890   if (value == min_jint) {subl(reg, value) ; return; }
2891   if (value <  0) { incrementl(reg, -value); return; }
2892   if (value == 0) {                        ; return; }
2893   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2894   /* else */      { subl(reg, value)       ; return; }
2895 }
2896 
2897 void MacroAssembler::decrementl(Address dst, int value) {
2898   if (value == min_jint) {subl(dst, value) ; return; }
2899   if (value <  0) { incrementl(dst, -value); return; }
2900   if (value == 0) {                        ; return; }
2901   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2902   /* else */      { subl(dst, value)       ; return; }
2903 }
2904 
2905 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2906   assert (shift_value > 0, "illegal shift value");
2907   Label _is_positive;
2908   testl (reg, reg);
2909   jcc (Assembler::positive, _is_positive);
2910   int offset = (1 << shift_value) - 1 ;
2911 
2912   if (offset == 1) {
2913     incrementl(reg);
2914   } else {
2915     addl(reg, offset);
2916   }
2917 
2918   bind (_is_positive);
2919   sarl(reg, shift_value);
2920 }
2921 
2922 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2923   if (reachable(src)) {
2924     Assembler::divsd(dst, as_Address(src));
2925   } else {
2926     lea(rscratch1, src);
2927     Assembler::divsd(dst, Address(rscratch1, 0));
2928   }
2929 }
2930 
2931 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2932   if (reachable(src)) {
2933     Assembler::divss(dst, as_Address(src));
2934   } else {
2935     lea(rscratch1, src);
2936     Assembler::divss(dst, Address(rscratch1, 0));
2937   }
2938 }
2939 
2940 // !defined(COMPILER2) is because of stupid core builds
2941 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2942 void MacroAssembler::empty_FPU_stack() {
2943   if (VM_Version::supports_mmx()) {
2944     emms();
2945   } else {
2946     for (int i = 8; i-- > 0; ) ffree(i);
2947   }
2948 }
2949 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2950 
2951 
2952 // Defines obj, preserves var_size_in_bytes
2953 void MacroAssembler::eden_allocate(Register obj,
2954                                    Register var_size_in_bytes,
2955                                    int con_size_in_bytes,
2956                                    Register t1,
2957                                    Label& slow_case) {
2958   assert(obj == rax, "obj must be in rax, for cmpxchg");
2959   assert_different_registers(obj, var_size_in_bytes, t1);
2960   if (!Universe::heap()->supports_inline_contig_alloc()) {
2961     jmp(slow_case);
2962   } else {
2963     Register end = t1;
2964     Label retry;
2965     bind(retry);
2966     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2967     movptr(obj, heap_top);
2968     if (var_size_in_bytes == noreg) {
2969       lea(end, Address(obj, con_size_in_bytes));
2970     } else {
2971       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2972     }
2973     // if end < obj then we wrapped around => object too long => slow case
2974     cmpptr(end, obj);
2975     jcc(Assembler::below, slow_case);
2976     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2977     jcc(Assembler::above, slow_case);
2978     // Compare obj with the top addr, and if still equal, store the new top addr in
2979     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2980     // it otherwise. Use lock prefix for atomicity on MPs.
2981     locked_cmpxchgptr(end, heap_top);
2982     jcc(Assembler::notEqual, retry);
2983   }
2984 }
2985 
2986 void MacroAssembler::enter() {
2987   push(rbp);
2988   mov(rbp, rsp);
2989 }
2990 
2991 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2992 void MacroAssembler::fat_nop() {
2993   if (UseAddressNop) {
2994     addr_nop_5();
2995   } else {
2996     emit_int8(0x26); // es:
2997     emit_int8(0x2e); // cs:
2998     emit_int8(0x64); // fs:
2999     emit_int8(0x65); // gs:
3000     emit_int8((unsigned char)0x90);
3001   }
3002 }
3003 
3004 void MacroAssembler::fcmp(Register tmp) {
3005   fcmp(tmp, 1, true, true);
3006 }
3007 
3008 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3009   assert(!pop_right || pop_left, "usage error");
3010   if (VM_Version::supports_cmov()) {
3011     assert(tmp == noreg, "unneeded temp");
3012     if (pop_left) {
3013       fucomip(index);
3014     } else {
3015       fucomi(index);
3016     }
3017     if (pop_right) {
3018       fpop();
3019     }
3020   } else {
3021     assert(tmp != noreg, "need temp");
3022     if (pop_left) {
3023       if (pop_right) {
3024         fcompp();
3025       } else {
3026         fcomp(index);
3027       }
3028     } else {
3029       fcom(index);
3030     }
3031     // convert FPU condition into eflags condition via rax,
3032     save_rax(tmp);
3033     fwait(); fnstsw_ax();
3034     sahf();
3035     restore_rax(tmp);
3036   }
3037   // condition codes set as follows:
3038   //
3039   // CF (corresponds to C0) if x < y
3040   // PF (corresponds to C2) if unordered
3041   // ZF (corresponds to C3) if x = y
3042 }
3043 
3044 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3045   fcmp2int(dst, unordered_is_less, 1, true, true);
3046 }
3047 
3048 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3049   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3050   Label L;
3051   if (unordered_is_less) {
3052     movl(dst, -1);
3053     jcc(Assembler::parity, L);
3054     jcc(Assembler::below , L);
3055     movl(dst, 0);
3056     jcc(Assembler::equal , L);
3057     increment(dst);
3058   } else { // unordered is greater
3059     movl(dst, 1);
3060     jcc(Assembler::parity, L);
3061     jcc(Assembler::above , L);
3062     movl(dst, 0);
3063     jcc(Assembler::equal , L);
3064     decrementl(dst);
3065   }
3066   bind(L);
3067 }
3068 
3069 void MacroAssembler::fld_d(AddressLiteral src) {
3070   fld_d(as_Address(src));
3071 }
3072 
3073 void MacroAssembler::fld_s(AddressLiteral src) {
3074   fld_s(as_Address(src));
3075 }
3076 
3077 void MacroAssembler::fld_x(AddressLiteral src) {
3078   Assembler::fld_x(as_Address(src));
3079 }
3080 
3081 void MacroAssembler::fldcw(AddressLiteral src) {
3082   Assembler::fldcw(as_Address(src));
3083 }
3084 
3085 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3086   if (reachable(src)) {
3087     Assembler::mulpd(dst, as_Address(src));
3088   } else {
3089     lea(rscratch1, src);
3090     Assembler::mulpd(dst, Address(rscratch1, 0));
3091   }
3092 }
3093 
3094 void MacroAssembler::increase_precision() {
3095   subptr(rsp, BytesPerWord);
3096   fnstcw(Address(rsp, 0));
3097   movl(rax, Address(rsp, 0));
3098   orl(rax, 0x300);
3099   push(rax);
3100   fldcw(Address(rsp, 0));
3101   pop(rax);
3102 }
3103 
3104 void MacroAssembler::restore_precision() {
3105   fldcw(Address(rsp, 0));
3106   addptr(rsp, BytesPerWord);
3107 }
3108 
3109 void MacroAssembler::fpop() {
3110   ffree();
3111   fincstp();
3112 }
3113 
3114 void MacroAssembler::load_float(Address src) {
3115   if (UseSSE >= 1) {
3116     movflt(xmm0, src);
3117   } else {
3118     LP64_ONLY(ShouldNotReachHere());
3119     NOT_LP64(fld_s(src));
3120   }
3121 }
3122 
3123 void MacroAssembler::store_float(Address dst) {
3124   if (UseSSE >= 1) {
3125     movflt(dst, xmm0);
3126   } else {
3127     LP64_ONLY(ShouldNotReachHere());
3128     NOT_LP64(fstp_s(dst));
3129   }
3130 }
3131 
3132 void MacroAssembler::load_double(Address src) {
3133   if (UseSSE >= 2) {
3134     movdbl(xmm0, src);
3135   } else {
3136     LP64_ONLY(ShouldNotReachHere());
3137     NOT_LP64(fld_d(src));
3138   }
3139 }
3140 
3141 void MacroAssembler::store_double(Address dst) {
3142   if (UseSSE >= 2) {
3143     movdbl(dst, xmm0);
3144   } else {
3145     LP64_ONLY(ShouldNotReachHere());
3146     NOT_LP64(fstp_d(dst));
3147   }
3148 }
3149 
3150 void MacroAssembler::fremr(Register tmp) {
3151   save_rax(tmp);
3152   { Label L;
3153     bind(L);
3154     fprem();
3155     fwait(); fnstsw_ax();
3156 #ifdef _LP64
3157     testl(rax, 0x400);
3158     jcc(Assembler::notEqual, L);
3159 #else
3160     sahf();
3161     jcc(Assembler::parity, L);
3162 #endif // _LP64
3163   }
3164   restore_rax(tmp);
3165   // Result is in ST0.
3166   // Note: fxch & fpop to get rid of ST1
3167   // (otherwise FPU stack could overflow eventually)
3168   fxch(1);
3169   fpop();
3170 }
3171 
3172 // dst = c = a * b + c
3173 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3174   Assembler::vfmadd231sd(c, a, b);
3175   if (dst != c) {
3176     movdbl(dst, c);
3177   }
3178 }
3179 
3180 // dst = c = a * b + c
3181 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3182   Assembler::vfmadd231ss(c, a, b);
3183   if (dst != c) {
3184     movflt(dst, c);
3185   }
3186 }
3187 
3188 // dst = c = a * b + c
3189 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3190   Assembler::vfmadd231pd(c, a, b, vector_len);
3191   if (dst != c) {
3192     vmovdqu(dst, c);
3193   }
3194 }
3195 
3196 // dst = c = a * b + c
3197 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3198   Assembler::vfmadd231ps(c, a, b, vector_len);
3199   if (dst != c) {
3200     vmovdqu(dst, c);
3201   }
3202 }
3203 
3204 // dst = c = a * b + c
3205 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3206   Assembler::vfmadd231pd(c, a, b, vector_len);
3207   if (dst != c) {
3208     vmovdqu(dst, c);
3209   }
3210 }
3211 
3212 // dst = c = a * b + c
3213 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3214   Assembler::vfmadd231ps(c, a, b, vector_len);
3215   if (dst != c) {
3216     vmovdqu(dst, c);
3217   }
3218 }
3219 
3220 void MacroAssembler::incrementl(AddressLiteral dst) {
3221   if (reachable(dst)) {
3222     incrementl(as_Address(dst));
3223   } else {
3224     lea(rscratch1, dst);
3225     incrementl(Address(rscratch1, 0));
3226   }
3227 }
3228 
3229 void MacroAssembler::incrementl(ArrayAddress dst) {
3230   incrementl(as_Address(dst));
3231 }
3232 
3233 void MacroAssembler::incrementl(Register reg, int value) {
3234   if (value == min_jint) {addl(reg, value) ; return; }
3235   if (value <  0) { decrementl(reg, -value); return; }
3236   if (value == 0) {                        ; return; }
3237   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3238   /* else */      { addl(reg, value)       ; return; }
3239 }
3240 
3241 void MacroAssembler::incrementl(Address dst, int value) {
3242   if (value == min_jint) {addl(dst, value) ; return; }
3243   if (value <  0) { decrementl(dst, -value); return; }
3244   if (value == 0) {                        ; return; }
3245   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3246   /* else */      { addl(dst, value)       ; return; }
3247 }
3248 
3249 void MacroAssembler::jump(AddressLiteral dst) {
3250   if (reachable(dst)) {
3251     jmp_literal(dst.target(), dst.rspec());
3252   } else {
3253     lea(rscratch1, dst);
3254     jmp(rscratch1);
3255   }
3256 }
3257 
3258 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3259   if (reachable(dst)) {
3260     InstructionMark im(this);
3261     relocate(dst.reloc());
3262     const int short_size = 2;
3263     const int long_size = 6;
3264     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3265     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3266       // 0111 tttn #8-bit disp
3267       emit_int8(0x70 | cc);
3268       emit_int8((offs - short_size) & 0xFF);
3269     } else {
3270       // 0000 1111 1000 tttn #32-bit disp
3271       emit_int8(0x0F);
3272       emit_int8((unsigned char)(0x80 | cc));
3273       emit_int32(offs - long_size);
3274     }
3275   } else {
3276 #ifdef ASSERT
3277     warning("reversing conditional branch");
3278 #endif /* ASSERT */
3279     Label skip;
3280     jccb(reverse[cc], skip);
3281     lea(rscratch1, dst);
3282     Assembler::jmp(rscratch1);
3283     bind(skip);
3284   }
3285 }
3286 
3287 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3288   if (reachable(src)) {
3289     Assembler::ldmxcsr(as_Address(src));
3290   } else {
3291     lea(rscratch1, src);
3292     Assembler::ldmxcsr(Address(rscratch1, 0));
3293   }
3294 }
3295 
3296 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3297   int off;
3298   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3299     off = offset();
3300     movsbl(dst, src); // movsxb
3301   } else {
3302     off = load_unsigned_byte(dst, src);
3303     shll(dst, 24);
3304     sarl(dst, 24);
3305   }
3306   return off;
3307 }
3308 
3309 // Note: load_signed_short used to be called load_signed_word.
3310 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3311 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3312 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3313 int MacroAssembler::load_signed_short(Register dst, Address src) {
3314   int off;
3315   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3316     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3317     // version but this is what 64bit has always done. This seems to imply
3318     // that users are only using 32bits worth.
3319     off = offset();
3320     movswl(dst, src); // movsxw
3321   } else {
3322     off = load_unsigned_short(dst, src);
3323     shll(dst, 16);
3324     sarl(dst, 16);
3325   }
3326   return off;
3327 }
3328 
3329 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3330   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3331   // and "3.9 Partial Register Penalties", p. 22).
3332   int off;
3333   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3334     off = offset();
3335     movzbl(dst, src); // movzxb
3336   } else {
3337     xorl(dst, dst);
3338     off = offset();
3339     movb(dst, src);
3340   }
3341   return off;
3342 }
3343 
3344 // Note: load_unsigned_short used to be called load_unsigned_word.
3345 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3346   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3347   // and "3.9 Partial Register Penalties", p. 22).
3348   int off;
3349   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3350     off = offset();
3351     movzwl(dst, src); // movzxw
3352   } else {
3353     xorl(dst, dst);
3354     off = offset();
3355     movw(dst, src);
3356   }
3357   return off;
3358 }
3359 
3360 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3361   switch (size_in_bytes) {
3362 #ifndef _LP64
3363   case  8:
3364     assert(dst2 != noreg, "second dest register required");
3365     movl(dst,  src);
3366     movl(dst2, src.plus_disp(BytesPerInt));
3367     break;
3368 #else
3369   case  8:  movq(dst, src); break;
3370 #endif
3371   case  4:  movl(dst, src); break;
3372   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3373   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3374   default:  ShouldNotReachHere();
3375   }
3376 }
3377 
3378 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3379   switch (size_in_bytes) {
3380 #ifndef _LP64
3381   case  8:
3382     assert(src2 != noreg, "second source register required");
3383     movl(dst,                        src);
3384     movl(dst.plus_disp(BytesPerInt), src2);
3385     break;
3386 #else
3387   case  8:  movq(dst, src); break;
3388 #endif
3389   case  4:  movl(dst, src); break;
3390   case  2:  movw(dst, src); break;
3391   case  1:  movb(dst, src); break;
3392   default:  ShouldNotReachHere();
3393   }
3394 }
3395 
3396 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3397   if (reachable(dst)) {
3398     movl(as_Address(dst), src);
3399   } else {
3400     lea(rscratch1, dst);
3401     movl(Address(rscratch1, 0), src);
3402   }
3403 }
3404 
3405 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3406   if (reachable(src)) {
3407     movl(dst, as_Address(src));
3408   } else {
3409     lea(rscratch1, src);
3410     movl(dst, Address(rscratch1, 0));
3411   }
3412 }
3413 
3414 // C++ bool manipulation
3415 
3416 void MacroAssembler::movbool(Register dst, Address src) {
3417   if(sizeof(bool) == 1)
3418     movb(dst, src);
3419   else if(sizeof(bool) == 2)
3420     movw(dst, src);
3421   else if(sizeof(bool) == 4)
3422     movl(dst, src);
3423   else
3424     // unsupported
3425     ShouldNotReachHere();
3426 }
3427 
3428 void MacroAssembler::movbool(Address dst, bool boolconst) {
3429   if(sizeof(bool) == 1)
3430     movb(dst, (int) boolconst);
3431   else if(sizeof(bool) == 2)
3432     movw(dst, (int) boolconst);
3433   else if(sizeof(bool) == 4)
3434     movl(dst, (int) boolconst);
3435   else
3436     // unsupported
3437     ShouldNotReachHere();
3438 }
3439 
3440 void MacroAssembler::movbool(Address dst, Register src) {
3441   if(sizeof(bool) == 1)
3442     movb(dst, src);
3443   else if(sizeof(bool) == 2)
3444     movw(dst, src);
3445   else if(sizeof(bool) == 4)
3446     movl(dst, src);
3447   else
3448     // unsupported
3449     ShouldNotReachHere();
3450 }
3451 
3452 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3453   movb(as_Address(dst), src);
3454 }
3455 
3456 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3457   if (reachable(src)) {
3458     movdl(dst, as_Address(src));
3459   } else {
3460     lea(rscratch1, src);
3461     movdl(dst, Address(rscratch1, 0));
3462   }
3463 }
3464 
3465 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3466   if (reachable(src)) {
3467     movq(dst, as_Address(src));
3468   } else {
3469     lea(rscratch1, src);
3470     movq(dst, Address(rscratch1, 0));
3471   }
3472 }
3473 
3474 void MacroAssembler::setvectmask(Register dst, Register src) {
3475   Assembler::movl(dst, 1);
3476   Assembler::shlxl(dst, dst, src);
3477   Assembler::decl(dst);
3478   Assembler::kmovdl(k1, dst);
3479   Assembler::movl(dst, src);
3480 }
3481 
3482 void MacroAssembler::restorevectmask() {
3483   Assembler::knotwl(k1, k0);
3484 }
3485 
3486 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3487   if (reachable(src)) {
3488     if (UseXmmLoadAndClearUpper) {
3489       movsd (dst, as_Address(src));
3490     } else {
3491       movlpd(dst, as_Address(src));
3492     }
3493   } else {
3494     lea(rscratch1, src);
3495     if (UseXmmLoadAndClearUpper) {
3496       movsd (dst, Address(rscratch1, 0));
3497     } else {
3498       movlpd(dst, Address(rscratch1, 0));
3499     }
3500   }
3501 }
3502 
3503 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3504   if (reachable(src)) {
3505     movss(dst, as_Address(src));
3506   } else {
3507     lea(rscratch1, src);
3508     movss(dst, Address(rscratch1, 0));
3509   }
3510 }
3511 
3512 void MacroAssembler::movptr(Register dst, Register src) {
3513   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3514 }
3515 
3516 void MacroAssembler::movptr(Register dst, Address src) {
3517   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3518 }
3519 
3520 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3521 void MacroAssembler::movptr(Register dst, intptr_t src) {
3522   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3523 }
3524 
3525 void MacroAssembler::movptr(Address dst, Register src) {
3526   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3527 }
3528 
3529 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3530   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3531     Assembler::vextractf32x4(dst, src, 0);
3532   } else {
3533     Assembler::movdqu(dst, src);
3534   }
3535 }
3536 
3537 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3538   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3539     Assembler::vinsertf32x4(dst, dst, src, 0);
3540   } else {
3541     Assembler::movdqu(dst, src);
3542   }
3543 }
3544 
3545 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3546   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3547     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3548   } else {
3549     Assembler::movdqu(dst, src);
3550   }
3551 }
3552 
3553 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3554   if (reachable(src)) {
3555     movdqu(dst, as_Address(src));
3556   } else {
3557     lea(scratchReg, src);
3558     movdqu(dst, Address(scratchReg, 0));
3559   }
3560 }
3561 
3562 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3563   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3564     vextractf64x4_low(dst, src);
3565   } else {
3566     Assembler::vmovdqu(dst, src);
3567   }
3568 }
3569 
3570 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3571   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3572     vinsertf64x4_low(dst, src);
3573   } else {
3574     Assembler::vmovdqu(dst, src);
3575   }
3576 }
3577 
3578 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3579   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3580     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3581   }
3582   else {
3583     Assembler::vmovdqu(dst, src);
3584   }
3585 }
3586 
3587 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3588   if (reachable(src)) {
3589     vmovdqu(dst, as_Address(src));
3590   }
3591   else {
3592     lea(rscratch1, src);
3593     vmovdqu(dst, Address(rscratch1, 0));
3594   }
3595 }
3596 
3597 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3598   if (reachable(src)) {
3599     Assembler::movdqa(dst, as_Address(src));
3600   } else {
3601     lea(rscratch1, src);
3602     Assembler::movdqa(dst, Address(rscratch1, 0));
3603   }
3604 }
3605 
3606 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3607   if (reachable(src)) {
3608     Assembler::movsd(dst, as_Address(src));
3609   } else {
3610     lea(rscratch1, src);
3611     Assembler::movsd(dst, Address(rscratch1, 0));
3612   }
3613 }
3614 
3615 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3616   if (reachable(src)) {
3617     Assembler::movss(dst, as_Address(src));
3618   } else {
3619     lea(rscratch1, src);
3620     Assembler::movss(dst, Address(rscratch1, 0));
3621   }
3622 }
3623 
3624 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3625   if (reachable(src)) {
3626     Assembler::mulsd(dst, as_Address(src));
3627   } else {
3628     lea(rscratch1, src);
3629     Assembler::mulsd(dst, Address(rscratch1, 0));
3630   }
3631 }
3632 
3633 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3634   if (reachable(src)) {
3635     Assembler::mulss(dst, as_Address(src));
3636   } else {
3637     lea(rscratch1, src);
3638     Assembler::mulss(dst, Address(rscratch1, 0));
3639   }
3640 }
3641 
3642 void MacroAssembler::null_check(Register reg, int offset) {
3643   if (needs_explicit_null_check(offset)) {
3644     // provoke OS NULL exception if reg = NULL by
3645     // accessing M[reg] w/o changing any (non-CC) registers
3646     // NOTE: cmpl is plenty here to provoke a segv
3647     cmpptr(rax, Address(reg, 0));
3648     // Note: should probably use testl(rax, Address(reg, 0));
3649     //       may be shorter code (however, this version of
3650     //       testl needs to be implemented first)
3651   } else {
3652     // nothing to do, (later) access of M[reg + offset]
3653     // will provoke OS NULL exception if reg = NULL
3654   }
3655 }
3656 
3657 void MacroAssembler::os_breakpoint() {
3658   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3659   // (e.g., MSVC can't call ps() otherwise)
3660   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3661 }
3662 
3663 void MacroAssembler::unimplemented(const char* what) {
3664   const char* buf = NULL;
3665   {
3666     ResourceMark rm;
3667     stringStream ss;
3668     ss.print("unimplemented: %s", what);
3669     buf = code_string(ss.as_string());
3670   }
3671   stop(buf);
3672 }
3673 
3674 #ifdef _LP64
3675 #define XSTATE_BV 0x200
3676 #endif
3677 
3678 void MacroAssembler::pop_CPU_state() {
3679   pop_FPU_state();
3680   pop_IU_state();
3681 }
3682 
3683 void MacroAssembler::pop_FPU_state() {
3684 #ifndef _LP64
3685   frstor(Address(rsp, 0));
3686 #else
3687   fxrstor(Address(rsp, 0));
3688 #endif
3689   addptr(rsp, FPUStateSizeInWords * wordSize);
3690 }
3691 
3692 void MacroAssembler::pop_IU_state() {
3693   popa();
3694   LP64_ONLY(addq(rsp, 8));
3695   popf();
3696 }
3697 
3698 // Save Integer and Float state
3699 // Warning: Stack must be 16 byte aligned (64bit)
3700 void MacroAssembler::push_CPU_state() {
3701   push_IU_state();
3702   push_FPU_state();
3703 }
3704 
3705 void MacroAssembler::push_FPU_state() {
3706   subptr(rsp, FPUStateSizeInWords * wordSize);
3707 #ifndef _LP64
3708   fnsave(Address(rsp, 0));
3709   fwait();
3710 #else
3711   fxsave(Address(rsp, 0));
3712 #endif // LP64
3713 }
3714 
3715 void MacroAssembler::push_IU_state() {
3716   // Push flags first because pusha kills them
3717   pushf();
3718   // Make sure rsp stays 16-byte aligned
3719   LP64_ONLY(subq(rsp, 8));
3720   pusha();
3721 }
3722 
3723 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3724   if (!java_thread->is_valid()) {
3725     java_thread = rdi;
3726     get_thread(java_thread);
3727   }
3728   // we must set sp to zero to clear frame
3729   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3730   if (clear_fp) {
3731     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3732   }
3733 
3734   // Always clear the pc because it could have been set by make_walkable()
3735   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3736 
3737   vzeroupper();
3738 }
3739 
3740 void MacroAssembler::restore_rax(Register tmp) {
3741   if (tmp == noreg) pop(rax);
3742   else if (tmp != rax) mov(rax, tmp);
3743 }
3744 
3745 void MacroAssembler::round_to(Register reg, int modulus) {
3746   addptr(reg, modulus - 1);
3747   andptr(reg, -modulus);
3748 }
3749 
3750 void MacroAssembler::save_rax(Register tmp) {
3751   if (tmp == noreg) push(rax);
3752   else if (tmp != rax) mov(tmp, rax);
3753 }
3754 
3755 // Write serialization page so VM thread can do a pseudo remote membar.
3756 // We use the current thread pointer to calculate a thread specific
3757 // offset to write to within the page. This minimizes bus traffic
3758 // due to cache line collision.
3759 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3760   movl(tmp, thread);
3761   shrl(tmp, os::get_serialize_page_shift_count());
3762   andl(tmp, (os::vm_page_size() - sizeof(int)));
3763 
3764   Address index(noreg, tmp, Address::times_1);
3765   ExternalAddress page(os::get_memory_serialize_page());
3766 
3767   // Size of store must match masking code above
3768   movl(as_Address(ArrayAddress(page, index)), tmp);
3769 }
3770 
3771 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3772   if (SafepointMechanism::uses_thread_local_poll()) {
3773 #ifdef _LP64
3774     assert(thread_reg == r15_thread, "should be");
3775 #else
3776     if (thread_reg == noreg) {
3777       thread_reg = temp_reg;
3778       get_thread(thread_reg);
3779     }
3780 #endif
3781     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3782     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3783   } else {
3784     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3785         SafepointSynchronize::_not_synchronized);
3786     jcc(Assembler::notEqual, slow_path);
3787   }
3788 }
3789 
3790 // Calls to C land
3791 //
3792 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3793 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3794 // has to be reset to 0. This is required to allow proper stack traversal.
3795 void MacroAssembler::set_last_Java_frame(Register java_thread,
3796                                          Register last_java_sp,
3797                                          Register last_java_fp,
3798                                          address  last_java_pc) {
3799   vzeroupper();
3800   // determine java_thread register
3801   if (!java_thread->is_valid()) {
3802     java_thread = rdi;
3803     get_thread(java_thread);
3804   }
3805   // determine last_java_sp register
3806   if (!last_java_sp->is_valid()) {
3807     last_java_sp = rsp;
3808   }
3809 
3810   // last_java_fp is optional
3811 
3812   if (last_java_fp->is_valid()) {
3813     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3814   }
3815 
3816   // last_java_pc is optional
3817 
3818   if (last_java_pc != NULL) {
3819     lea(Address(java_thread,
3820                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3821         InternalAddress(last_java_pc));
3822 
3823   }
3824   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3825 }
3826 
3827 void MacroAssembler::shlptr(Register dst, int imm8) {
3828   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3829 }
3830 
3831 void MacroAssembler::shrptr(Register dst, int imm8) {
3832   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3833 }
3834 
3835 void MacroAssembler::sign_extend_byte(Register reg) {
3836   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3837     movsbl(reg, reg); // movsxb
3838   } else {
3839     shll(reg, 24);
3840     sarl(reg, 24);
3841   }
3842 }
3843 
3844 void MacroAssembler::sign_extend_short(Register reg) {
3845   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3846     movswl(reg, reg); // movsxw
3847   } else {
3848     shll(reg, 16);
3849     sarl(reg, 16);
3850   }
3851 }
3852 
3853 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3854   assert(reachable(src), "Address should be reachable");
3855   testl(dst, as_Address(src));
3856 }
3857 
3858 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3859   int dst_enc = dst->encoding();
3860   int src_enc = src->encoding();
3861   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3862     Assembler::pcmpeqb(dst, src);
3863   } else if ((dst_enc < 16) && (src_enc < 16)) {
3864     Assembler::pcmpeqb(dst, src);
3865   } else if (src_enc < 16) {
3866     subptr(rsp, 64);
3867     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3868     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3869     Assembler::pcmpeqb(xmm0, src);
3870     movdqu(dst, xmm0);
3871     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3872     addptr(rsp, 64);
3873   } else if (dst_enc < 16) {
3874     subptr(rsp, 64);
3875     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3876     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3877     Assembler::pcmpeqb(dst, xmm0);
3878     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3879     addptr(rsp, 64);
3880   } else {
3881     subptr(rsp, 64);
3882     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3883     subptr(rsp, 64);
3884     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3885     movdqu(xmm0, src);
3886     movdqu(xmm1, dst);
3887     Assembler::pcmpeqb(xmm1, xmm0);
3888     movdqu(dst, xmm1);
3889     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3890     addptr(rsp, 64);
3891     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3892     addptr(rsp, 64);
3893   }
3894 }
3895 
3896 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3897   int dst_enc = dst->encoding();
3898   int src_enc = src->encoding();
3899   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3900     Assembler::pcmpeqw(dst, src);
3901   } else if ((dst_enc < 16) && (src_enc < 16)) {
3902     Assembler::pcmpeqw(dst, src);
3903   } else if (src_enc < 16) {
3904     subptr(rsp, 64);
3905     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3906     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3907     Assembler::pcmpeqw(xmm0, src);
3908     movdqu(dst, xmm0);
3909     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3910     addptr(rsp, 64);
3911   } else if (dst_enc < 16) {
3912     subptr(rsp, 64);
3913     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3914     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3915     Assembler::pcmpeqw(dst, xmm0);
3916     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3917     addptr(rsp, 64);
3918   } else {
3919     subptr(rsp, 64);
3920     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3921     subptr(rsp, 64);
3922     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3923     movdqu(xmm0, src);
3924     movdqu(xmm1, dst);
3925     Assembler::pcmpeqw(xmm1, xmm0);
3926     movdqu(dst, xmm1);
3927     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3928     addptr(rsp, 64);
3929     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3930     addptr(rsp, 64);
3931   }
3932 }
3933 
3934 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3935   int dst_enc = dst->encoding();
3936   if (dst_enc < 16) {
3937     Assembler::pcmpestri(dst, src, imm8);
3938   } else {
3939     subptr(rsp, 64);
3940     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3941     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3942     Assembler::pcmpestri(xmm0, src, imm8);
3943     movdqu(dst, xmm0);
3944     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3945     addptr(rsp, 64);
3946   }
3947 }
3948 
3949 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3950   int dst_enc = dst->encoding();
3951   int src_enc = src->encoding();
3952   if ((dst_enc < 16) && (src_enc < 16)) {
3953     Assembler::pcmpestri(dst, src, imm8);
3954   } else if (src_enc < 16) {
3955     subptr(rsp, 64);
3956     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3957     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3958     Assembler::pcmpestri(xmm0, src, imm8);
3959     movdqu(dst, xmm0);
3960     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3961     addptr(rsp, 64);
3962   } else if (dst_enc < 16) {
3963     subptr(rsp, 64);
3964     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3965     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3966     Assembler::pcmpestri(dst, xmm0, imm8);
3967     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3968     addptr(rsp, 64);
3969   } else {
3970     subptr(rsp, 64);
3971     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3972     subptr(rsp, 64);
3973     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3974     movdqu(xmm0, src);
3975     movdqu(xmm1, dst);
3976     Assembler::pcmpestri(xmm1, xmm0, imm8);
3977     movdqu(dst, xmm1);
3978     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3979     addptr(rsp, 64);
3980     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3981     addptr(rsp, 64);
3982   }
3983 }
3984 
3985 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3986   int dst_enc = dst->encoding();
3987   int src_enc = src->encoding();
3988   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3989     Assembler::pmovzxbw(dst, src);
3990   } else if ((dst_enc < 16) && (src_enc < 16)) {
3991     Assembler::pmovzxbw(dst, src);
3992   } else if (src_enc < 16) {
3993     subptr(rsp, 64);
3994     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3995     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3996     Assembler::pmovzxbw(xmm0, src);
3997     movdqu(dst, xmm0);
3998     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3999     addptr(rsp, 64);
4000   } else if (dst_enc < 16) {
4001     subptr(rsp, 64);
4002     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4003     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4004     Assembler::pmovzxbw(dst, xmm0);
4005     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4006     addptr(rsp, 64);
4007   } else {
4008     subptr(rsp, 64);
4009     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4010     subptr(rsp, 64);
4011     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4012     movdqu(xmm0, src);
4013     movdqu(xmm1, dst);
4014     Assembler::pmovzxbw(xmm1, xmm0);
4015     movdqu(dst, xmm1);
4016     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4017     addptr(rsp, 64);
4018     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4019     addptr(rsp, 64);
4020   }
4021 }
4022 
4023 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4024   int dst_enc = dst->encoding();
4025   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4026     Assembler::pmovzxbw(dst, src);
4027   } else if (dst_enc < 16) {
4028     Assembler::pmovzxbw(dst, src);
4029   } else {
4030     subptr(rsp, 64);
4031     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4032     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4033     Assembler::pmovzxbw(xmm0, src);
4034     movdqu(dst, xmm0);
4035     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4036     addptr(rsp, 64);
4037   }
4038 }
4039 
4040 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4041   int src_enc = src->encoding();
4042   if (src_enc < 16) {
4043     Assembler::pmovmskb(dst, src);
4044   } else {
4045     subptr(rsp, 64);
4046     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4047     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4048     Assembler::pmovmskb(dst, xmm0);
4049     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4050     addptr(rsp, 64);
4051   }
4052 }
4053 
4054 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4055   int dst_enc = dst->encoding();
4056   int src_enc = src->encoding();
4057   if ((dst_enc < 16) && (src_enc < 16)) {
4058     Assembler::ptest(dst, src);
4059   } else if (src_enc < 16) {
4060     subptr(rsp, 64);
4061     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4062     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4063     Assembler::ptest(xmm0, src);
4064     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4065     addptr(rsp, 64);
4066   } else if (dst_enc < 16) {
4067     subptr(rsp, 64);
4068     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4069     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4070     Assembler::ptest(dst, xmm0);
4071     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4072     addptr(rsp, 64);
4073   } else {
4074     subptr(rsp, 64);
4075     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4076     subptr(rsp, 64);
4077     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4078     movdqu(xmm0, src);
4079     movdqu(xmm1, dst);
4080     Assembler::ptest(xmm1, xmm0);
4081     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4082     addptr(rsp, 64);
4083     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4084     addptr(rsp, 64);
4085   }
4086 }
4087 
4088 void MacroAssembler::testq(Register dst, AddressLiteral src) {
4089   assert(reachable(src), "Address should be reachable");
4090   testq(dst, as_Address(src));
4091 }
4092 
4093 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4094   if (reachable(src)) {
4095     Assembler::sqrtsd(dst, as_Address(src));
4096   } else {
4097     lea(rscratch1, src);
4098     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4099   }
4100 }
4101 
4102 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4103   if (reachable(src)) {
4104     Assembler::sqrtss(dst, as_Address(src));
4105   } else {
4106     lea(rscratch1, src);
4107     Assembler::sqrtss(dst, Address(rscratch1, 0));
4108   }
4109 }
4110 
4111 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4112   if (reachable(src)) {
4113     Assembler::subsd(dst, as_Address(src));
4114   } else {
4115     lea(rscratch1, src);
4116     Assembler::subsd(dst, Address(rscratch1, 0));
4117   }
4118 }
4119 
4120 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4121   if (reachable(src)) {
4122     Assembler::subss(dst, as_Address(src));
4123   } else {
4124     lea(rscratch1, src);
4125     Assembler::subss(dst, Address(rscratch1, 0));
4126   }
4127 }
4128 
4129 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4130   if (reachable(src)) {
4131     Assembler::ucomisd(dst, as_Address(src));
4132   } else {
4133     lea(rscratch1, src);
4134     Assembler::ucomisd(dst, Address(rscratch1, 0));
4135   }
4136 }
4137 
4138 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4139   if (reachable(src)) {
4140     Assembler::ucomiss(dst, as_Address(src));
4141   } else {
4142     lea(rscratch1, src);
4143     Assembler::ucomiss(dst, Address(rscratch1, 0));
4144   }
4145 }
4146 
4147 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4148   // Used in sign-bit flipping with aligned address.
4149   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4150   if (reachable(src)) {
4151     Assembler::xorpd(dst, as_Address(src));
4152   } else {
4153     lea(rscratch1, src);
4154     Assembler::xorpd(dst, Address(rscratch1, 0));
4155   }
4156 }
4157 
4158 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4159   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4160     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4161   }
4162   else {
4163     Assembler::xorpd(dst, src);
4164   }
4165 }
4166 
4167 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4168   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4169     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4170   } else {
4171     Assembler::xorps(dst, src);
4172   }
4173 }
4174 
4175 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4176   // Used in sign-bit flipping with aligned address.
4177   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4178   if (reachable(src)) {
4179     Assembler::xorps(dst, as_Address(src));
4180   } else {
4181     lea(rscratch1, src);
4182     Assembler::xorps(dst, Address(rscratch1, 0));
4183   }
4184 }
4185 
4186 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4187   // Used in sign-bit flipping with aligned address.
4188   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4189   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4190   if (reachable(src)) {
4191     Assembler::pshufb(dst, as_Address(src));
4192   } else {
4193     lea(rscratch1, src);
4194     Assembler::pshufb(dst, Address(rscratch1, 0));
4195   }
4196 }
4197 
4198 // AVX 3-operands instructions
4199 
4200 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4201   if (reachable(src)) {
4202     vaddsd(dst, nds, as_Address(src));
4203   } else {
4204     lea(rscratch1, src);
4205     vaddsd(dst, nds, Address(rscratch1, 0));
4206   }
4207 }
4208 
4209 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4210   if (reachable(src)) {
4211     vaddss(dst, nds, as_Address(src));
4212   } else {
4213     lea(rscratch1, src);
4214     vaddss(dst, nds, Address(rscratch1, 0));
4215   }
4216 }
4217 
4218 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4219   int dst_enc = dst->encoding();
4220   int nds_enc = nds->encoding();
4221   int src_enc = src->encoding();
4222   if ((dst_enc < 16) && (nds_enc < 16)) {
4223     vandps(dst, nds, negate_field, vector_len);
4224   } else if ((src_enc < 16) && (dst_enc < 16)) {
4225     evmovdqul(src, nds, Assembler::AVX_512bit);
4226     vandps(dst, src, negate_field, vector_len);
4227   } else if (src_enc < 16) {
4228     evmovdqul(src, nds, Assembler::AVX_512bit);
4229     vandps(src, src, negate_field, vector_len);
4230     evmovdqul(dst, src, Assembler::AVX_512bit);
4231   } else if (dst_enc < 16) {
4232     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4233     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4234     vandps(dst, xmm0, negate_field, vector_len);
4235     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4236   } else {
4237     if (src_enc != dst_enc) {
4238       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4239       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4240       vandps(xmm0, xmm0, negate_field, vector_len);
4241       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4242       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4243     } else {
4244       subptr(rsp, 64);
4245       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4246       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4247       vandps(xmm0, xmm0, negate_field, vector_len);
4248       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4249       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4250       addptr(rsp, 64);
4251     }
4252   }
4253 }
4254 
4255 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4256   int dst_enc = dst->encoding();
4257   int nds_enc = nds->encoding();
4258   int src_enc = src->encoding();
4259   if ((dst_enc < 16) && (nds_enc < 16)) {
4260     vandpd(dst, nds, negate_field, vector_len);
4261   } else if ((src_enc < 16) && (dst_enc < 16)) {
4262     evmovdqul(src, nds, Assembler::AVX_512bit);
4263     vandpd(dst, src, negate_field, vector_len);
4264   } else if (src_enc < 16) {
4265     evmovdqul(src, nds, Assembler::AVX_512bit);
4266     vandpd(src, src, negate_field, vector_len);
4267     evmovdqul(dst, src, Assembler::AVX_512bit);
4268   } else if (dst_enc < 16) {
4269     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4270     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4271     vandpd(dst, xmm0, negate_field, vector_len);
4272     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4273   } else {
4274     if (src_enc != dst_enc) {
4275       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4276       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4277       vandpd(xmm0, xmm0, negate_field, vector_len);
4278       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4279       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4280     } else {
4281       subptr(rsp, 64);
4282       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4283       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4284       vandpd(xmm0, xmm0, negate_field, vector_len);
4285       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4286       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4287       addptr(rsp, 64);
4288     }
4289   }
4290 }
4291 
4292 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4293   int dst_enc = dst->encoding();
4294   int nds_enc = nds->encoding();
4295   int src_enc = src->encoding();
4296   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4297     Assembler::vpaddb(dst, nds, src, vector_len);
4298   } else if ((dst_enc < 16) && (src_enc < 16)) {
4299     Assembler::vpaddb(dst, dst, src, vector_len);
4300   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4301     // use nds as scratch for src
4302     evmovdqul(nds, src, Assembler::AVX_512bit);
4303     Assembler::vpaddb(dst, dst, nds, vector_len);
4304   } else if ((src_enc < 16) && (nds_enc < 16)) {
4305     // use nds as scratch for dst
4306     evmovdqul(nds, dst, Assembler::AVX_512bit);
4307     Assembler::vpaddb(nds, nds, src, vector_len);
4308     evmovdqul(dst, nds, Assembler::AVX_512bit);
4309   } else if (dst_enc < 16) {
4310     // use nds as scatch for xmm0 to hold src
4311     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4312     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4313     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4314     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4315   } else {
4316     // worse case scenario, all regs are in the upper bank
4317     subptr(rsp, 64);
4318     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4319     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4320     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4321     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4322     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4323     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4324     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4325     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4326     addptr(rsp, 64);
4327   }
4328 }
4329 
4330 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4331   int dst_enc = dst->encoding();
4332   int nds_enc = nds->encoding();
4333   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4334     Assembler::vpaddb(dst, nds, src, vector_len);
4335   } else if (dst_enc < 16) {
4336     Assembler::vpaddb(dst, dst, src, vector_len);
4337   } else if (nds_enc < 16) {
4338     // implies dst_enc in upper bank with src as scratch
4339     evmovdqul(nds, dst, Assembler::AVX_512bit);
4340     Assembler::vpaddb(nds, nds, src, vector_len);
4341     evmovdqul(dst, nds, Assembler::AVX_512bit);
4342   } else {
4343     // worse case scenario, all regs in upper bank
4344     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4345     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4346     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4347     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4348   }
4349 }
4350 
4351 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4352   int dst_enc = dst->encoding();
4353   int nds_enc = nds->encoding();
4354   int src_enc = src->encoding();
4355   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4356     Assembler::vpaddw(dst, nds, src, vector_len);
4357   } else if ((dst_enc < 16) && (src_enc < 16)) {
4358     Assembler::vpaddw(dst, dst, src, vector_len);
4359   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4360     // use nds as scratch for src
4361     evmovdqul(nds, src, Assembler::AVX_512bit);
4362     Assembler::vpaddw(dst, dst, nds, vector_len);
4363   } else if ((src_enc < 16) && (nds_enc < 16)) {
4364     // use nds as scratch for dst
4365     evmovdqul(nds, dst, Assembler::AVX_512bit);
4366     Assembler::vpaddw(nds, nds, src, vector_len);
4367     evmovdqul(dst, nds, Assembler::AVX_512bit);
4368   } else if (dst_enc < 16) {
4369     // use nds as scatch for xmm0 to hold src
4370     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4371     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4372     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4373     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4374   } else {
4375     // worse case scenario, all regs are in the upper bank
4376     subptr(rsp, 64);
4377     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4378     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4379     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4380     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4381     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4382     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4383     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4384     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4385     addptr(rsp, 64);
4386   }
4387 }
4388 
4389 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4390   int dst_enc = dst->encoding();
4391   int nds_enc = nds->encoding();
4392   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4393     Assembler::vpaddw(dst, nds, src, vector_len);
4394   } else if (dst_enc < 16) {
4395     Assembler::vpaddw(dst, dst, src, vector_len);
4396   } else if (nds_enc < 16) {
4397     // implies dst_enc in upper bank with src as scratch
4398     evmovdqul(nds, dst, Assembler::AVX_512bit);
4399     Assembler::vpaddw(nds, nds, src, vector_len);
4400     evmovdqul(dst, nds, Assembler::AVX_512bit);
4401   } else {
4402     // worse case scenario, all regs in upper bank
4403     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4404     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4405     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4406     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4407   }
4408 }
4409 
4410 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4411   if (reachable(src)) {
4412     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4413   } else {
4414     lea(rscratch1, src);
4415     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4416   }
4417 }
4418 
4419 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4420   int dst_enc = dst->encoding();
4421   int src_enc = src->encoding();
4422   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4423     Assembler::vpbroadcastw(dst, src);
4424   } else if ((dst_enc < 16) && (src_enc < 16)) {
4425     Assembler::vpbroadcastw(dst, src);
4426   } else if (src_enc < 16) {
4427     subptr(rsp, 64);
4428     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4429     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4430     Assembler::vpbroadcastw(xmm0, src);
4431     movdqu(dst, xmm0);
4432     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4433     addptr(rsp, 64);
4434   } else if (dst_enc < 16) {
4435     subptr(rsp, 64);
4436     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4437     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4438     Assembler::vpbroadcastw(dst, xmm0);
4439     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4440     addptr(rsp, 64);
4441   } else {
4442     subptr(rsp, 64);
4443     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4444     subptr(rsp, 64);
4445     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4446     movdqu(xmm0, src);
4447     movdqu(xmm1, dst);
4448     Assembler::vpbroadcastw(xmm1, xmm0);
4449     movdqu(dst, xmm1);
4450     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4451     addptr(rsp, 64);
4452     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4453     addptr(rsp, 64);
4454   }
4455 }
4456 
4457 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4458   int dst_enc = dst->encoding();
4459   int nds_enc = nds->encoding();
4460   int src_enc = src->encoding();
4461   assert(dst_enc == nds_enc, "");
4462   if ((dst_enc < 16) && (src_enc < 16)) {
4463     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4464   } else if (src_enc < 16) {
4465     subptr(rsp, 64);
4466     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4467     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4468     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4469     movdqu(dst, xmm0);
4470     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4471     addptr(rsp, 64);
4472   } else if (dst_enc < 16) {
4473     subptr(rsp, 64);
4474     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4475     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4476     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4477     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4478     addptr(rsp, 64);
4479   } else {
4480     subptr(rsp, 64);
4481     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4482     subptr(rsp, 64);
4483     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4484     movdqu(xmm0, src);
4485     movdqu(xmm1, dst);
4486     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4487     movdqu(dst, xmm1);
4488     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4489     addptr(rsp, 64);
4490     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4491     addptr(rsp, 64);
4492   }
4493 }
4494 
4495 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4496   int dst_enc = dst->encoding();
4497   int nds_enc = nds->encoding();
4498   int src_enc = src->encoding();
4499   assert(dst_enc == nds_enc, "");
4500   if ((dst_enc < 16) && (src_enc < 16)) {
4501     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4502   } else if (src_enc < 16) {
4503     subptr(rsp, 64);
4504     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4505     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4506     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4507     movdqu(dst, xmm0);
4508     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4509     addptr(rsp, 64);
4510   } else if (dst_enc < 16) {
4511     subptr(rsp, 64);
4512     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4513     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4514     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4515     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4516     addptr(rsp, 64);
4517   } else {
4518     subptr(rsp, 64);
4519     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4520     subptr(rsp, 64);
4521     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4522     movdqu(xmm0, src);
4523     movdqu(xmm1, dst);
4524     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4525     movdqu(dst, xmm1);
4526     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4527     addptr(rsp, 64);
4528     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4529     addptr(rsp, 64);
4530   }
4531 }
4532 
4533 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4534   int dst_enc = dst->encoding();
4535   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4536     Assembler::vpmovzxbw(dst, src, vector_len);
4537   } else if (dst_enc < 16) {
4538     Assembler::vpmovzxbw(dst, src, vector_len);
4539   } else {
4540     subptr(rsp, 64);
4541     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4542     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4543     Assembler::vpmovzxbw(xmm0, src, vector_len);
4544     movdqu(dst, xmm0);
4545     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4546     addptr(rsp, 64);
4547   }
4548 }
4549 
4550 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4551   int src_enc = src->encoding();
4552   if (src_enc < 16) {
4553     Assembler::vpmovmskb(dst, src);
4554   } else {
4555     subptr(rsp, 64);
4556     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4557     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4558     Assembler::vpmovmskb(dst, xmm0);
4559     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4560     addptr(rsp, 64);
4561   }
4562 }
4563 
4564 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4565   int dst_enc = dst->encoding();
4566   int nds_enc = nds->encoding();
4567   int src_enc = src->encoding();
4568   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4569     Assembler::vpmullw(dst, nds, src, vector_len);
4570   } else if ((dst_enc < 16) && (src_enc < 16)) {
4571     Assembler::vpmullw(dst, dst, src, vector_len);
4572   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4573     // use nds as scratch for src
4574     evmovdqul(nds, src, Assembler::AVX_512bit);
4575     Assembler::vpmullw(dst, dst, nds, vector_len);
4576   } else if ((src_enc < 16) && (nds_enc < 16)) {
4577     // use nds as scratch for dst
4578     evmovdqul(nds, dst, Assembler::AVX_512bit);
4579     Assembler::vpmullw(nds, nds, src, vector_len);
4580     evmovdqul(dst, nds, Assembler::AVX_512bit);
4581   } else if (dst_enc < 16) {
4582     // use nds as scatch for xmm0 to hold src
4583     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4584     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4585     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4586     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4587   } else {
4588     // worse case scenario, all regs are in the upper bank
4589     subptr(rsp, 64);
4590     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4591     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4592     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4593     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4594     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4595     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4596     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4597     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4598     addptr(rsp, 64);
4599   }
4600 }
4601 
4602 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4603   int dst_enc = dst->encoding();
4604   int nds_enc = nds->encoding();
4605   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4606     Assembler::vpmullw(dst, nds, src, vector_len);
4607   } else if (dst_enc < 16) {
4608     Assembler::vpmullw(dst, dst, src, vector_len);
4609   } else if (nds_enc < 16) {
4610     // implies dst_enc in upper bank with src as scratch
4611     evmovdqul(nds, dst, Assembler::AVX_512bit);
4612     Assembler::vpmullw(nds, nds, src, vector_len);
4613     evmovdqul(dst, nds, Assembler::AVX_512bit);
4614   } else {
4615     // worse case scenario, all regs in upper bank
4616     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4617     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4618     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4619     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4620   }
4621 }
4622 
4623 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4624   int dst_enc = dst->encoding();
4625   int nds_enc = nds->encoding();
4626   int src_enc = src->encoding();
4627   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4628     Assembler::vpsubb(dst, nds, src, vector_len);
4629   } else if ((dst_enc < 16) && (src_enc < 16)) {
4630     Assembler::vpsubb(dst, dst, src, vector_len);
4631   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4632     // use nds as scratch for src
4633     evmovdqul(nds, src, Assembler::AVX_512bit);
4634     Assembler::vpsubb(dst, dst, nds, vector_len);
4635   } else if ((src_enc < 16) && (nds_enc < 16)) {
4636     // use nds as scratch for dst
4637     evmovdqul(nds, dst, Assembler::AVX_512bit);
4638     Assembler::vpsubb(nds, nds, src, vector_len);
4639     evmovdqul(dst, nds, Assembler::AVX_512bit);
4640   } else if (dst_enc < 16) {
4641     // use nds as scatch for xmm0 to hold src
4642     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4643     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4644     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4645     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4646   } else {
4647     // worse case scenario, all regs are in the upper bank
4648     subptr(rsp, 64);
4649     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4650     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4651     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4652     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4653     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4654     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4655     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4656     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4657     addptr(rsp, 64);
4658   }
4659 }
4660 
4661 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4662   int dst_enc = dst->encoding();
4663   int nds_enc = nds->encoding();
4664   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4665     Assembler::vpsubb(dst, nds, src, vector_len);
4666   } else if (dst_enc < 16) {
4667     Assembler::vpsubb(dst, dst, src, vector_len);
4668   } else if (nds_enc < 16) {
4669     // implies dst_enc in upper bank with src as scratch
4670     evmovdqul(nds, dst, Assembler::AVX_512bit);
4671     Assembler::vpsubb(nds, nds, src, vector_len);
4672     evmovdqul(dst, nds, Assembler::AVX_512bit);
4673   } else {
4674     // worse case scenario, all regs in upper bank
4675     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4676     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4677     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4678     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4679   }
4680 }
4681 
4682 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4683   int dst_enc = dst->encoding();
4684   int nds_enc = nds->encoding();
4685   int src_enc = src->encoding();
4686   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4687     Assembler::vpsubw(dst, nds, src, vector_len);
4688   } else if ((dst_enc < 16) && (src_enc < 16)) {
4689     Assembler::vpsubw(dst, dst, src, vector_len);
4690   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4691     // use nds as scratch for src
4692     evmovdqul(nds, src, Assembler::AVX_512bit);
4693     Assembler::vpsubw(dst, dst, nds, vector_len);
4694   } else if ((src_enc < 16) && (nds_enc < 16)) {
4695     // use nds as scratch for dst
4696     evmovdqul(nds, dst, Assembler::AVX_512bit);
4697     Assembler::vpsubw(nds, nds, src, vector_len);
4698     evmovdqul(dst, nds, Assembler::AVX_512bit);
4699   } else if (dst_enc < 16) {
4700     // use nds as scatch for xmm0 to hold src
4701     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4702     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4703     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4704     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4705   } else {
4706     // worse case scenario, all regs are in the upper bank
4707     subptr(rsp, 64);
4708     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4709     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4710     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4711     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4712     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4713     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4714     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4715     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4716     addptr(rsp, 64);
4717   }
4718 }
4719 
4720 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4721   int dst_enc = dst->encoding();
4722   int nds_enc = nds->encoding();
4723   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4724     Assembler::vpsubw(dst, nds, src, vector_len);
4725   } else if (dst_enc < 16) {
4726     Assembler::vpsubw(dst, dst, src, vector_len);
4727   } else if (nds_enc < 16) {
4728     // implies dst_enc in upper bank with src as scratch
4729     evmovdqul(nds, dst, Assembler::AVX_512bit);
4730     Assembler::vpsubw(nds, nds, src, vector_len);
4731     evmovdqul(dst, nds, Assembler::AVX_512bit);
4732   } else {
4733     // worse case scenario, all regs in upper bank
4734     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4735     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4736     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4737     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4738   }
4739 }
4740 
4741 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4742   int dst_enc = dst->encoding();
4743   int nds_enc = nds->encoding();
4744   int shift_enc = shift->encoding();
4745   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4746     Assembler::vpsraw(dst, nds, shift, vector_len);
4747   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4748     Assembler::vpsraw(dst, dst, shift, vector_len);
4749   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4750     // use nds_enc as scratch with shift
4751     evmovdqul(nds, shift, Assembler::AVX_512bit);
4752     Assembler::vpsraw(dst, dst, nds, vector_len);
4753   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4754     // use nds as scratch with dst
4755     evmovdqul(nds, dst, Assembler::AVX_512bit);
4756     Assembler::vpsraw(nds, nds, shift, vector_len);
4757     evmovdqul(dst, nds, Assembler::AVX_512bit);
4758   } else if (dst_enc < 16) {
4759     // use nds to save a copy of xmm0 and hold shift
4760     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4761     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4762     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4763     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4764   } else if (nds_enc < 16) {
4765     // use nds as dest as temps
4766     evmovdqul(nds, dst, Assembler::AVX_512bit);
4767     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4768     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4769     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4770     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4771     evmovdqul(dst, nds, Assembler::AVX_512bit);
4772   } else {
4773     // worse case scenario, all regs are in the upper bank
4774     subptr(rsp, 64);
4775     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4776     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4777     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4778     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4779     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4780     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4781     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4782     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4783     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4784     addptr(rsp, 64);
4785   }
4786 }
4787 
4788 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4789   int dst_enc = dst->encoding();
4790   int nds_enc = nds->encoding();
4791   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4792     Assembler::vpsraw(dst, nds, shift, vector_len);
4793   } else if (dst_enc < 16) {
4794     Assembler::vpsraw(dst, dst, shift, vector_len);
4795   } else if (nds_enc < 16) {
4796     // use nds as scratch
4797     evmovdqul(nds, dst, Assembler::AVX_512bit);
4798     Assembler::vpsraw(nds, nds, shift, vector_len);
4799     evmovdqul(dst, nds, Assembler::AVX_512bit);
4800   } else {
4801     // use nds as scratch for xmm0
4802     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4803     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4804     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4805     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4806   }
4807 }
4808 
4809 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4810   int dst_enc = dst->encoding();
4811   int nds_enc = nds->encoding();
4812   int shift_enc = shift->encoding();
4813   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4814     Assembler::vpsrlw(dst, nds, shift, vector_len);
4815   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4816     Assembler::vpsrlw(dst, dst, shift, vector_len);
4817   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4818     // use nds_enc as scratch with shift
4819     evmovdqul(nds, shift, Assembler::AVX_512bit);
4820     Assembler::vpsrlw(dst, dst, nds, vector_len);
4821   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4822     // use nds as scratch with dst
4823     evmovdqul(nds, dst, Assembler::AVX_512bit);
4824     Assembler::vpsrlw(nds, nds, shift, vector_len);
4825     evmovdqul(dst, nds, Assembler::AVX_512bit);
4826   } else if (dst_enc < 16) {
4827     // use nds to save a copy of xmm0 and hold shift
4828     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4829     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4830     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4831     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4832   } else if (nds_enc < 16) {
4833     // use nds as dest as temps
4834     evmovdqul(nds, dst, Assembler::AVX_512bit);
4835     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4836     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4837     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4838     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4839     evmovdqul(dst, nds, Assembler::AVX_512bit);
4840   } else {
4841     // worse case scenario, all regs are in the upper bank
4842     subptr(rsp, 64);
4843     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4844     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4845     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4846     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4847     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4848     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4849     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4850     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4851     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4852     addptr(rsp, 64);
4853   }
4854 }
4855 
4856 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4857   int dst_enc = dst->encoding();
4858   int nds_enc = nds->encoding();
4859   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4860     Assembler::vpsrlw(dst, nds, shift, vector_len);
4861   } else if (dst_enc < 16) {
4862     Assembler::vpsrlw(dst, dst, shift, vector_len);
4863   } else if (nds_enc < 16) {
4864     // use nds as scratch
4865     evmovdqul(nds, dst, Assembler::AVX_512bit);
4866     Assembler::vpsrlw(nds, nds, shift, vector_len);
4867     evmovdqul(dst, nds, Assembler::AVX_512bit);
4868   } else {
4869     // use nds as scratch for xmm0
4870     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4871     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4872     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4873     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4874   }
4875 }
4876 
4877 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4878   int dst_enc = dst->encoding();
4879   int nds_enc = nds->encoding();
4880   int shift_enc = shift->encoding();
4881   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4882     Assembler::vpsllw(dst, nds, shift, vector_len);
4883   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4884     Assembler::vpsllw(dst, dst, shift, vector_len);
4885   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4886     // use nds_enc as scratch with shift
4887     evmovdqul(nds, shift, Assembler::AVX_512bit);
4888     Assembler::vpsllw(dst, dst, nds, vector_len);
4889   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4890     // use nds as scratch with dst
4891     evmovdqul(nds, dst, Assembler::AVX_512bit);
4892     Assembler::vpsllw(nds, nds, shift, vector_len);
4893     evmovdqul(dst, nds, Assembler::AVX_512bit);
4894   } else if (dst_enc < 16) {
4895     // use nds to save a copy of xmm0 and hold shift
4896     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4897     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4898     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4899     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4900   } else if (nds_enc < 16) {
4901     // use nds as dest as temps
4902     evmovdqul(nds, dst, Assembler::AVX_512bit);
4903     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4904     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4905     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4906     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4907     evmovdqul(dst, nds, Assembler::AVX_512bit);
4908   } else {
4909     // worse case scenario, all regs are in the upper bank
4910     subptr(rsp, 64);
4911     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4912     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4913     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4914     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4915     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4916     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4917     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4918     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4919     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4920     addptr(rsp, 64);
4921   }
4922 }
4923 
4924 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4925   int dst_enc = dst->encoding();
4926   int nds_enc = nds->encoding();
4927   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4928     Assembler::vpsllw(dst, nds, shift, vector_len);
4929   } else if (dst_enc < 16) {
4930     Assembler::vpsllw(dst, dst, shift, vector_len);
4931   } else if (nds_enc < 16) {
4932     // use nds as scratch
4933     evmovdqul(nds, dst, Assembler::AVX_512bit);
4934     Assembler::vpsllw(nds, nds, shift, vector_len);
4935     evmovdqul(dst, nds, Assembler::AVX_512bit);
4936   } else {
4937     // use nds as scratch for xmm0
4938     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4939     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4940     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4941     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4942   }
4943 }
4944 
4945 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4946   int dst_enc = dst->encoding();
4947   int src_enc = src->encoding();
4948   if ((dst_enc < 16) && (src_enc < 16)) {
4949     Assembler::vptest(dst, src);
4950   } else if (src_enc < 16) {
4951     subptr(rsp, 64);
4952     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4953     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4954     Assembler::vptest(xmm0, src);
4955     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4956     addptr(rsp, 64);
4957   } else if (dst_enc < 16) {
4958     subptr(rsp, 64);
4959     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4960     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4961     Assembler::vptest(dst, xmm0);
4962     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4963     addptr(rsp, 64);
4964   } else {
4965     subptr(rsp, 64);
4966     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4967     subptr(rsp, 64);
4968     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4969     movdqu(xmm0, src);
4970     movdqu(xmm1, dst);
4971     Assembler::vptest(xmm1, xmm0);
4972     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4973     addptr(rsp, 64);
4974     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4975     addptr(rsp, 64);
4976   }
4977 }
4978 
4979 // This instruction exists within macros, ergo we cannot control its input
4980 // when emitted through those patterns.
4981 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4982   if (VM_Version::supports_avx512nobw()) {
4983     int dst_enc = dst->encoding();
4984     int src_enc = src->encoding();
4985     if (dst_enc == src_enc) {
4986       if (dst_enc < 16) {
4987         Assembler::punpcklbw(dst, src);
4988       } else {
4989         subptr(rsp, 64);
4990         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4991         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4992         Assembler::punpcklbw(xmm0, xmm0);
4993         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4994         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4995         addptr(rsp, 64);
4996       }
4997     } else {
4998       if ((src_enc < 16) && (dst_enc < 16)) {
4999         Assembler::punpcklbw(dst, src);
5000       } else if (src_enc < 16) {
5001         subptr(rsp, 64);
5002         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5003         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5004         Assembler::punpcklbw(xmm0, src);
5005         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5006         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5007         addptr(rsp, 64);
5008       } else if (dst_enc < 16) {
5009         subptr(rsp, 64);
5010         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5011         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5012         Assembler::punpcklbw(dst, xmm0);
5013         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5014         addptr(rsp, 64);
5015       } else {
5016         subptr(rsp, 64);
5017         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5018         subptr(rsp, 64);
5019         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5020         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5021         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5022         Assembler::punpcklbw(xmm0, xmm1);
5023         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5024         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5025         addptr(rsp, 64);
5026         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5027         addptr(rsp, 64);
5028       }
5029     }
5030   } else {
5031     Assembler::punpcklbw(dst, src);
5032   }
5033 }
5034 
5035 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5036   if (VM_Version::supports_avx512vl()) {
5037     Assembler::pshufd(dst, src, mode);
5038   } else {
5039     int dst_enc = dst->encoding();
5040     if (dst_enc < 16) {
5041       Assembler::pshufd(dst, src, mode);
5042     } else {
5043       subptr(rsp, 64);
5044       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5045       Assembler::pshufd(xmm0, src, mode);
5046       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5047       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5048       addptr(rsp, 64);
5049     }
5050   }
5051 }
5052 
5053 // This instruction exists within macros, ergo we cannot control its input
5054 // when emitted through those patterns.
5055 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5056   if (VM_Version::supports_avx512nobw()) {
5057     int dst_enc = dst->encoding();
5058     int src_enc = src->encoding();
5059     if (dst_enc == src_enc) {
5060       if (dst_enc < 16) {
5061         Assembler::pshuflw(dst, src, mode);
5062       } else {
5063         subptr(rsp, 64);
5064         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5066         Assembler::pshuflw(xmm0, xmm0, mode);
5067         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5068         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5069         addptr(rsp, 64);
5070       }
5071     } else {
5072       if ((src_enc < 16) && (dst_enc < 16)) {
5073         Assembler::pshuflw(dst, src, mode);
5074       } else if (src_enc < 16) {
5075         subptr(rsp, 64);
5076         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5078         Assembler::pshuflw(xmm0, src, mode);
5079         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5080         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5081         addptr(rsp, 64);
5082       } else if (dst_enc < 16) {
5083         subptr(rsp, 64);
5084         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5085         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5086         Assembler::pshuflw(dst, xmm0, mode);
5087         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5088         addptr(rsp, 64);
5089       } else {
5090         subptr(rsp, 64);
5091         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5092         subptr(rsp, 64);
5093         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5094         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5095         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5096         Assembler::pshuflw(xmm0, xmm1, mode);
5097         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5098         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5099         addptr(rsp, 64);
5100         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5101         addptr(rsp, 64);
5102       }
5103     }
5104   } else {
5105     Assembler::pshuflw(dst, src, mode);
5106   }
5107 }
5108 
5109 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5110   if (reachable(src)) {
5111     vandpd(dst, nds, as_Address(src), vector_len);
5112   } else {
5113     lea(rscratch1, src);
5114     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5115   }
5116 }
5117 
5118 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5119   if (reachable(src)) {
5120     vandps(dst, nds, as_Address(src), vector_len);
5121   } else {
5122     lea(rscratch1, src);
5123     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5124   }
5125 }
5126 
5127 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5128   if (reachable(src)) {
5129     vdivsd(dst, nds, as_Address(src));
5130   } else {
5131     lea(rscratch1, src);
5132     vdivsd(dst, nds, Address(rscratch1, 0));
5133   }
5134 }
5135 
5136 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5137   if (reachable(src)) {
5138     vdivss(dst, nds, as_Address(src));
5139   } else {
5140     lea(rscratch1, src);
5141     vdivss(dst, nds, Address(rscratch1, 0));
5142   }
5143 }
5144 
5145 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5146   if (reachable(src)) {
5147     vmulsd(dst, nds, as_Address(src));
5148   } else {
5149     lea(rscratch1, src);
5150     vmulsd(dst, nds, Address(rscratch1, 0));
5151   }
5152 }
5153 
5154 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5155   if (reachable(src)) {
5156     vmulss(dst, nds, as_Address(src));
5157   } else {
5158     lea(rscratch1, src);
5159     vmulss(dst, nds, Address(rscratch1, 0));
5160   }
5161 }
5162 
5163 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5164   if (reachable(src)) {
5165     vsubsd(dst, nds, as_Address(src));
5166   } else {
5167     lea(rscratch1, src);
5168     vsubsd(dst, nds, Address(rscratch1, 0));
5169   }
5170 }
5171 
5172 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5173   if (reachable(src)) {
5174     vsubss(dst, nds, as_Address(src));
5175   } else {
5176     lea(rscratch1, src);
5177     vsubss(dst, nds, Address(rscratch1, 0));
5178   }
5179 }
5180 
5181 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5182   int nds_enc = nds->encoding();
5183   int dst_enc = dst->encoding();
5184   bool dst_upper_bank = (dst_enc > 15);
5185   bool nds_upper_bank = (nds_enc > 15);
5186   if (VM_Version::supports_avx512novl() &&
5187       (nds_upper_bank || dst_upper_bank)) {
5188     if (dst_upper_bank) {
5189       subptr(rsp, 64);
5190       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5191       movflt(xmm0, nds);
5192       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5193       movflt(dst, xmm0);
5194       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5195       addptr(rsp, 64);
5196     } else {
5197       movflt(dst, nds);
5198       vxorps(dst, dst, src, Assembler::AVX_128bit);
5199     }
5200   } else {
5201     vxorps(dst, nds, src, Assembler::AVX_128bit);
5202   }
5203 }
5204 
5205 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5206   int nds_enc = nds->encoding();
5207   int dst_enc = dst->encoding();
5208   bool dst_upper_bank = (dst_enc > 15);
5209   bool nds_upper_bank = (nds_enc > 15);
5210   if (VM_Version::supports_avx512novl() &&
5211       (nds_upper_bank || dst_upper_bank)) {
5212     if (dst_upper_bank) {
5213       subptr(rsp, 64);
5214       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5215       movdbl(xmm0, nds);
5216       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5217       movdbl(dst, xmm0);
5218       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5219       addptr(rsp, 64);
5220     } else {
5221       movdbl(dst, nds);
5222       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5223     }
5224   } else {
5225     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5226   }
5227 }
5228 
5229 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5230   if (reachable(src)) {
5231     vxorpd(dst, nds, as_Address(src), vector_len);
5232   } else {
5233     lea(rscratch1, src);
5234     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5235   }
5236 }
5237 
5238 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5239   if (reachable(src)) {
5240     vxorps(dst, nds, as_Address(src), vector_len);
5241   } else {
5242     lea(rscratch1, src);
5243     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5244   }
5245 }
5246 
5247 
5248 void MacroAssembler::resolve_jobject(Register value,
5249                                      Register thread,
5250                                      Register tmp) {
5251   assert_different_registers(value, thread, tmp);
5252   Label done, not_weak;
5253   testptr(value, value);
5254   jcc(Assembler::zero, done);                // Use NULL as-is.
5255   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5256   jcc(Assembler::zero, not_weak);
5257   // Resolve jweak.
5258 #if INCLUDE_ALL_GCS
5259   if (UseLoadBarrier) {
5260     load_barrier(value, Address(value, -JNIHandles::weak_tag_value), false /* expand call */, LoadBarrierOnPhantomOopRef);
5261   } else
5262 #endif
5263   {
5264     movptr(value, Address(value, -JNIHandles::weak_tag_value));
5265   }
5266   verify_oop(value);
5267 #if INCLUDE_ALL_GCS
5268   if (UseG1GC) {
5269     g1_write_barrier_pre(noreg /* obj */,
5270                          value /* pre_val */,
5271                          thread /* thread */,
5272                          tmp /* tmp */,
5273                          true /* tosca_live */,
5274                          true /* expand_call */);
5275   }
5276 #endif // INCLUDE_ALL_GCS
5277   jmp(done);
5278   bind(not_weak);
5279   // Resolve (untagged) jobject.
5280   movptr(value, Address(value, 0));
5281   verify_oop(value);
5282   bind(done);
5283 }
5284 
5285 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5286   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5287   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5288   // The inverted mask is sign-extended
5289   andptr(possibly_jweak, inverted_jweak_mask);
5290 }
5291 
5292 //////////////////////////////////////////////////////////////////////////////////
5293 #if INCLUDE_ALL_GCS
5294 
5295 void MacroAssembler::g1_write_barrier_pre(Register obj,
5296                                           Register pre_val,
5297                                           Register thread,
5298                                           Register tmp,
5299                                           bool tosca_live,
5300                                           bool expand_call) {
5301 
5302   // If expand_call is true then we expand the call_VM_leaf macro
5303   // directly to skip generating the check by
5304   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5305 
5306 #ifdef _LP64
5307   assert(thread == r15_thread, "must be");
5308 #endif // _LP64
5309 
5310   Label done;
5311   Label runtime;
5312 
5313   assert(pre_val != noreg, "check this code");
5314 
5315   if (obj != noreg) {
5316     assert_different_registers(obj, pre_val, tmp);
5317     assert(pre_val != rax, "check this code");
5318   }
5319 
5320   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5321                                        SATBMarkQueue::byte_offset_of_active()));
5322   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5323                                        SATBMarkQueue::byte_offset_of_index()));
5324   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5325                                        SATBMarkQueue::byte_offset_of_buf()));
5326 
5327 
5328   // Is marking active?
5329   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5330     cmpl(in_progress, 0);
5331   } else {
5332     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5333     cmpb(in_progress, 0);
5334   }
5335   jcc(Assembler::equal, done);
5336 
5337   // Do we need to load the previous value?
5338   if (obj != noreg) {
5339     load_heap_oop(pre_val, Address(obj, 0));
5340   }
5341 
5342   // Is the previous value null?
5343   cmpptr(pre_val, (int32_t) NULL_WORD);
5344   jcc(Assembler::equal, done);
5345 
5346   // Can we store original value in the thread's buffer?
5347   // Is index == 0?
5348   // (The index field is typed as size_t.)
5349 
5350   movptr(tmp, index);                   // tmp := *index_adr
5351   cmpptr(tmp, 0);                       // tmp == 0?
5352   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5353 
5354   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5355   movptr(index, tmp);                   // *index_adr := tmp
5356   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5357 
5358   // Record the previous value
5359   movptr(Address(tmp, 0), pre_val);
5360   jmp(done);
5361 
5362   bind(runtime);
5363   // save the live input values
5364   if(tosca_live) push(rax);
5365 
5366   if (obj != noreg && obj != rax)
5367     push(obj);
5368 
5369   if (pre_val != rax)
5370     push(pre_val);
5371 
5372   // Calling the runtime using the regular call_VM_leaf mechanism generates
5373   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5374   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5375   //
5376   // If we care generating the pre-barrier without a frame (e.g. in the
5377   // intrinsified Reference.get() routine) then ebp might be pointing to
5378   // the caller frame and so this check will most likely fail at runtime.
5379   //
5380   // Expanding the call directly bypasses the generation of the check.
5381   // So when we do not have have a full interpreter frame on the stack
5382   // expand_call should be passed true.
5383 
5384   NOT_LP64( push(thread); )
5385 
5386   if (expand_call) {
5387     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5388     pass_arg1(this, thread);
5389     pass_arg0(this, pre_val);
5390     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5391   } else {
5392     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5393   }
5394 
5395   NOT_LP64( pop(thread); )
5396 
5397   // save the live input values
5398   if (pre_val != rax)
5399     pop(pre_val);
5400 
5401   if (obj != noreg && obj != rax)
5402     pop(obj);
5403 
5404   if(tosca_live) pop(rax);
5405 
5406   bind(done);
5407 }
5408 
5409 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5410                                            Register new_val,
5411                                            Register thread,
5412                                            Register tmp,
5413                                            Register tmp2) {
5414 #ifdef _LP64
5415   assert(thread == r15_thread, "must be");
5416 #endif // _LP64
5417 
5418   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5419                                        DirtyCardQueue::byte_offset_of_index()));
5420   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5421                                        DirtyCardQueue::byte_offset_of_buf()));
5422 
5423   CardTableModRefBS* ct =
5424     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5425   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5426 
5427   Label done;
5428   Label runtime;
5429 
5430   // Does store cross heap regions?
5431 
5432   movptr(tmp, store_addr);
5433   xorptr(tmp, new_val);
5434   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5435   jcc(Assembler::equal, done);
5436 
5437   // crosses regions, storing NULL?
5438 
5439   cmpptr(new_val, (int32_t) NULL_WORD);
5440   jcc(Assembler::equal, done);
5441 
5442   // storing region crossing non-NULL, is card already dirty?
5443 
5444   const Register card_addr = tmp;
5445   const Register cardtable = tmp2;
5446 
5447   movptr(card_addr, store_addr);
5448   shrptr(card_addr, CardTableModRefBS::card_shift);
5449   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5450   // a valid address and therefore is not properly handled by the relocation code.
5451   movptr(cardtable, (intptr_t)ct->byte_map_base);
5452   addptr(card_addr, cardtable);
5453 
5454   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5455   jcc(Assembler::equal, done);
5456 
5457   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5458   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5459   jcc(Assembler::equal, done);
5460 
5461 
5462   // storing a region crossing, non-NULL oop, card is clean.
5463   // dirty card and log.
5464 
5465   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5466 
5467   cmpl(queue_index, 0);
5468   jcc(Assembler::equal, runtime);
5469   subl(queue_index, wordSize);
5470   movptr(tmp2, buffer);
5471 #ifdef _LP64
5472   movslq(rscratch1, queue_index);
5473   addq(tmp2, rscratch1);
5474   movq(Address(tmp2, 0), card_addr);
5475 #else
5476   addl(tmp2, queue_index);
5477   movl(Address(tmp2, 0), card_addr);
5478 #endif
5479   jmp(done);
5480 
5481   bind(runtime);
5482   // save the live input values
5483   push(store_addr);
5484   push(new_val);
5485 #ifdef _LP64
5486   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5487 #else
5488   push(thread);
5489   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5490   pop(thread);
5491 #endif
5492   pop(new_val);
5493   pop(store_addr);
5494 
5495   bind(done);
5496 }
5497 
5498 #endif // INCLUDE_ALL_GCS
5499 //////////////////////////////////////////////////////////////////////////////////
5500 
5501 
5502 void MacroAssembler::store_check(Register obj, Address dst) {
5503   store_check(obj);
5504 }
5505 
5506 void MacroAssembler::store_check(Register obj) {
5507   // Does a store check for the oop in register obj. The content of
5508   // register obj is destroyed afterwards.
5509   BarrierSet* bs = Universe::heap()->barrier_set();
5510   assert(bs->kind() == BarrierSet::CardTableForRS ||
5511          bs->kind() == BarrierSet::CardTableExtension,
5512          "Wrong barrier set kind");
5513 
5514   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5515   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5516 
5517   shrptr(obj, CardTableModRefBS::card_shift);
5518 
5519   Address card_addr;
5520 
5521   // The calculation for byte_map_base is as follows:
5522   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5523   // So this essentially converts an address to a displacement and it will
5524   // never need to be relocated. On 64bit however the value may be too
5525   // large for a 32bit displacement.
5526   intptr_t disp = (intptr_t) ct->byte_map_base;
5527   if (is_simm32(disp)) {
5528     card_addr = Address(noreg, obj, Address::times_1, disp);
5529   } else {
5530     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5531     // displacement and done in a single instruction given favorable mapping and a
5532     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5533     // entry and that entry is not properly handled by the relocation code.
5534     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5535     Address index(noreg, obj, Address::times_1);
5536     card_addr = as_Address(ArrayAddress(cardtable, index));
5537   }
5538 
5539   int dirty = CardTableModRefBS::dirty_card_val();
5540   if (UseCondCardMark) {
5541     Label L_already_dirty;
5542     if (UseConcMarkSweepGC) {
5543       membar(Assembler::StoreLoad);
5544     }
5545     cmpb(card_addr, dirty);
5546     jcc(Assembler::equal, L_already_dirty);
5547     movb(card_addr, dirty);
5548     bind(L_already_dirty);
5549   } else {
5550     movb(card_addr, dirty);
5551   }
5552 }
5553 
5554 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5555   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5556 }
5557 
5558 // Force generation of a 4 byte immediate value even if it fits into 8bit
5559 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5560   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5561 }
5562 
5563 void MacroAssembler::subptr(Register dst, Register src) {
5564   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5565 }
5566 
5567 // C++ bool manipulation
5568 void MacroAssembler::testbool(Register dst) {
5569   if(sizeof(bool) == 1)
5570     testb(dst, 0xff);
5571   else if(sizeof(bool) == 2) {
5572     // testw implementation needed for two byte bools
5573     ShouldNotReachHere();
5574   } else if(sizeof(bool) == 4)
5575     testl(dst, dst);
5576   else
5577     // unsupported
5578     ShouldNotReachHere();
5579 }
5580 
5581 void MacroAssembler::testptr(Register dst, Register src) {
5582   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5583 }
5584 
5585 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5586 void MacroAssembler::tlab_allocate(Register obj,
5587                                    Register var_size_in_bytes,
5588                                    int con_size_in_bytes,
5589                                    Register t1,
5590                                    Register t2,
5591                                    Label& slow_case) {
5592   assert_different_registers(obj, t1, t2);
5593   assert_different_registers(obj, var_size_in_bytes, t1);
5594   Register end = t2;
5595   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5596 
5597   verify_tlab();
5598 
5599   NOT_LP64(get_thread(thread));
5600 
5601   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5602   if (var_size_in_bytes == noreg) {
5603     lea(end, Address(obj, con_size_in_bytes));
5604   } else {
5605     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5606   }
5607   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5608   jcc(Assembler::above, slow_case);
5609 
5610   // update the tlab top pointer
5611   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5612 
5613   // recover var_size_in_bytes if necessary
5614   if (var_size_in_bytes == end) {
5615     subptr(var_size_in_bytes, obj);
5616   }
5617   verify_tlab();
5618 }
5619 
5620 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5621 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5622   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5623   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5624   Label done;
5625 
5626   testptr(length_in_bytes, length_in_bytes);
5627   jcc(Assembler::zero, done);
5628 
5629   // initialize topmost word, divide index by 2, check if odd and test if zero
5630   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5631 #ifdef ASSERT
5632   {
5633     Label L;
5634     testptr(length_in_bytes, BytesPerWord - 1);
5635     jcc(Assembler::zero, L);
5636     stop("length must be a multiple of BytesPerWord");
5637     bind(L);
5638   }
5639 #endif
5640   Register index = length_in_bytes;
5641   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5642   if (UseIncDec) {
5643     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5644   } else {
5645     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5646     shrptr(index, 1);
5647   }
5648 #ifndef _LP64
5649   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5650   {
5651     Label even;
5652     // note: if index was a multiple of 8, then it cannot
5653     //       be 0 now otherwise it must have been 0 before
5654     //       => if it is even, we don't need to check for 0 again
5655     jcc(Assembler::carryClear, even);
5656     // clear topmost word (no jump would be needed if conditional assignment worked here)
5657     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5658     // index could be 0 now, must check again
5659     jcc(Assembler::zero, done);
5660     bind(even);
5661   }
5662 #endif // !_LP64
5663   // initialize remaining object fields: index is a multiple of 2 now
5664   {
5665     Label loop;
5666     bind(loop);
5667     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5668     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5669     decrement(index);
5670     jcc(Assembler::notZero, loop);
5671   }
5672 
5673   bind(done);
5674 }
5675 
5676 void MacroAssembler::incr_allocated_bytes(Register thread,
5677                                           Register var_size_in_bytes,
5678                                           int con_size_in_bytes,
5679                                           Register t1) {
5680   if (!thread->is_valid()) {
5681 #ifdef _LP64
5682     thread = r15_thread;
5683 #else
5684     assert(t1->is_valid(), "need temp reg");
5685     thread = t1;
5686     get_thread(thread);
5687 #endif
5688   }
5689 
5690 #ifdef _LP64
5691   if (var_size_in_bytes->is_valid()) {
5692     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5693   } else {
5694     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5695   }
5696 #else
5697   if (var_size_in_bytes->is_valid()) {
5698     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5699   } else {
5700     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5701   }
5702   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5703 #endif
5704 }
5705 
5706 // Look up the method for a megamorphic invokeinterface call.
5707 // The target method is determined by <intf_klass, itable_index>.
5708 // The receiver klass is in recv_klass.
5709 // On success, the result will be in method_result, and execution falls through.
5710 // On failure, execution transfers to the given label.
5711 void MacroAssembler::lookup_interface_method(Register recv_klass,
5712                                              Register intf_klass,
5713                                              RegisterOrConstant itable_index,
5714                                              Register method_result,
5715                                              Register scan_temp,
5716                                              Label& L_no_such_interface,
5717                                              bool return_method) {
5718   assert_different_registers(recv_klass, intf_klass, scan_temp);
5719   assert_different_registers(method_result, intf_klass, scan_temp);
5720   assert(recv_klass != method_result || !return_method,
5721          "recv_klass can be destroyed when method isn't needed");
5722 
5723   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5724          "caller must use same register for non-constant itable index as for method");
5725 
5726   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5727   int vtable_base = in_bytes(Klass::vtable_start_offset());
5728   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5729   int scan_step   = itableOffsetEntry::size() * wordSize;
5730   int vte_size    = vtableEntry::size_in_bytes();
5731   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5732   assert(vte_size == wordSize, "else adjust times_vte_scale");
5733 
5734   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5735 
5736   // %%% Could store the aligned, prescaled offset in the klassoop.
5737   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5738 
5739   if (return_method) {
5740     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5741     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5742     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5743   }
5744 
5745   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5746   //   if (scan->interface() == intf) {
5747   //     result = (klass + scan->offset() + itable_index);
5748   //   }
5749   // }
5750   Label search, found_method;
5751 
5752   for (int peel = 1; peel >= 0; peel--) {
5753     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5754     cmpptr(intf_klass, method_result);
5755 
5756     if (peel) {
5757       jccb(Assembler::equal, found_method);
5758     } else {
5759       jccb(Assembler::notEqual, search);
5760       // (invert the test to fall through to found_method...)
5761     }
5762 
5763     if (!peel)  break;
5764 
5765     bind(search);
5766 
5767     // Check that the previous entry is non-null.  A null entry means that
5768     // the receiver class doesn't implement the interface, and wasn't the
5769     // same as when the caller was compiled.
5770     testptr(method_result, method_result);
5771     jcc(Assembler::zero, L_no_such_interface);
5772     addptr(scan_temp, scan_step);
5773   }
5774 
5775   bind(found_method);
5776 
5777   if (return_method) {
5778     // Got a hit.
5779     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5780     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5781   }
5782 }
5783 
5784 
5785 // virtual method calling
5786 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5787                                            RegisterOrConstant vtable_index,
5788                                            Register method_result) {
5789   const int base = in_bytes(Klass::vtable_start_offset());
5790   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5791   Address vtable_entry_addr(recv_klass,
5792                             vtable_index, Address::times_ptr,
5793                             base + vtableEntry::method_offset_in_bytes());
5794   movptr(method_result, vtable_entry_addr);
5795 }
5796 
5797 
5798 void MacroAssembler::check_klass_subtype(Register sub_klass,
5799                            Register super_klass,
5800                            Register temp_reg,
5801                            Label& L_success) {
5802   Label L_failure;
5803   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5804   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5805   bind(L_failure);
5806 }
5807 
5808 
5809 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5810                                                    Register super_klass,
5811                                                    Register temp_reg,
5812                                                    Label* L_success,
5813                                                    Label* L_failure,
5814                                                    Label* L_slow_path,
5815                                         RegisterOrConstant super_check_offset) {
5816   assert_different_registers(sub_klass, super_klass, temp_reg);
5817   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5818   if (super_check_offset.is_register()) {
5819     assert_different_registers(sub_klass, super_klass,
5820                                super_check_offset.as_register());
5821   } else if (must_load_sco) {
5822     assert(temp_reg != noreg, "supply either a temp or a register offset");
5823   }
5824 
5825   Label L_fallthrough;
5826   int label_nulls = 0;
5827   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5828   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5829   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5830   assert(label_nulls <= 1, "at most one NULL in the batch");
5831 
5832   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5833   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5834   Address super_check_offset_addr(super_klass, sco_offset);
5835 
5836   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5837   // range of a jccb.  If this routine grows larger, reconsider at
5838   // least some of these.
5839 #define local_jcc(assembler_cond, label)                                \
5840   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5841   else                             jcc( assembler_cond, label) /*omit semi*/
5842 
5843   // Hacked jmp, which may only be used just before L_fallthrough.
5844 #define final_jmp(label)                                                \
5845   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5846   else                            jmp(label)                /*omit semi*/
5847 
5848   // If the pointers are equal, we are done (e.g., String[] elements).
5849   // This self-check enables sharing of secondary supertype arrays among
5850   // non-primary types such as array-of-interface.  Otherwise, each such
5851   // type would need its own customized SSA.
5852   // We move this check to the front of the fast path because many
5853   // type checks are in fact trivially successful in this manner,
5854   // so we get a nicely predicted branch right at the start of the check.
5855   cmpptr(sub_klass, super_klass);
5856   local_jcc(Assembler::equal, *L_success);
5857 
5858   // Check the supertype display:
5859   if (must_load_sco) {
5860     // Positive movl does right thing on LP64.
5861     movl(temp_reg, super_check_offset_addr);
5862     super_check_offset = RegisterOrConstant(temp_reg);
5863   }
5864   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5865   cmpptr(super_klass, super_check_addr); // load displayed supertype
5866 
5867   // This check has worked decisively for primary supers.
5868   // Secondary supers are sought in the super_cache ('super_cache_addr').
5869   // (Secondary supers are interfaces and very deeply nested subtypes.)
5870   // This works in the same check above because of a tricky aliasing
5871   // between the super_cache and the primary super display elements.
5872   // (The 'super_check_addr' can address either, as the case requires.)
5873   // Note that the cache is updated below if it does not help us find
5874   // what we need immediately.
5875   // So if it was a primary super, we can just fail immediately.
5876   // Otherwise, it's the slow path for us (no success at this point).
5877 
5878   if (super_check_offset.is_register()) {
5879     local_jcc(Assembler::equal, *L_success);
5880     cmpl(super_check_offset.as_register(), sc_offset);
5881     if (L_failure == &L_fallthrough) {
5882       local_jcc(Assembler::equal, *L_slow_path);
5883     } else {
5884       local_jcc(Assembler::notEqual, *L_failure);
5885       final_jmp(*L_slow_path);
5886     }
5887   } else if (super_check_offset.as_constant() == sc_offset) {
5888     // Need a slow path; fast failure is impossible.
5889     if (L_slow_path == &L_fallthrough) {
5890       local_jcc(Assembler::equal, *L_success);
5891     } else {
5892       local_jcc(Assembler::notEqual, *L_slow_path);
5893       final_jmp(*L_success);
5894     }
5895   } else {
5896     // No slow path; it's a fast decision.
5897     if (L_failure == &L_fallthrough) {
5898       local_jcc(Assembler::equal, *L_success);
5899     } else {
5900       local_jcc(Assembler::notEqual, *L_failure);
5901       final_jmp(*L_success);
5902     }
5903   }
5904 
5905   bind(L_fallthrough);
5906 
5907 #undef local_jcc
5908 #undef final_jmp
5909 }
5910 
5911 
5912 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5913                                                    Register super_klass,
5914                                                    Register temp_reg,
5915                                                    Register temp2_reg,
5916                                                    Label* L_success,
5917                                                    Label* L_failure,
5918                                                    bool set_cond_codes) {
5919   assert_different_registers(sub_klass, super_klass, temp_reg);
5920   if (temp2_reg != noreg)
5921     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5922 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5923 
5924   Label L_fallthrough;
5925   int label_nulls = 0;
5926   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5927   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5928   assert(label_nulls <= 1, "at most one NULL in the batch");
5929 
5930   // a couple of useful fields in sub_klass:
5931   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5932   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5933   Address secondary_supers_addr(sub_klass, ss_offset);
5934   Address super_cache_addr(     sub_klass, sc_offset);
5935 
5936   // Do a linear scan of the secondary super-klass chain.
5937   // This code is rarely used, so simplicity is a virtue here.
5938   // The repne_scan instruction uses fixed registers, which we must spill.
5939   // Don't worry too much about pre-existing connections with the input regs.
5940 
5941   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5942   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5943 
5944   // Get super_klass value into rax (even if it was in rdi or rcx).
5945   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5946   if (super_klass != rax || UseCompressedOops) {
5947     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5948     mov(rax, super_klass);
5949   }
5950   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5951   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5952 
5953 #ifndef PRODUCT
5954   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5955   ExternalAddress pst_counter_addr((address) pst_counter);
5956   NOT_LP64(  incrementl(pst_counter_addr) );
5957   LP64_ONLY( lea(rcx, pst_counter_addr) );
5958   LP64_ONLY( incrementl(Address(rcx, 0)) );
5959 #endif //PRODUCT
5960 
5961   // We will consult the secondary-super array.
5962   movptr(rdi, secondary_supers_addr);
5963   // Load the array length.  (Positive movl does right thing on LP64.)
5964   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5965   // Skip to start of data.
5966   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5967 
5968   // Scan RCX words at [RDI] for an occurrence of RAX.
5969   // Set NZ/Z based on last compare.
5970   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5971   // not change flags (only scas instruction which is repeated sets flags).
5972   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5973 
5974     testptr(rax,rax); // Set Z = 0
5975     repne_scan();
5976 
5977   // Unspill the temp. registers:
5978   if (pushed_rdi)  pop(rdi);
5979   if (pushed_rcx)  pop(rcx);
5980   if (pushed_rax)  pop(rax);
5981 
5982   if (set_cond_codes) {
5983     // Special hack for the AD files:  rdi is guaranteed non-zero.
5984     assert(!pushed_rdi, "rdi must be left non-NULL");
5985     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5986   }
5987 
5988   if (L_failure == &L_fallthrough)
5989         jccb(Assembler::notEqual, *L_failure);
5990   else  jcc(Assembler::notEqual, *L_failure);
5991 
5992   // Success.  Cache the super we found and proceed in triumph.
5993   movptr(super_cache_addr, super_klass);
5994 
5995   if (L_success != &L_fallthrough) {
5996     jmp(*L_success);
5997   }
5998 
5999 #undef IS_A_TEMP
6000 
6001   bind(L_fallthrough);
6002 }
6003 
6004 
6005 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6006   if (VM_Version::supports_cmov()) {
6007     cmovl(cc, dst, src);
6008   } else {
6009     Label L;
6010     jccb(negate_condition(cc), L);
6011     movl(dst, src);
6012     bind(L);
6013   }
6014 }
6015 
6016 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6017   if (VM_Version::supports_cmov()) {
6018     cmovl(cc, dst, src);
6019   } else {
6020     Label L;
6021     jccb(negate_condition(cc), L);
6022     movl(dst, src);
6023     bind(L);
6024   }
6025 }
6026 
6027 void MacroAssembler::verify_oop(Register reg, const char* s) {
6028   if (!VerifyOops) return;
6029 
6030   // Pass register number to verify_oop_subroutine
6031   const char* b = NULL;
6032   {
6033     ResourceMark rm;
6034     stringStream ss;
6035     ss.print("verify_oop: %s: %s", reg->name(), s);
6036     b = code_string(ss.as_string());
6037   }
6038   BLOCK_COMMENT("verify_oop {");
6039 #ifdef _LP64
6040   push(rscratch1);                    // save r10, trashed by movptr()
6041 #endif
6042   push(rax);                          // save rax,
6043   push(reg);                          // pass register argument
6044   ExternalAddress buffer((address) b);
6045   // avoid using pushptr, as it modifies scratch registers
6046   // and our contract is not to modify anything
6047   movptr(rax, buffer.addr());
6048   push(rax);
6049   // call indirectly to solve generation ordering problem
6050   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6051   call(rax);
6052   // Caller pops the arguments (oop, message) and restores rax, r10
6053   BLOCK_COMMENT("} verify_oop");
6054 }
6055 
6056 
6057 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6058                                                       Register tmp,
6059                                                       int offset) {
6060   intptr_t value = *delayed_value_addr;
6061   if (value != 0)
6062     return RegisterOrConstant(value + offset);
6063 
6064   // load indirectly to solve generation ordering problem
6065   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6066 
6067 #ifdef ASSERT
6068   { Label L;
6069     testptr(tmp, tmp);
6070     if (WizardMode) {
6071       const char* buf = NULL;
6072       {
6073         ResourceMark rm;
6074         stringStream ss;
6075         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6076         buf = code_string(ss.as_string());
6077       }
6078       jcc(Assembler::notZero, L);
6079       STOP(buf);
6080     } else {
6081       jccb(Assembler::notZero, L);
6082       hlt();
6083     }
6084     bind(L);
6085   }
6086 #endif
6087 
6088   if (offset != 0)
6089     addptr(tmp, offset);
6090 
6091   return RegisterOrConstant(tmp);
6092 }
6093 
6094 
6095 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6096                                          int extra_slot_offset) {
6097   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6098   int stackElementSize = Interpreter::stackElementSize;
6099   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6100 #ifdef ASSERT
6101   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6102   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6103 #endif
6104   Register             scale_reg    = noreg;
6105   Address::ScaleFactor scale_factor = Address::no_scale;
6106   if (arg_slot.is_constant()) {
6107     offset += arg_slot.as_constant() * stackElementSize;
6108   } else {
6109     scale_reg    = arg_slot.as_register();
6110     scale_factor = Address::times(stackElementSize);
6111   }
6112   offset += wordSize;           // return PC is on stack
6113   return Address(rsp, scale_reg, scale_factor, offset);
6114 }
6115 
6116 
6117 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6118   if (!VerifyOops) return;
6119 
6120   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6121   // Pass register number to verify_oop_subroutine
6122   const char* b = NULL;
6123   {
6124     ResourceMark rm;
6125     stringStream ss;
6126     ss.print("verify_oop_addr: %s", s);
6127     b = code_string(ss.as_string());
6128   }
6129 #ifdef _LP64
6130   push(rscratch1);                    // save r10, trashed by movptr()
6131 #endif
6132   push(rax);                          // save rax,
6133   // addr may contain rsp so we will have to adjust it based on the push
6134   // we just did (and on 64 bit we do two pushes)
6135   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6136   // stores rax into addr which is backwards of what was intended.
6137   if (addr.uses(rsp)) {
6138     lea(rax, addr);
6139     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6140   } else {
6141     pushptr(addr);
6142   }
6143 
6144   ExternalAddress buffer((address) b);
6145   // pass msg argument
6146   // avoid using pushptr, as it modifies scratch registers
6147   // and our contract is not to modify anything
6148   movptr(rax, buffer.addr());
6149   push(rax);
6150 
6151   // call indirectly to solve generation ordering problem
6152   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6153   call(rax);
6154   // Caller pops the arguments (addr, message) and restores rax, r10.
6155 }
6156 
6157 void MacroAssembler::verify_tlab() {
6158 #ifdef ASSERT
6159   if (UseTLAB && VerifyOops) {
6160     Label next, ok;
6161     Register t1 = rsi;
6162     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6163 
6164     push(t1);
6165     NOT_LP64(push(thread_reg));
6166     NOT_LP64(get_thread(thread_reg));
6167 
6168     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6169     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6170     jcc(Assembler::aboveEqual, next);
6171     STOP("assert(top >= start)");
6172     should_not_reach_here();
6173 
6174     bind(next);
6175     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6176     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6177     jcc(Assembler::aboveEqual, ok);
6178     STOP("assert(top <= end)");
6179     should_not_reach_here();
6180 
6181     bind(ok);
6182     NOT_LP64(pop(thread_reg));
6183     pop(t1);
6184   }
6185 #endif
6186 }
6187 
6188 class ControlWord {
6189  public:
6190   int32_t _value;
6191 
6192   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6193   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6194   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6195   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6196   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6197   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6198   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6199   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6200 
6201   void print() const {
6202     // rounding control
6203     const char* rc;
6204     switch (rounding_control()) {
6205       case 0: rc = "round near"; break;
6206       case 1: rc = "round down"; break;
6207       case 2: rc = "round up  "; break;
6208       case 3: rc = "chop      "; break;
6209     };
6210     // precision control
6211     const char* pc;
6212     switch (precision_control()) {
6213       case 0: pc = "24 bits "; break;
6214       case 1: pc = "reserved"; break;
6215       case 2: pc = "53 bits "; break;
6216       case 3: pc = "64 bits "; break;
6217     };
6218     // flags
6219     char f[9];
6220     f[0] = ' ';
6221     f[1] = ' ';
6222     f[2] = (precision   ()) ? 'P' : 'p';
6223     f[3] = (underflow   ()) ? 'U' : 'u';
6224     f[4] = (overflow    ()) ? 'O' : 'o';
6225     f[5] = (zero_divide ()) ? 'Z' : 'z';
6226     f[6] = (denormalized()) ? 'D' : 'd';
6227     f[7] = (invalid     ()) ? 'I' : 'i';
6228     f[8] = '\x0';
6229     // output
6230     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6231   }
6232 
6233 };
6234 
6235 class StatusWord {
6236  public:
6237   int32_t _value;
6238 
6239   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6240   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6241   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6242   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6243   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6244   int  top() const                     { return  (_value >> 11) & 7      ; }
6245   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6246   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6247   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6248   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6249   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6250   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6251   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6252   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6253 
6254   void print() const {
6255     // condition codes
6256     char c[5];
6257     c[0] = (C3()) ? '3' : '-';
6258     c[1] = (C2()) ? '2' : '-';
6259     c[2] = (C1()) ? '1' : '-';
6260     c[3] = (C0()) ? '0' : '-';
6261     c[4] = '\x0';
6262     // flags
6263     char f[9];
6264     f[0] = (error_status()) ? 'E' : '-';
6265     f[1] = (stack_fault ()) ? 'S' : '-';
6266     f[2] = (precision   ()) ? 'P' : '-';
6267     f[3] = (underflow   ()) ? 'U' : '-';
6268     f[4] = (overflow    ()) ? 'O' : '-';
6269     f[5] = (zero_divide ()) ? 'Z' : '-';
6270     f[6] = (denormalized()) ? 'D' : '-';
6271     f[7] = (invalid     ()) ? 'I' : '-';
6272     f[8] = '\x0';
6273     // output
6274     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6275   }
6276 
6277 };
6278 
6279 class TagWord {
6280  public:
6281   int32_t _value;
6282 
6283   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6284 
6285   void print() const {
6286     printf("%04x", _value & 0xFFFF);
6287   }
6288 
6289 };
6290 
6291 class FPU_Register {
6292  public:
6293   int32_t _m0;
6294   int32_t _m1;
6295   int16_t _ex;
6296 
6297   bool is_indefinite() const           {
6298     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6299   }
6300 
6301   void print() const {
6302     char  sign = (_ex < 0) ? '-' : '+';
6303     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6304     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6305   };
6306 
6307 };
6308 
6309 class FPU_State {
6310  public:
6311   enum {
6312     register_size       = 10,
6313     number_of_registers =  8,
6314     register_mask       =  7
6315   };
6316 
6317   ControlWord  _control_word;
6318   StatusWord   _status_word;
6319   TagWord      _tag_word;
6320   int32_t      _error_offset;
6321   int32_t      _error_selector;
6322   int32_t      _data_offset;
6323   int32_t      _data_selector;
6324   int8_t       _register[register_size * number_of_registers];
6325 
6326   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6327   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6328 
6329   const char* tag_as_string(int tag) const {
6330     switch (tag) {
6331       case 0: return "valid";
6332       case 1: return "zero";
6333       case 2: return "special";
6334       case 3: return "empty";
6335     }
6336     ShouldNotReachHere();
6337     return NULL;
6338   }
6339 
6340   void print() const {
6341     // print computation registers
6342     { int t = _status_word.top();
6343       for (int i = 0; i < number_of_registers; i++) {
6344         int j = (i - t) & register_mask;
6345         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6346         st(j)->print();
6347         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6348       }
6349     }
6350     printf("\n");
6351     // print control registers
6352     printf("ctrl = "); _control_word.print(); printf("\n");
6353     printf("stat = "); _status_word .print(); printf("\n");
6354     printf("tags = "); _tag_word    .print(); printf("\n");
6355   }
6356 
6357 };
6358 
6359 class Flag_Register {
6360  public:
6361   int32_t _value;
6362 
6363   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6364   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6365   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6366   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6367   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6368   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6369   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6370 
6371   void print() const {
6372     // flags
6373     char f[8];
6374     f[0] = (overflow       ()) ? 'O' : '-';
6375     f[1] = (direction      ()) ? 'D' : '-';
6376     f[2] = (sign           ()) ? 'S' : '-';
6377     f[3] = (zero           ()) ? 'Z' : '-';
6378     f[4] = (auxiliary_carry()) ? 'A' : '-';
6379     f[5] = (parity         ()) ? 'P' : '-';
6380     f[6] = (carry          ()) ? 'C' : '-';
6381     f[7] = '\x0';
6382     // output
6383     printf("%08x  flags = %s", _value, f);
6384   }
6385 
6386 };
6387 
6388 class IU_Register {
6389  public:
6390   int32_t _value;
6391 
6392   void print() const {
6393     printf("%08x  %11d", _value, _value);
6394   }
6395 
6396 };
6397 
6398 class IU_State {
6399  public:
6400   Flag_Register _eflags;
6401   IU_Register   _rdi;
6402   IU_Register   _rsi;
6403   IU_Register   _rbp;
6404   IU_Register   _rsp;
6405   IU_Register   _rbx;
6406   IU_Register   _rdx;
6407   IU_Register   _rcx;
6408   IU_Register   _rax;
6409 
6410   void print() const {
6411     // computation registers
6412     printf("rax,  = "); _rax.print(); printf("\n");
6413     printf("rbx,  = "); _rbx.print(); printf("\n");
6414     printf("rcx  = "); _rcx.print(); printf("\n");
6415     printf("rdx  = "); _rdx.print(); printf("\n");
6416     printf("rdi  = "); _rdi.print(); printf("\n");
6417     printf("rsi  = "); _rsi.print(); printf("\n");
6418     printf("rbp,  = "); _rbp.print(); printf("\n");
6419     printf("rsp  = "); _rsp.print(); printf("\n");
6420     printf("\n");
6421     // control registers
6422     printf("flgs = "); _eflags.print(); printf("\n");
6423   }
6424 };
6425 
6426 
6427 class CPU_State {
6428  public:
6429   FPU_State _fpu_state;
6430   IU_State  _iu_state;
6431 
6432   void print() const {
6433     printf("--------------------------------------------------\n");
6434     _iu_state .print();
6435     printf("\n");
6436     _fpu_state.print();
6437     printf("--------------------------------------------------\n");
6438   }
6439 
6440 };
6441 
6442 
6443 static void _print_CPU_state(CPU_State* state) {
6444   state->print();
6445 };
6446 
6447 
6448 void MacroAssembler::print_CPU_state() {
6449   push_CPU_state();
6450   push(rsp);                // pass CPU state
6451   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6452   addptr(rsp, wordSize);       // discard argument
6453   pop_CPU_state();
6454 }
6455 
6456 
6457 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6458   static int counter = 0;
6459   FPU_State* fs = &state->_fpu_state;
6460   counter++;
6461   // For leaf calls, only verify that the top few elements remain empty.
6462   // We only need 1 empty at the top for C2 code.
6463   if( stack_depth < 0 ) {
6464     if( fs->tag_for_st(7) != 3 ) {
6465       printf("FPR7 not empty\n");
6466       state->print();
6467       assert(false, "error");
6468       return false;
6469     }
6470     return true;                // All other stack states do not matter
6471   }
6472 
6473   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6474          "bad FPU control word");
6475 
6476   // compute stack depth
6477   int i = 0;
6478   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6479   int d = i;
6480   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6481   // verify findings
6482   if (i != FPU_State::number_of_registers) {
6483     // stack not contiguous
6484     printf("%s: stack not contiguous at ST%d\n", s, i);
6485     state->print();
6486     assert(false, "error");
6487     return false;
6488   }
6489   // check if computed stack depth corresponds to expected stack depth
6490   if (stack_depth < 0) {
6491     // expected stack depth is -stack_depth or less
6492     if (d > -stack_depth) {
6493       // too many elements on the stack
6494       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6495       state->print();
6496       assert(false, "error");
6497       return false;
6498     }
6499   } else {
6500     // expected stack depth is stack_depth
6501     if (d != stack_depth) {
6502       // wrong stack depth
6503       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6504       state->print();
6505       assert(false, "error");
6506       return false;
6507     }
6508   }
6509   // everything is cool
6510   return true;
6511 }
6512 
6513 
6514 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6515   if (!VerifyFPU) return;
6516   push_CPU_state();
6517   push(rsp);                // pass CPU state
6518   ExternalAddress msg((address) s);
6519   // pass message string s
6520   pushptr(msg.addr());
6521   push(stack_depth);        // pass stack depth
6522   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6523   addptr(rsp, 3 * wordSize);   // discard arguments
6524   // check for error
6525   { Label L;
6526     testl(rax, rax);
6527     jcc(Assembler::notZero, L);
6528     int3();                  // break if error condition
6529     bind(L);
6530   }
6531   pop_CPU_state();
6532 }
6533 
6534 void MacroAssembler::restore_cpu_control_state_after_jni() {
6535   // Either restore the MXCSR register after returning from the JNI Call
6536   // or verify that it wasn't changed (with -Xcheck:jni flag).
6537   if (VM_Version::supports_sse()) {
6538     if (RestoreMXCSROnJNICalls) {
6539       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6540     } else if (CheckJNICalls) {
6541       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6542     }
6543   }
6544   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6545   vzeroupper();
6546   // Reset k1 to 0xffff.
6547   if (VM_Version::supports_evex()) {
6548     push(rcx);
6549     movl(rcx, 0xffff);
6550     kmovwl(k1, rcx);
6551     pop(rcx);
6552   }
6553 
6554 #ifndef _LP64
6555   // Either restore the x87 floating pointer control word after returning
6556   // from the JNI call or verify that it wasn't changed.
6557   if (CheckJNICalls) {
6558     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6559   }
6560 #endif // _LP64
6561 }
6562 
6563 // ((OopHandle)result).resolve();
6564 void MacroAssembler::resolve_oop_handle(Register result) {
6565   // OopHandle::resolve is an indirection.
6566   movptr(result, Address(result, 0));
6567 }
6568 
6569 void MacroAssembler::load_mirror(Register mirror, Register method) {
6570   // get mirror
6571   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6572   movptr(mirror, Address(method, Method::const_offset()));
6573   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6574   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6575   movptr(mirror, Address(mirror, mirror_offset));
6576   resolve_oop_handle(mirror);
6577 }
6578 
6579 void MacroAssembler::load_klass(Register dst, Register src) {
6580 #ifdef _LP64
6581   if (UseCompressedClassPointers) {
6582     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6583     decode_klass_not_null(dst);
6584   } else
6585 #endif
6586     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6587 }
6588 
6589 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6590   load_klass(dst, src);
6591   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6592 }
6593 
6594 void MacroAssembler::store_klass(Register dst, Register src) {
6595 #ifdef _LP64
6596   if (UseCompressedClassPointers) {
6597     encode_klass_not_null(src);
6598     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6599   } else
6600 #endif
6601     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6602 }
6603 
6604 #if INCLUDE_ALL_GCS && defined(_LP64)
6605 
6606 void MacroAssembler::load_barrier(Register ref, Address ref_addr, bool expand_call, LoadBarrierOn on) {
6607   Label done;
6608   const Register resolved_ref_addr = rsi;
6609   assert_different_registers(ref, resolved_ref_addr);
6610 
6611   BLOCK_COMMENT("load_barrier {");
6612 
6613   // Save temp register
6614   push(resolved_ref_addr);
6615 
6616   // Resolve reference address now, ref_addr might use the same register as ref,
6617   // which means it gets killed when we write to ref.
6618   lea(resolved_ref_addr, ref_addr);
6619 
6620   // Load reference
6621   movptr(ref, Address(resolved_ref_addr, 0));
6622 
6623   // Check if mask is not bad, which includes an implicit null check.
6624   testptr(ref, Address(r15_thread, JavaThread::zaddress_bad_mask_offset()));
6625   jcc(Assembler::zero, done);
6626 
6627   // Save live registers
6628   push(rax);
6629   push(rcx);
6630   push(rdx);
6631   push(rdi);
6632   push(r8);
6633   push(r9);
6634   push(r10);
6635   push(r11);
6636 
6637   // We may end up here from generate_native_wrapper, then the method may have
6638   // floats as arguments, and we must spill them before calling the VM runtime
6639   // leaf. From the interpreter all floats are passed on the stack.
6640   assert(Argument::n_float_register_parameters_j == 8, "Found %d float regs", Argument::n_float_register_parameters_j);
6641   int f_spill_size = Argument::n_float_register_parameters_j * wordSize * 2;
6642   subptr(rsp, f_spill_size);
6643   movdqu(Address(rsp, 14 * wordSize), xmm7);
6644   movdqu(Address(rsp, 12 * wordSize), xmm6);
6645   movdqu(Address(rsp, 10 * wordSize), xmm5);
6646   movdqu(Address(rsp, 8 * wordSize), xmm4);
6647   movdqu(Address(rsp, 6 * wordSize), xmm3);
6648   movdqu(Address(rsp, 4 * wordSize), xmm2);
6649   movdqu(Address(rsp, 2 * wordSize), xmm1);
6650   movdqu(Address(rsp, 0 * wordSize), xmm0);
6651 
6652   // Call into VM to handle the slow path
6653   if (expand_call) {
6654     assert(ref != c_rarg1, "smashed arg");
6655     pass_arg1(this, resolved_ref_addr);
6656     pass_arg0(this, ref);
6657     switch (on) {
6658     case LoadBarrierOnStrongOopRef:
6659       MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_oop_field_preloaded), 2);
6660       break;
6661     case LoadBarrierOnWeakOopRef:
6662       MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_weak_oop_field_preloaded), 2);
6663       break;
6664     case LoadBarrierOnPhantomOopRef:
6665       MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_phantom_oop_field_preloaded), 2);
6666       break;
6667     default:
6668       fatal("Unknown strength: %d", on);
6669       break;
6670     }
6671   } else {
6672     switch (on) {
6673     case LoadBarrierOnStrongOopRef:
6674       call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_oop_field_preloaded), ref, resolved_ref_addr);
6675       break;
6676     case LoadBarrierOnWeakOopRef:
6677       call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_weak_oop_field_preloaded), ref, resolved_ref_addr);
6678       break;
6679     case LoadBarrierOnPhantomOopRef:
6680       call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_phantom_oop_field_preloaded), ref, resolved_ref_addr);
6681       break;
6682     default: fatal("Unknown strength: %d", on);
6683       break;
6684     }
6685   }
6686 
6687   // Restore live registers
6688   movdqu(xmm0, Address(rsp, 0 * wordSize));
6689   movdqu(xmm1, Address(rsp, 2 * wordSize));
6690   movdqu(xmm2, Address(rsp, 4 * wordSize));
6691   movdqu(xmm3, Address(rsp, 6 * wordSize));
6692   movdqu(xmm4, Address(rsp, 8 * wordSize));
6693   movdqu(xmm5, Address(rsp, 10 * wordSize));
6694   movdqu(xmm6, Address(rsp, 12 * wordSize));
6695   movdqu(xmm7, Address(rsp, 14 * wordSize));
6696   addptr(rsp, f_spill_size);
6697 
6698   pop(r11);
6699   pop(r10);
6700   pop(r9);
6701   pop(r8);
6702   pop(rdi);
6703   pop(rdx);
6704   pop(rcx);
6705 
6706   if (ref == rax) {
6707     addptr(rsp, wordSize);
6708   } else {
6709     movptr(ref, rax);
6710     pop(rax);
6711   }
6712 
6713   bind(done);
6714 
6715   // Restore temp register
6716   pop(resolved_ref_addr);
6717 
6718   BLOCK_COMMENT("} load_barrier");
6719 }
6720 
6721 #endif
6722 
6723 void MacroAssembler::load_heap_oop(Register dst, Address src, bool expand_call, LoadBarrierOn on) {
6724 #ifdef _LP64
6725 #if INCLUDE_ALL_GCS
6726   if (UseLoadBarrier) {
6727     load_barrier(dst, src, expand_call, on);
6728   } else
6729 #endif
6730   if (UseCompressedOops) {
6731     movl(dst, src);
6732     decode_heap_oop(dst);
6733   } else
6734 #endif
6735     movptr(dst, src);
6736 }
6737 
6738 // Doesn't do verfication, generates fixed size code
6739 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6740 #ifdef _LP64
6741   if (UseCompressedOops) {
6742     movl(dst, src);
6743     decode_heap_oop_not_null(dst);
6744   } else
6745 #endif
6746     movptr(dst, src);
6747 }
6748 
6749 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6750 #ifdef ASSERT
6751   if (VerifyOops && UseLoadBarrier) {
6752     // Check if mask is good
6753     Label done;
6754     testptr(src, Address(r15_thread, JavaThread::zaddress_bad_mask_offset()));
6755     jcc(Assembler::zero, done);
6756     STOP("Writing broken oop");
6757     should_not_reach_here();
6758     bind(done);
6759   }
6760 #endif
6761 
6762 #ifdef _LP64
6763   if (UseCompressedOops) {
6764     assert(!dst.uses(src), "not enough registers");
6765     encode_heap_oop(src);
6766     movl(dst, src);
6767   } else
6768 #endif
6769     movptr(dst, src);
6770 }
6771 
6772 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6773   assert_different_registers(src1, tmp);
6774 #ifdef _LP64
6775   if (UseCompressedOops) {
6776     bool did_push = false;
6777     if (tmp == noreg) {
6778       tmp = rax;
6779       push(tmp);
6780       did_push = true;
6781       assert(!src2.uses(rsp), "can't push");
6782     }
6783     load_heap_oop(tmp, src2);
6784     cmpptr(src1, tmp);
6785     if (did_push)  pop(tmp);
6786   } else
6787 #endif
6788     cmpptr(src1, src2);
6789 }
6790 
6791 // Used for storing NULLs.
6792 void MacroAssembler::store_heap_oop_null(Address dst) {
6793 #ifdef _LP64
6794   if (UseCompressedOops) {
6795     movl(dst, (int32_t)NULL_WORD);
6796   } else {
6797     movslq(dst, (int32_t)NULL_WORD);
6798   }
6799 #else
6800   movl(dst, (int32_t)NULL_WORD);
6801 #endif
6802 }
6803 
6804 #ifdef _LP64
6805 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6806   if (UseCompressedClassPointers) {
6807     // Store to klass gap in destination
6808     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6809   }
6810 }
6811 
6812 #ifdef ASSERT
6813 void MacroAssembler::verify_heapbase(const char* msg) {
6814   assert (UseCompressedOops, "should be compressed");
6815   assert (Universe::heap() != NULL, "java heap should be initialized");
6816   if (CheckCompressedOops) {
6817     Label ok;
6818     push(rscratch1); // cmpptr trashes rscratch1
6819     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6820     jcc(Assembler::equal, ok);
6821     STOP(msg);
6822     bind(ok);
6823     pop(rscratch1);
6824   }
6825 }
6826 #endif
6827 
6828 // Algorithm must match oop.inline.hpp encode_heap_oop.
6829 void MacroAssembler::encode_heap_oop(Register r) {
6830 #ifdef ASSERT
6831   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6832 #endif
6833   verify_oop(r, "broken oop in encode_heap_oop");
6834   if (Universe::narrow_oop_base() == NULL) {
6835     if (Universe::narrow_oop_shift() != 0) {
6836       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6837       shrq(r, LogMinObjAlignmentInBytes);
6838     }
6839     return;
6840   }
6841   testq(r, r);
6842   cmovq(Assembler::equal, r, r12_heapbase);
6843   subq(r, r12_heapbase);
6844   shrq(r, LogMinObjAlignmentInBytes);
6845 }
6846 
6847 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6848 #ifdef ASSERT
6849   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6850   if (CheckCompressedOops) {
6851     Label ok;
6852     testq(r, r);
6853     jcc(Assembler::notEqual, ok);
6854     STOP("null oop passed to encode_heap_oop_not_null");
6855     bind(ok);
6856   }
6857 #endif
6858   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6859   if (Universe::narrow_oop_base() != NULL) {
6860     subq(r, r12_heapbase);
6861   }
6862   if (Universe::narrow_oop_shift() != 0) {
6863     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6864     shrq(r, LogMinObjAlignmentInBytes);
6865   }
6866 }
6867 
6868 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6869 #ifdef ASSERT
6870   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6871   if (CheckCompressedOops) {
6872     Label ok;
6873     testq(src, src);
6874     jcc(Assembler::notEqual, ok);
6875     STOP("null oop passed to encode_heap_oop_not_null2");
6876     bind(ok);
6877   }
6878 #endif
6879   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6880   if (dst != src) {
6881     movq(dst, src);
6882   }
6883   if (Universe::narrow_oop_base() != NULL) {
6884     subq(dst, r12_heapbase);
6885   }
6886   if (Universe::narrow_oop_shift() != 0) {
6887     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6888     shrq(dst, LogMinObjAlignmentInBytes);
6889   }
6890 }
6891 
6892 void  MacroAssembler::decode_heap_oop(Register r) {
6893 #ifdef ASSERT
6894   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6895 #endif
6896   if (Universe::narrow_oop_base() == NULL) {
6897     if (Universe::narrow_oop_shift() != 0) {
6898       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6899       shlq(r, LogMinObjAlignmentInBytes);
6900     }
6901   } else {
6902     Label done;
6903     shlq(r, LogMinObjAlignmentInBytes);
6904     jccb(Assembler::equal, done);
6905     addq(r, r12_heapbase);
6906     bind(done);
6907   }
6908   verify_oop(r, "broken oop in decode_heap_oop");
6909 }
6910 
6911 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6912   // Note: it will change flags
6913   assert (UseCompressedOops, "should only be used for compressed headers");
6914   assert (Universe::heap() != NULL, "java heap should be initialized");
6915   // Cannot assert, unverified entry point counts instructions (see .ad file)
6916   // vtableStubs also counts instructions in pd_code_size_limit.
6917   // Also do not verify_oop as this is called by verify_oop.
6918   if (Universe::narrow_oop_shift() != 0) {
6919     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6920     shlq(r, LogMinObjAlignmentInBytes);
6921     if (Universe::narrow_oop_base() != NULL) {
6922       addq(r, r12_heapbase);
6923     }
6924   } else {
6925     assert (Universe::narrow_oop_base() == NULL, "sanity");
6926   }
6927 }
6928 
6929 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6930   // Note: it will change flags
6931   assert (UseCompressedOops, "should only be used for compressed headers");
6932   assert (Universe::heap() != NULL, "java heap should be initialized");
6933   // Cannot assert, unverified entry point counts instructions (see .ad file)
6934   // vtableStubs also counts instructions in pd_code_size_limit.
6935   // Also do not verify_oop as this is called by verify_oop.
6936   if (Universe::narrow_oop_shift() != 0) {
6937     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6938     if (LogMinObjAlignmentInBytes == Address::times_8) {
6939       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6940     } else {
6941       if (dst != src) {
6942         movq(dst, src);
6943       }
6944       shlq(dst, LogMinObjAlignmentInBytes);
6945       if (Universe::narrow_oop_base() != NULL) {
6946         addq(dst, r12_heapbase);
6947       }
6948     }
6949   } else {
6950     assert (Universe::narrow_oop_base() == NULL, "sanity");
6951     if (dst != src) {
6952       movq(dst, src);
6953     }
6954   }
6955 }
6956 
6957 void MacroAssembler::encode_klass_not_null(Register r) {
6958   if (Universe::narrow_klass_base() != NULL) {
6959     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6960     assert(r != r12_heapbase, "Encoding a klass in r12");
6961     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6962     subq(r, r12_heapbase);
6963   }
6964   if (Universe::narrow_klass_shift() != 0) {
6965     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6966     shrq(r, LogKlassAlignmentInBytes);
6967   }
6968   if (Universe::narrow_klass_base() != NULL) {
6969     reinit_heapbase();
6970   }
6971 }
6972 
6973 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6974   if (dst == src) {
6975     encode_klass_not_null(src);
6976   } else {
6977     if (Universe::narrow_klass_base() != NULL) {
6978       mov64(dst, (int64_t)Universe::narrow_klass_base());
6979       negq(dst);
6980       addq(dst, src);
6981     } else {
6982       movptr(dst, src);
6983     }
6984     if (Universe::narrow_klass_shift() != 0) {
6985       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6986       shrq(dst, LogKlassAlignmentInBytes);
6987     }
6988   }
6989 }
6990 
6991 // Function instr_size_for_decode_klass_not_null() counts the instructions
6992 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6993 // when (Universe::heap() != NULL).  Hence, if the instructions they
6994 // generate change, then this method needs to be updated.
6995 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6996   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6997   if (Universe::narrow_klass_base() != NULL) {
6998     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6999     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7000   } else {
7001     // longest load decode klass function, mov64, leaq
7002     return 16;
7003   }
7004 }
7005 
7006 // !!! If the instructions that get generated here change then function
7007 // instr_size_for_decode_klass_not_null() needs to get updated.
7008 void  MacroAssembler::decode_klass_not_null(Register r) {
7009   // Note: it will change flags
7010   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7011   assert(r != r12_heapbase, "Decoding a klass in r12");
7012   // Cannot assert, unverified entry point counts instructions (see .ad file)
7013   // vtableStubs also counts instructions in pd_code_size_limit.
7014   // Also do not verify_oop as this is called by verify_oop.
7015   if (Universe::narrow_klass_shift() != 0) {
7016     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7017     shlq(r, LogKlassAlignmentInBytes);
7018   }
7019   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7020   if (Universe::narrow_klass_base() != NULL) {
7021     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7022     addq(r, r12_heapbase);
7023     reinit_heapbase();
7024   }
7025 }
7026 
7027 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7028   // Note: it will change flags
7029   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7030   if (dst == src) {
7031     decode_klass_not_null(dst);
7032   } else {
7033     // Cannot assert, unverified entry point counts instructions (see .ad file)
7034     // vtableStubs also counts instructions in pd_code_size_limit.
7035     // Also do not verify_oop as this is called by verify_oop.
7036     mov64(dst, (int64_t)Universe::narrow_klass_base());
7037     if (Universe::narrow_klass_shift() != 0) {
7038       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7039       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7040       leaq(dst, Address(dst, src, Address::times_8, 0));
7041     } else {
7042       addq(dst, src);
7043     }
7044   }
7045 }
7046 
7047 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7048   assert (UseCompressedOops, "should only be used for compressed headers");
7049   assert (Universe::heap() != NULL, "java heap should be initialized");
7050   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7051   int oop_index = oop_recorder()->find_index(obj);
7052   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7053   mov_narrow_oop(dst, oop_index, rspec);
7054 }
7055 
7056 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7057   assert (UseCompressedOops, "should only be used for compressed headers");
7058   assert (Universe::heap() != NULL, "java heap should be initialized");
7059   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7060   int oop_index = oop_recorder()->find_index(obj);
7061   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7062   mov_narrow_oop(dst, oop_index, rspec);
7063 }
7064 
7065 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7066   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7067   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7068   int klass_index = oop_recorder()->find_index(k);
7069   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7070   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7071 }
7072 
7073 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7074   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7075   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7076   int klass_index = oop_recorder()->find_index(k);
7077   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7078   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7079 }
7080 
7081 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7082   assert (UseCompressedOops, "should only be used for compressed headers");
7083   assert (Universe::heap() != NULL, "java heap should be initialized");
7084   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7085   int oop_index = oop_recorder()->find_index(obj);
7086   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7087   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7088 }
7089 
7090 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7091   assert (UseCompressedOops, "should only be used for compressed headers");
7092   assert (Universe::heap() != NULL, "java heap should be initialized");
7093   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7094   int oop_index = oop_recorder()->find_index(obj);
7095   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7096   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7097 }
7098 
7099 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7100   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7101   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7102   int klass_index = oop_recorder()->find_index(k);
7103   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7104   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7105 }
7106 
7107 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7108   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7109   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7110   int klass_index = oop_recorder()->find_index(k);
7111   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7112   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7113 }
7114 
7115 void MacroAssembler::reinit_heapbase() {
7116   if (UseCompressedOops || UseCompressedClassPointers) {
7117     if (Universe::heap() != NULL) {
7118       if (Universe::narrow_oop_base() == NULL) {
7119         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7120       } else {
7121         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7122       }
7123     } else {
7124       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7125     }
7126   } else {
7127     mov64(r12, -1);
7128   }
7129 }
7130 
7131 #endif // _LP64
7132 
7133 // C2 compiled method's prolog code.
7134 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7135 
7136   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7137   // NativeJump::patch_verified_entry will be able to patch out the entry
7138   // code safely. The push to verify stack depth is ok at 5 bytes,
7139   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7140   // stack bang then we must use the 6 byte frame allocation even if
7141   // we have no frame. :-(
7142   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7143 
7144   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7145   // Remove word for return addr
7146   framesize -= wordSize;
7147   stack_bang_size -= wordSize;
7148 
7149   // Calls to C2R adapters often do not accept exceptional returns.
7150   // We require that their callers must bang for them.  But be careful, because
7151   // some VM calls (such as call site linkage) can use several kilobytes of
7152   // stack.  But the stack safety zone should account for that.
7153   // See bugs 4446381, 4468289, 4497237.
7154   if (stack_bang_size > 0) {
7155     generate_stack_overflow_check(stack_bang_size);
7156 
7157     // We always push rbp, so that on return to interpreter rbp, will be
7158     // restored correctly and we can correct the stack.
7159     push(rbp);
7160     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7161     if (PreserveFramePointer) {
7162       mov(rbp, rsp);
7163     }
7164     // Remove word for ebp
7165     framesize -= wordSize;
7166 
7167     // Create frame
7168     if (framesize) {
7169       subptr(rsp, framesize);
7170     }
7171   } else {
7172     // Create frame (force generation of a 4 byte immediate value)
7173     subptr_imm32(rsp, framesize);
7174 
7175     // Save RBP register now.
7176     framesize -= wordSize;
7177     movptr(Address(rsp, framesize), rbp);
7178     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7179     if (PreserveFramePointer) {
7180       movptr(rbp, rsp);
7181       if (framesize > 0) {
7182         addptr(rbp, framesize);
7183       }
7184     }
7185   }
7186 
7187   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7188     framesize -= wordSize;
7189     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7190   }
7191 
7192 #ifndef _LP64
7193   // If method sets FPU control word do it now
7194   if (fp_mode_24b) {
7195     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7196   }
7197   if (UseSSE >= 2 && VerifyFPU) {
7198     verify_FPU(0, "FPU stack must be clean on entry");
7199   }
7200 #endif
7201 
7202 #ifdef ASSERT
7203   if (VerifyStackAtCalls) {
7204     Label L;
7205     push(rax);
7206     mov(rax, rsp);
7207     andptr(rax, StackAlignmentInBytes-1);
7208     cmpptr(rax, StackAlignmentInBytes-wordSize);
7209     pop(rax);
7210     jcc(Assembler::equal, L);
7211     STOP("Stack is not properly aligned!");
7212     bind(L);
7213   }
7214 #endif
7215 
7216 }
7217 
7218 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7219   // cnt - number of qwords (8-byte words).
7220   // base - start address, qword aligned.
7221   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7222   assert(base==rdi, "base register must be edi for rep stos");
7223   assert(tmp==rax,   "tmp register must be eax for rep stos");
7224   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7225   assert(InitArrayShortSize % BytesPerLong == 0,
7226     "InitArrayShortSize should be the multiple of BytesPerLong");
7227 
7228   Label DONE;
7229 
7230   xorptr(tmp, tmp);
7231 
7232   if (!is_large) {
7233     Label LOOP, LONG;
7234     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7235     jccb(Assembler::greater, LONG);
7236 
7237     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7238 
7239     decrement(cnt);
7240     jccb(Assembler::negative, DONE); // Zero length
7241 
7242     // Use individual pointer-sized stores for small counts:
7243     BIND(LOOP);
7244     movptr(Address(base, cnt, Address::times_ptr), tmp);
7245     decrement(cnt);
7246     jccb(Assembler::greaterEqual, LOOP);
7247     jmpb(DONE);
7248 
7249     BIND(LONG);
7250   }
7251 
7252   // Use longer rep-prefixed ops for non-small counts:
7253   if (UseFastStosb) {
7254     shlptr(cnt, 3); // convert to number of bytes
7255     rep_stosb();
7256   } else {
7257     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7258     rep_stos();
7259   }
7260 
7261   BIND(DONE);
7262 }
7263 
7264 #ifdef COMPILER2
7265 
7266 // IndexOf for constant substrings with size >= 8 chars
7267 // which don't need to be loaded through stack.
7268 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7269                                       Register cnt1, Register cnt2,
7270                                       int int_cnt2,  Register result,
7271                                       XMMRegister vec, Register tmp,
7272                                       int ae) {
7273   ShortBranchVerifier sbv(this);
7274   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7275   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7276 
7277   // This method uses the pcmpestri instruction with bound registers
7278   //   inputs:
7279   //     xmm - substring
7280   //     rax - substring length (elements count)
7281   //     mem - scanned string
7282   //     rdx - string length (elements count)
7283   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7284   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7285   //   outputs:
7286   //     rcx - matched index in string
7287   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7288   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7289   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7290   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7291   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7292 
7293   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7294         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7295         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7296 
7297   // Note, inline_string_indexOf() generates checks:
7298   // if (substr.count > string.count) return -1;
7299   // if (substr.count == 0) return 0;
7300   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7301 
7302   // Load substring.
7303   if (ae == StrIntrinsicNode::UL) {
7304     pmovzxbw(vec, Address(str2, 0));
7305   } else {
7306     movdqu(vec, Address(str2, 0));
7307   }
7308   movl(cnt2, int_cnt2);
7309   movptr(result, str1); // string addr
7310 
7311   if (int_cnt2 > stride) {
7312     jmpb(SCAN_TO_SUBSTR);
7313 
7314     // Reload substr for rescan, this code
7315     // is executed only for large substrings (> 8 chars)
7316     bind(RELOAD_SUBSTR);
7317     if (ae == StrIntrinsicNode::UL) {
7318       pmovzxbw(vec, Address(str2, 0));
7319     } else {
7320       movdqu(vec, Address(str2, 0));
7321     }
7322     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7323 
7324     bind(RELOAD_STR);
7325     // We came here after the beginning of the substring was
7326     // matched but the rest of it was not so we need to search
7327     // again. Start from the next element after the previous match.
7328 
7329     // cnt2 is number of substring reminding elements and
7330     // cnt1 is number of string reminding elements when cmp failed.
7331     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7332     subl(cnt1, cnt2);
7333     addl(cnt1, int_cnt2);
7334     movl(cnt2, int_cnt2); // Now restore cnt2
7335 
7336     decrementl(cnt1);     // Shift to next element
7337     cmpl(cnt1, cnt2);
7338     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7339 
7340     addptr(result, (1<<scale1));
7341 
7342   } // (int_cnt2 > 8)
7343 
7344   // Scan string for start of substr in 16-byte vectors
7345   bind(SCAN_TO_SUBSTR);
7346   pcmpestri(vec, Address(result, 0), mode);
7347   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7348   subl(cnt1, stride);
7349   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7350   cmpl(cnt1, cnt2);
7351   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7352   addptr(result, 16);
7353   jmpb(SCAN_TO_SUBSTR);
7354 
7355   // Found a potential substr
7356   bind(FOUND_CANDIDATE);
7357   // Matched whole vector if first element matched (tmp(rcx) == 0).
7358   if (int_cnt2 == stride) {
7359     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7360   } else { // int_cnt2 > 8
7361     jccb(Assembler::overflow, FOUND_SUBSTR);
7362   }
7363   // After pcmpestri tmp(rcx) contains matched element index
7364   // Compute start addr of substr
7365   lea(result, Address(result, tmp, scale1));
7366 
7367   // Make sure string is still long enough
7368   subl(cnt1, tmp);
7369   cmpl(cnt1, cnt2);
7370   if (int_cnt2 == stride) {
7371     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7372   } else { // int_cnt2 > 8
7373     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7374   }
7375   // Left less then substring.
7376 
7377   bind(RET_NOT_FOUND);
7378   movl(result, -1);
7379   jmp(EXIT);
7380 
7381   if (int_cnt2 > stride) {
7382     // This code is optimized for the case when whole substring
7383     // is matched if its head is matched.
7384     bind(MATCH_SUBSTR_HEAD);
7385     pcmpestri(vec, Address(result, 0), mode);
7386     // Reload only string if does not match
7387     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7388 
7389     Label CONT_SCAN_SUBSTR;
7390     // Compare the rest of substring (> 8 chars).
7391     bind(FOUND_SUBSTR);
7392     // First 8 chars are already matched.
7393     negptr(cnt2);
7394     addptr(cnt2, stride);
7395 
7396     bind(SCAN_SUBSTR);
7397     subl(cnt1, stride);
7398     cmpl(cnt2, -stride); // Do not read beyond substring
7399     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7400     // Back-up strings to avoid reading beyond substring:
7401     // cnt1 = cnt1 - cnt2 + 8
7402     addl(cnt1, cnt2); // cnt2 is negative
7403     addl(cnt1, stride);
7404     movl(cnt2, stride); negptr(cnt2);
7405     bind(CONT_SCAN_SUBSTR);
7406     if (int_cnt2 < (int)G) {
7407       int tail_off1 = int_cnt2<<scale1;
7408       int tail_off2 = int_cnt2<<scale2;
7409       if (ae == StrIntrinsicNode::UL) {
7410         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7411       } else {
7412         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7413       }
7414       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7415     } else {
7416       // calculate index in register to avoid integer overflow (int_cnt2*2)
7417       movl(tmp, int_cnt2);
7418       addptr(tmp, cnt2);
7419       if (ae == StrIntrinsicNode::UL) {
7420         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7421       } else {
7422         movdqu(vec, Address(str2, tmp, scale2, 0));
7423       }
7424       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7425     }
7426     // Need to reload strings pointers if not matched whole vector
7427     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7428     addptr(cnt2, stride);
7429     jcc(Assembler::negative, SCAN_SUBSTR);
7430     // Fall through if found full substring
7431 
7432   } // (int_cnt2 > 8)
7433 
7434   bind(RET_FOUND);
7435   // Found result if we matched full small substring.
7436   // Compute substr offset
7437   subptr(result, str1);
7438   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7439     shrl(result, 1); // index
7440   }
7441   bind(EXIT);
7442 
7443 } // string_indexofC8
7444 
7445 // Small strings are loaded through stack if they cross page boundary.
7446 void MacroAssembler::string_indexof(Register str1, Register str2,
7447                                     Register cnt1, Register cnt2,
7448                                     int int_cnt2,  Register result,
7449                                     XMMRegister vec, Register tmp,
7450                                     int ae) {
7451   ShortBranchVerifier sbv(this);
7452   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7453   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7454 
7455   //
7456   // int_cnt2 is length of small (< 8 chars) constant substring
7457   // or (-1) for non constant substring in which case its length
7458   // is in cnt2 register.
7459   //
7460   // Note, inline_string_indexOf() generates checks:
7461   // if (substr.count > string.count) return -1;
7462   // if (substr.count == 0) return 0;
7463   //
7464   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7465   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7466   // This method uses the pcmpestri instruction with bound registers
7467   //   inputs:
7468   //     xmm - substring
7469   //     rax - substring length (elements count)
7470   //     mem - scanned string
7471   //     rdx - string length (elements count)
7472   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7473   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7474   //   outputs:
7475   //     rcx - matched index in string
7476   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7477   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7478   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7479   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7480 
7481   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7482         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7483         FOUND_CANDIDATE;
7484 
7485   { //========================================================
7486     // We don't know where these strings are located
7487     // and we can't read beyond them. Load them through stack.
7488     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7489 
7490     movptr(tmp, rsp); // save old SP
7491 
7492     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7493       if (int_cnt2 == (1>>scale2)) { // One byte
7494         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7495         load_unsigned_byte(result, Address(str2, 0));
7496         movdl(vec, result); // move 32 bits
7497       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7498         // Not enough header space in 32-bit VM: 12+3 = 15.
7499         movl(result, Address(str2, -1));
7500         shrl(result, 8);
7501         movdl(vec, result); // move 32 bits
7502       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7503         load_unsigned_short(result, Address(str2, 0));
7504         movdl(vec, result); // move 32 bits
7505       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7506         movdl(vec, Address(str2, 0)); // move 32 bits
7507       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7508         movq(vec, Address(str2, 0));  // move 64 bits
7509       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7510         // Array header size is 12 bytes in 32-bit VM
7511         // + 6 bytes for 3 chars == 18 bytes,
7512         // enough space to load vec and shift.
7513         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7514         if (ae == StrIntrinsicNode::UL) {
7515           int tail_off = int_cnt2-8;
7516           pmovzxbw(vec, Address(str2, tail_off));
7517           psrldq(vec, -2*tail_off);
7518         }
7519         else {
7520           int tail_off = int_cnt2*(1<<scale2);
7521           movdqu(vec, Address(str2, tail_off-16));
7522           psrldq(vec, 16-tail_off);
7523         }
7524       }
7525     } else { // not constant substring
7526       cmpl(cnt2, stride);
7527       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7528 
7529       // We can read beyond string if srt+16 does not cross page boundary
7530       // since heaps are aligned and mapped by pages.
7531       assert(os::vm_page_size() < (int)G, "default page should be small");
7532       movl(result, str2); // We need only low 32 bits
7533       andl(result, (os::vm_page_size()-1));
7534       cmpl(result, (os::vm_page_size()-16));
7535       jccb(Assembler::belowEqual, CHECK_STR);
7536 
7537       // Move small strings to stack to allow load 16 bytes into vec.
7538       subptr(rsp, 16);
7539       int stk_offset = wordSize-(1<<scale2);
7540       push(cnt2);
7541 
7542       bind(COPY_SUBSTR);
7543       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7544         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7545         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7546       } else if (ae == StrIntrinsicNode::UU) {
7547         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7548         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7549       }
7550       decrement(cnt2);
7551       jccb(Assembler::notZero, COPY_SUBSTR);
7552 
7553       pop(cnt2);
7554       movptr(str2, rsp);  // New substring address
7555     } // non constant
7556 
7557     bind(CHECK_STR);
7558     cmpl(cnt1, stride);
7559     jccb(Assembler::aboveEqual, BIG_STRINGS);
7560 
7561     // Check cross page boundary.
7562     movl(result, str1); // We need only low 32 bits
7563     andl(result, (os::vm_page_size()-1));
7564     cmpl(result, (os::vm_page_size()-16));
7565     jccb(Assembler::belowEqual, BIG_STRINGS);
7566 
7567     subptr(rsp, 16);
7568     int stk_offset = -(1<<scale1);
7569     if (int_cnt2 < 0) { // not constant
7570       push(cnt2);
7571       stk_offset += wordSize;
7572     }
7573     movl(cnt2, cnt1);
7574 
7575     bind(COPY_STR);
7576     if (ae == StrIntrinsicNode::LL) {
7577       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7578       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7579     } else {
7580       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7581       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7582     }
7583     decrement(cnt2);
7584     jccb(Assembler::notZero, COPY_STR);
7585 
7586     if (int_cnt2 < 0) { // not constant
7587       pop(cnt2);
7588     }
7589     movptr(str1, rsp);  // New string address
7590 
7591     bind(BIG_STRINGS);
7592     // Load substring.
7593     if (int_cnt2 < 0) { // -1
7594       if (ae == StrIntrinsicNode::UL) {
7595         pmovzxbw(vec, Address(str2, 0));
7596       } else {
7597         movdqu(vec, Address(str2, 0));
7598       }
7599       push(cnt2);       // substr count
7600       push(str2);       // substr addr
7601       push(str1);       // string addr
7602     } else {
7603       // Small (< 8 chars) constant substrings are loaded already.
7604       movl(cnt2, int_cnt2);
7605     }
7606     push(tmp);  // original SP
7607 
7608   } // Finished loading
7609 
7610   //========================================================
7611   // Start search
7612   //
7613 
7614   movptr(result, str1); // string addr
7615 
7616   if (int_cnt2  < 0) {  // Only for non constant substring
7617     jmpb(SCAN_TO_SUBSTR);
7618 
7619     // SP saved at sp+0
7620     // String saved at sp+1*wordSize
7621     // Substr saved at sp+2*wordSize
7622     // Substr count saved at sp+3*wordSize
7623 
7624     // Reload substr for rescan, this code
7625     // is executed only for large substrings (> 8 chars)
7626     bind(RELOAD_SUBSTR);
7627     movptr(str2, Address(rsp, 2*wordSize));
7628     movl(cnt2, Address(rsp, 3*wordSize));
7629     if (ae == StrIntrinsicNode::UL) {
7630       pmovzxbw(vec, Address(str2, 0));
7631     } else {
7632       movdqu(vec, Address(str2, 0));
7633     }
7634     // We came here after the beginning of the substring was
7635     // matched but the rest of it was not so we need to search
7636     // again. Start from the next element after the previous match.
7637     subptr(str1, result); // Restore counter
7638     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7639       shrl(str1, 1);
7640     }
7641     addl(cnt1, str1);
7642     decrementl(cnt1);   // Shift to next element
7643     cmpl(cnt1, cnt2);
7644     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7645 
7646     addptr(result, (1<<scale1));
7647   } // non constant
7648 
7649   // Scan string for start of substr in 16-byte vectors
7650   bind(SCAN_TO_SUBSTR);
7651   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7652   pcmpestri(vec, Address(result, 0), mode);
7653   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7654   subl(cnt1, stride);
7655   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7656   cmpl(cnt1, cnt2);
7657   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7658   addptr(result, 16);
7659 
7660   bind(ADJUST_STR);
7661   cmpl(cnt1, stride); // Do not read beyond string
7662   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7663   // Back-up string to avoid reading beyond string.
7664   lea(result, Address(result, cnt1, scale1, -16));
7665   movl(cnt1, stride);
7666   jmpb(SCAN_TO_SUBSTR);
7667 
7668   // Found a potential substr
7669   bind(FOUND_CANDIDATE);
7670   // After pcmpestri tmp(rcx) contains matched element index
7671 
7672   // Make sure string is still long enough
7673   subl(cnt1, tmp);
7674   cmpl(cnt1, cnt2);
7675   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7676   // Left less then substring.
7677 
7678   bind(RET_NOT_FOUND);
7679   movl(result, -1);
7680   jmpb(CLEANUP);
7681 
7682   bind(FOUND_SUBSTR);
7683   // Compute start addr of substr
7684   lea(result, Address(result, tmp, scale1));
7685   if (int_cnt2 > 0) { // Constant substring
7686     // Repeat search for small substring (< 8 chars)
7687     // from new point without reloading substring.
7688     // Have to check that we don't read beyond string.
7689     cmpl(tmp, stride-int_cnt2);
7690     jccb(Assembler::greater, ADJUST_STR);
7691     // Fall through if matched whole substring.
7692   } else { // non constant
7693     assert(int_cnt2 == -1, "should be != 0");
7694 
7695     addl(tmp, cnt2);
7696     // Found result if we matched whole substring.
7697     cmpl(tmp, stride);
7698     jccb(Assembler::lessEqual, RET_FOUND);
7699 
7700     // Repeat search for small substring (<= 8 chars)
7701     // from new point 'str1' without reloading substring.
7702     cmpl(cnt2, stride);
7703     // Have to check that we don't read beyond string.
7704     jccb(Assembler::lessEqual, ADJUST_STR);
7705 
7706     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7707     // Compare the rest of substring (> 8 chars).
7708     movptr(str1, result);
7709 
7710     cmpl(tmp, cnt2);
7711     // First 8 chars are already matched.
7712     jccb(Assembler::equal, CHECK_NEXT);
7713 
7714     bind(SCAN_SUBSTR);
7715     pcmpestri(vec, Address(str1, 0), mode);
7716     // Need to reload strings pointers if not matched whole vector
7717     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7718 
7719     bind(CHECK_NEXT);
7720     subl(cnt2, stride);
7721     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7722     addptr(str1, 16);
7723     if (ae == StrIntrinsicNode::UL) {
7724       addptr(str2, 8);
7725     } else {
7726       addptr(str2, 16);
7727     }
7728     subl(cnt1, stride);
7729     cmpl(cnt2, stride); // Do not read beyond substring
7730     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7731     // Back-up strings to avoid reading beyond substring.
7732 
7733     if (ae == StrIntrinsicNode::UL) {
7734       lea(str2, Address(str2, cnt2, scale2, -8));
7735       lea(str1, Address(str1, cnt2, scale1, -16));
7736     } else {
7737       lea(str2, Address(str2, cnt2, scale2, -16));
7738       lea(str1, Address(str1, cnt2, scale1, -16));
7739     }
7740     subl(cnt1, cnt2);
7741     movl(cnt2, stride);
7742     addl(cnt1, stride);
7743     bind(CONT_SCAN_SUBSTR);
7744     if (ae == StrIntrinsicNode::UL) {
7745       pmovzxbw(vec, Address(str2, 0));
7746     } else {
7747       movdqu(vec, Address(str2, 0));
7748     }
7749     jmp(SCAN_SUBSTR);
7750 
7751     bind(RET_FOUND_LONG);
7752     movptr(str1, Address(rsp, wordSize));
7753   } // non constant
7754 
7755   bind(RET_FOUND);
7756   // Compute substr offset
7757   subptr(result, str1);
7758   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7759     shrl(result, 1); // index
7760   }
7761   bind(CLEANUP);
7762   pop(rsp); // restore SP
7763 
7764 } // string_indexof
7765 
7766 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7767                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7768   ShortBranchVerifier sbv(this);
7769   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7770 
7771   int stride = 8;
7772 
7773   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7774         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7775         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7776         FOUND_SEQ_CHAR, DONE_LABEL;
7777 
7778   movptr(result, str1);
7779   if (UseAVX >= 2) {
7780     cmpl(cnt1, stride);
7781     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7782     cmpl(cnt1, 2*stride);
7783     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7784     movdl(vec1, ch);
7785     vpbroadcastw(vec1, vec1);
7786     vpxor(vec2, vec2);
7787     movl(tmp, cnt1);
7788     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7789     andl(cnt1,0x0000000F);  //tail count (in chars)
7790 
7791     bind(SCAN_TO_16_CHAR_LOOP);
7792     vmovdqu(vec3, Address(result, 0));
7793     vpcmpeqw(vec3, vec3, vec1, 1);
7794     vptest(vec2, vec3);
7795     jcc(Assembler::carryClear, FOUND_CHAR);
7796     addptr(result, 32);
7797     subl(tmp, 2*stride);
7798     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7799     jmp(SCAN_TO_8_CHAR);
7800     bind(SCAN_TO_8_CHAR_INIT);
7801     movdl(vec1, ch);
7802     pshuflw(vec1, vec1, 0x00);
7803     pshufd(vec1, vec1, 0);
7804     pxor(vec2, vec2);
7805   }
7806   bind(SCAN_TO_8_CHAR);
7807   cmpl(cnt1, stride);
7808   if (UseAVX >= 2) {
7809     jcc(Assembler::less, SCAN_TO_CHAR);
7810   } else {
7811     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7812     movdl(vec1, ch);
7813     pshuflw(vec1, vec1, 0x00);
7814     pshufd(vec1, vec1, 0);
7815     pxor(vec2, vec2);
7816   }
7817   movl(tmp, cnt1);
7818   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7819   andl(cnt1,0x00000007);  //tail count (in chars)
7820 
7821   bind(SCAN_TO_8_CHAR_LOOP);
7822   movdqu(vec3, Address(result, 0));
7823   pcmpeqw(vec3, vec1);
7824   ptest(vec2, vec3);
7825   jcc(Assembler::carryClear, FOUND_CHAR);
7826   addptr(result, 16);
7827   subl(tmp, stride);
7828   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7829   bind(SCAN_TO_CHAR);
7830   testl(cnt1, cnt1);
7831   jcc(Assembler::zero, RET_NOT_FOUND);
7832   bind(SCAN_TO_CHAR_LOOP);
7833   load_unsigned_short(tmp, Address(result, 0));
7834   cmpl(ch, tmp);
7835   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7836   addptr(result, 2);
7837   subl(cnt1, 1);
7838   jccb(Assembler::zero, RET_NOT_FOUND);
7839   jmp(SCAN_TO_CHAR_LOOP);
7840 
7841   bind(RET_NOT_FOUND);
7842   movl(result, -1);
7843   jmpb(DONE_LABEL);
7844 
7845   bind(FOUND_CHAR);
7846   if (UseAVX >= 2) {
7847     vpmovmskb(tmp, vec3);
7848   } else {
7849     pmovmskb(tmp, vec3);
7850   }
7851   bsfl(ch, tmp);
7852   addl(result, ch);
7853 
7854   bind(FOUND_SEQ_CHAR);
7855   subptr(result, str1);
7856   shrl(result, 1);
7857 
7858   bind(DONE_LABEL);
7859 } // string_indexof_char
7860 
7861 // helper function for string_compare
7862 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7863                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7864                                         Address::ScaleFactor scale2, Register index, int ae) {
7865   if (ae == StrIntrinsicNode::LL) {
7866     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7867     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7868   } else if (ae == StrIntrinsicNode::UU) {
7869     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7870     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7871   } else {
7872     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7873     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7874   }
7875 }
7876 
7877 // Compare strings, used for char[] and byte[].
7878 void MacroAssembler::string_compare(Register str1, Register str2,
7879                                     Register cnt1, Register cnt2, Register result,
7880                                     XMMRegister vec1, int ae) {
7881   ShortBranchVerifier sbv(this);
7882   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7883   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7884   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7885   int stride2x2 = 0x40;
7886   Address::ScaleFactor scale = Address::no_scale;
7887   Address::ScaleFactor scale1 = Address::no_scale;
7888   Address::ScaleFactor scale2 = Address::no_scale;
7889 
7890   if (ae != StrIntrinsicNode::LL) {
7891     stride2x2 = 0x20;
7892   }
7893 
7894   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7895     shrl(cnt2, 1);
7896   }
7897   // Compute the minimum of the string lengths and the
7898   // difference of the string lengths (stack).
7899   // Do the conditional move stuff
7900   movl(result, cnt1);
7901   subl(cnt1, cnt2);
7902   push(cnt1);
7903   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7904 
7905   // Is the minimum length zero?
7906   testl(cnt2, cnt2);
7907   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7908   if (ae == StrIntrinsicNode::LL) {
7909     // Load first bytes
7910     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7911     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7912   } else if (ae == StrIntrinsicNode::UU) {
7913     // Load first characters
7914     load_unsigned_short(result, Address(str1, 0));
7915     load_unsigned_short(cnt1, Address(str2, 0));
7916   } else {
7917     load_unsigned_byte(result, Address(str1, 0));
7918     load_unsigned_short(cnt1, Address(str2, 0));
7919   }
7920   subl(result, cnt1);
7921   jcc(Assembler::notZero,  POP_LABEL);
7922 
7923   if (ae == StrIntrinsicNode::UU) {
7924     // Divide length by 2 to get number of chars
7925     shrl(cnt2, 1);
7926   }
7927   cmpl(cnt2, 1);
7928   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7929 
7930   // Check if the strings start at the same location and setup scale and stride
7931   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7932     cmpptr(str1, str2);
7933     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7934     if (ae == StrIntrinsicNode::LL) {
7935       scale = Address::times_1;
7936       stride = 16;
7937     } else {
7938       scale = Address::times_2;
7939       stride = 8;
7940     }
7941   } else {
7942     scale1 = Address::times_1;
7943     scale2 = Address::times_2;
7944     // scale not used
7945     stride = 8;
7946   }
7947 
7948   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7949     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7950     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7951     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7952     Label COMPARE_TAIL_LONG;
7953     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7954 
7955     int pcmpmask = 0x19;
7956     if (ae == StrIntrinsicNode::LL) {
7957       pcmpmask &= ~0x01;
7958     }
7959 
7960     // Setup to compare 16-chars (32-bytes) vectors,
7961     // start from first character again because it has aligned address.
7962     if (ae == StrIntrinsicNode::LL) {
7963       stride2 = 32;
7964     } else {
7965       stride2 = 16;
7966     }
7967     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7968       adr_stride = stride << scale;
7969     } else {
7970       adr_stride1 = 8;  //stride << scale1;
7971       adr_stride2 = 16; //stride << scale2;
7972     }
7973 
7974     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7975     // rax and rdx are used by pcmpestri as elements counters
7976     movl(result, cnt2);
7977     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7978     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7979 
7980     // fast path : compare first 2 8-char vectors.
7981     bind(COMPARE_16_CHARS);
7982     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7983       movdqu(vec1, Address(str1, 0));
7984     } else {
7985       pmovzxbw(vec1, Address(str1, 0));
7986     }
7987     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7988     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7989 
7990     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7991       movdqu(vec1, Address(str1, adr_stride));
7992       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7993     } else {
7994       pmovzxbw(vec1, Address(str1, adr_stride1));
7995       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7996     }
7997     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7998     addl(cnt1, stride);
7999 
8000     // Compare the characters at index in cnt1
8001     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8002     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8003     subl(result, cnt2);
8004     jmp(POP_LABEL);
8005 
8006     // Setup the registers to start vector comparison loop
8007     bind(COMPARE_WIDE_VECTORS);
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     subl(result, stride2);
8016     subl(cnt2, stride2);
8017     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8018     negptr(result);
8019 
8020     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8021     bind(COMPARE_WIDE_VECTORS_LOOP);
8022 
8023 #ifdef _LP64
8024     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8025       cmpl(cnt2, stride2x2);
8026       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8027       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8028       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8029 
8030       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8031       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8032         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8033         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8034       } else {
8035         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8036         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8037       }
8038       kortestql(k7, k7);
8039       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8040       addptr(result, stride2x2);  // update since we already compared at this addr
8041       subl(cnt2, stride2x2);      // and sub the size too
8042       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8043 
8044       vpxor(vec1, vec1);
8045       jmpb(COMPARE_WIDE_TAIL);
8046     }//if (VM_Version::supports_avx512vlbw())
8047 #endif // _LP64
8048 
8049 
8050     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8051     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8052       vmovdqu(vec1, Address(str1, result, scale));
8053       vpxor(vec1, Address(str2, result, scale));
8054     } else {
8055       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8056       vpxor(vec1, Address(str2, result, scale2));
8057     }
8058     vptest(vec1, vec1);
8059     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8060     addptr(result, stride2);
8061     subl(cnt2, stride2);
8062     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8063     // clean upper bits of YMM registers
8064     vpxor(vec1, vec1);
8065 
8066     // compare wide vectors tail
8067     bind(COMPARE_WIDE_TAIL);
8068     testptr(result, result);
8069     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8070 
8071     movl(result, stride2);
8072     movl(cnt2, result);
8073     negptr(result);
8074     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8075 
8076     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8077     bind(VECTOR_NOT_EQUAL);
8078     // clean upper bits of YMM registers
8079     vpxor(vec1, vec1);
8080     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8081       lea(str1, Address(str1, result, scale));
8082       lea(str2, Address(str2, result, scale));
8083     } else {
8084       lea(str1, Address(str1, result, scale1));
8085       lea(str2, Address(str2, result, scale2));
8086     }
8087     jmp(COMPARE_16_CHARS);
8088 
8089     // Compare tail chars, length between 1 to 15 chars
8090     bind(COMPARE_TAIL_LONG);
8091     movl(cnt2, result);
8092     cmpl(cnt2, stride);
8093     jcc(Assembler::less, COMPARE_SMALL_STR);
8094 
8095     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8096       movdqu(vec1, Address(str1, 0));
8097     } else {
8098       pmovzxbw(vec1, Address(str1, 0));
8099     }
8100     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8101     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8102     subptr(cnt2, stride);
8103     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8104     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8105       lea(str1, Address(str1, result, scale));
8106       lea(str2, Address(str2, result, scale));
8107     } else {
8108       lea(str1, Address(str1, result, scale1));
8109       lea(str2, Address(str2, result, scale2));
8110     }
8111     negptr(cnt2);
8112     jmpb(WHILE_HEAD_LABEL);
8113 
8114     bind(COMPARE_SMALL_STR);
8115   } else if (UseSSE42Intrinsics) {
8116     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8117     int pcmpmask = 0x19;
8118     // Setup to compare 8-char (16-byte) vectors,
8119     // start from first character again because it has aligned address.
8120     movl(result, cnt2);
8121     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8122     if (ae == StrIntrinsicNode::LL) {
8123       pcmpmask &= ~0x01;
8124     }
8125     jcc(Assembler::zero, COMPARE_TAIL);
8126     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8127       lea(str1, Address(str1, result, scale));
8128       lea(str2, Address(str2, result, scale));
8129     } else {
8130       lea(str1, Address(str1, result, scale1));
8131       lea(str2, Address(str2, result, scale2));
8132     }
8133     negptr(result);
8134 
8135     // pcmpestri
8136     //   inputs:
8137     //     vec1- substring
8138     //     rax - negative string length (elements count)
8139     //     mem - scanned string
8140     //     rdx - string length (elements count)
8141     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8142     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8143     //   outputs:
8144     //     rcx - first mismatched element index
8145     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8146 
8147     bind(COMPARE_WIDE_VECTORS);
8148     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8149       movdqu(vec1, Address(str1, result, scale));
8150       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8151     } else {
8152       pmovzxbw(vec1, Address(str1, result, scale1));
8153       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8154     }
8155     // After pcmpestri cnt1(rcx) contains mismatched element index
8156 
8157     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8158     addptr(result, stride);
8159     subptr(cnt2, stride);
8160     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8161 
8162     // compare wide vectors tail
8163     testptr(result, result);
8164     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8165 
8166     movl(cnt2, stride);
8167     movl(result, stride);
8168     negptr(result);
8169     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8170       movdqu(vec1, Address(str1, result, scale));
8171       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8172     } else {
8173       pmovzxbw(vec1, Address(str1, result, scale1));
8174       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8175     }
8176     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8177 
8178     // Mismatched characters in the vectors
8179     bind(VECTOR_NOT_EQUAL);
8180     addptr(cnt1, result);
8181     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8182     subl(result, cnt2);
8183     jmpb(POP_LABEL);
8184 
8185     bind(COMPARE_TAIL); // limit is zero
8186     movl(cnt2, result);
8187     // Fallthru to tail compare
8188   }
8189   // Shift str2 and str1 to the end of the arrays, negate min
8190   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8191     lea(str1, Address(str1, cnt2, scale));
8192     lea(str2, Address(str2, cnt2, scale));
8193   } else {
8194     lea(str1, Address(str1, cnt2, scale1));
8195     lea(str2, Address(str2, cnt2, scale2));
8196   }
8197   decrementl(cnt2);  // first character was compared already
8198   negptr(cnt2);
8199 
8200   // Compare the rest of the elements
8201   bind(WHILE_HEAD_LABEL);
8202   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8203   subl(result, cnt1);
8204   jccb(Assembler::notZero, POP_LABEL);
8205   increment(cnt2);
8206   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8207 
8208   // Strings are equal up to min length.  Return the length difference.
8209   bind(LENGTH_DIFF_LABEL);
8210   pop(result);
8211   if (ae == StrIntrinsicNode::UU) {
8212     // Divide diff by 2 to get number of chars
8213     sarl(result, 1);
8214   }
8215   jmpb(DONE_LABEL);
8216 
8217 #ifdef _LP64
8218   if (VM_Version::supports_avx512vlbw()) {
8219 
8220     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8221 
8222     kmovql(cnt1, k7);
8223     notq(cnt1);
8224     bsfq(cnt2, cnt1);
8225     if (ae != StrIntrinsicNode::LL) {
8226       // Divide diff by 2 to get number of chars
8227       sarl(cnt2, 1);
8228     }
8229     addq(result, cnt2);
8230     if (ae == StrIntrinsicNode::LL) {
8231       load_unsigned_byte(cnt1, Address(str2, result));
8232       load_unsigned_byte(result, Address(str1, result));
8233     } else if (ae == StrIntrinsicNode::UU) {
8234       load_unsigned_short(cnt1, Address(str2, result, scale));
8235       load_unsigned_short(result, Address(str1, result, scale));
8236     } else {
8237       load_unsigned_short(cnt1, Address(str2, result, scale2));
8238       load_unsigned_byte(result, Address(str1, result, scale1));
8239     }
8240     subl(result, cnt1);
8241     jmpb(POP_LABEL);
8242   }//if (VM_Version::supports_avx512vlbw())
8243 #endif // _LP64
8244 
8245   // Discard the stored length difference
8246   bind(POP_LABEL);
8247   pop(cnt1);
8248 
8249   // That's it
8250   bind(DONE_LABEL);
8251   if(ae == StrIntrinsicNode::UL) {
8252     negl(result);
8253   }
8254 
8255 }
8256 
8257 // Search for Non-ASCII character (Negative byte value) in a byte array,
8258 // return true if it has any and false otherwise.
8259 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8260 //   @HotSpotIntrinsicCandidate
8261 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8262 //     for (int i = off; i < off + len; i++) {
8263 //       if (ba[i] < 0) {
8264 //         return true;
8265 //       }
8266 //     }
8267 //     return false;
8268 //   }
8269 void MacroAssembler::has_negatives(Register ary1, Register len,
8270   Register result, Register tmp1,
8271   XMMRegister vec1, XMMRegister vec2) {
8272   // rsi: byte array
8273   // rcx: len
8274   // rax: result
8275   ShortBranchVerifier sbv(this);
8276   assert_different_registers(ary1, len, result, tmp1);
8277   assert_different_registers(vec1, vec2);
8278   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8279 
8280   // len == 0
8281   testl(len, len);
8282   jcc(Assembler::zero, FALSE_LABEL);
8283 
8284   if ((UseAVX > 2) && // AVX512
8285     VM_Version::supports_avx512vlbw() &&
8286     VM_Version::supports_bmi2()) {
8287 
8288     set_vector_masking();  // opening of the stub context for programming mask registers
8289 
8290     Label test_64_loop, test_tail;
8291     Register tmp3_aliased = len;
8292 
8293     movl(tmp1, len);
8294     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8295 
8296     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8297     andl(len, ~(64 - 1));    // vector count (in chars)
8298     jccb(Assembler::zero, test_tail);
8299 
8300     lea(ary1, Address(ary1, len, Address::times_1));
8301     negptr(len);
8302 
8303     bind(test_64_loop);
8304     // Check whether our 64 elements of size byte contain negatives
8305     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8306     kortestql(k2, k2);
8307     jcc(Assembler::notZero, TRUE_LABEL);
8308 
8309     addptr(len, 64);
8310     jccb(Assembler::notZero, test_64_loop);
8311 
8312 
8313     bind(test_tail);
8314     // bail out when there is nothing to be done
8315     testl(tmp1, -1);
8316     jcc(Assembler::zero, FALSE_LABEL);
8317 
8318     // Save k1
8319     kmovql(k3, k1);
8320 
8321     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8322 #ifdef _LP64
8323     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8324     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8325     notq(tmp3_aliased);
8326     kmovql(k1, tmp3_aliased);
8327 #else
8328     Label k_init;
8329     jmp(k_init);
8330 
8331     // We could not read 64-bits from a general purpose register thus we move
8332     // data required to compose 64 1's to the instruction stream
8333     // We emit 64 byte wide series of elements from 0..63 which later on would
8334     // be used as a compare targets with tail count contained in tmp1 register.
8335     // Result would be a k1 register having tmp1 consecutive number or 1
8336     // counting from least significant bit.
8337     address tmp = pc();
8338     emit_int64(0x0706050403020100);
8339     emit_int64(0x0F0E0D0C0B0A0908);
8340     emit_int64(0x1716151413121110);
8341     emit_int64(0x1F1E1D1C1B1A1918);
8342     emit_int64(0x2726252423222120);
8343     emit_int64(0x2F2E2D2C2B2A2928);
8344     emit_int64(0x3736353433323130);
8345     emit_int64(0x3F3E3D3C3B3A3938);
8346 
8347     bind(k_init);
8348     lea(len, InternalAddress(tmp));
8349     // create mask to test for negative byte inside a vector
8350     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8351     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8352 
8353 #endif
8354     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8355     ktestq(k2, k1);
8356     // Restore k1
8357     kmovql(k1, k3);
8358     jcc(Assembler::notZero, TRUE_LABEL);
8359 
8360     jmp(FALSE_LABEL);
8361 
8362     clear_vector_masking();   // closing of the stub context for programming mask registers
8363   } else {
8364     movl(result, len); // copy
8365 
8366     if (UseAVX == 2 && UseSSE >= 2) {
8367       // With AVX2, use 32-byte vector compare
8368       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8369 
8370       // Compare 32-byte vectors
8371       andl(result, 0x0000001f);  //   tail count (in bytes)
8372       andl(len, 0xffffffe0);   // vector count (in bytes)
8373       jccb(Assembler::zero, COMPARE_TAIL);
8374 
8375       lea(ary1, Address(ary1, len, Address::times_1));
8376       negptr(len);
8377 
8378       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8379       movdl(vec2, tmp1);
8380       vpbroadcastd(vec2, vec2);
8381 
8382       bind(COMPARE_WIDE_VECTORS);
8383       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8384       vptest(vec1, vec2);
8385       jccb(Assembler::notZero, TRUE_LABEL);
8386       addptr(len, 32);
8387       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8388 
8389       testl(result, result);
8390       jccb(Assembler::zero, FALSE_LABEL);
8391 
8392       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8393       vptest(vec1, vec2);
8394       jccb(Assembler::notZero, TRUE_LABEL);
8395       jmpb(FALSE_LABEL);
8396 
8397       bind(COMPARE_TAIL); // len is zero
8398       movl(len, result);
8399       // Fallthru to tail compare
8400     } else if (UseSSE42Intrinsics) {
8401       // With SSE4.2, use double quad vector compare
8402       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8403 
8404       // Compare 16-byte vectors
8405       andl(result, 0x0000000f);  //   tail count (in bytes)
8406       andl(len, 0xfffffff0);   // vector count (in bytes)
8407       jccb(Assembler::zero, COMPARE_TAIL);
8408 
8409       lea(ary1, Address(ary1, len, Address::times_1));
8410       negptr(len);
8411 
8412       movl(tmp1, 0x80808080);
8413       movdl(vec2, tmp1);
8414       pshufd(vec2, vec2, 0);
8415 
8416       bind(COMPARE_WIDE_VECTORS);
8417       movdqu(vec1, Address(ary1, len, Address::times_1));
8418       ptest(vec1, vec2);
8419       jccb(Assembler::notZero, TRUE_LABEL);
8420       addptr(len, 16);
8421       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8422 
8423       testl(result, result);
8424       jccb(Assembler::zero, FALSE_LABEL);
8425 
8426       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8427       ptest(vec1, vec2);
8428       jccb(Assembler::notZero, TRUE_LABEL);
8429       jmpb(FALSE_LABEL);
8430 
8431       bind(COMPARE_TAIL); // len is zero
8432       movl(len, result);
8433       // Fallthru to tail compare
8434     }
8435   }
8436   // Compare 4-byte vectors
8437   andl(len, 0xfffffffc); // vector count (in bytes)
8438   jccb(Assembler::zero, COMPARE_CHAR);
8439 
8440   lea(ary1, Address(ary1, len, Address::times_1));
8441   negptr(len);
8442 
8443   bind(COMPARE_VECTORS);
8444   movl(tmp1, Address(ary1, len, Address::times_1));
8445   andl(tmp1, 0x80808080);
8446   jccb(Assembler::notZero, TRUE_LABEL);
8447   addptr(len, 4);
8448   jcc(Assembler::notZero, COMPARE_VECTORS);
8449 
8450   // Compare trailing char (final 2 bytes), if any
8451   bind(COMPARE_CHAR);
8452   testl(result, 0x2);   // tail  char
8453   jccb(Assembler::zero, COMPARE_BYTE);
8454   load_unsigned_short(tmp1, Address(ary1, 0));
8455   andl(tmp1, 0x00008080);
8456   jccb(Assembler::notZero, TRUE_LABEL);
8457   subptr(result, 2);
8458   lea(ary1, Address(ary1, 2));
8459 
8460   bind(COMPARE_BYTE);
8461   testl(result, 0x1);   // tail  byte
8462   jccb(Assembler::zero, FALSE_LABEL);
8463   load_unsigned_byte(tmp1, Address(ary1, 0));
8464   andl(tmp1, 0x00000080);
8465   jccb(Assembler::notEqual, TRUE_LABEL);
8466   jmpb(FALSE_LABEL);
8467 
8468   bind(TRUE_LABEL);
8469   movl(result, 1);   // return true
8470   jmpb(DONE);
8471 
8472   bind(FALSE_LABEL);
8473   xorl(result, result); // return false
8474 
8475   // That's it
8476   bind(DONE);
8477   if (UseAVX >= 2 && UseSSE >= 2) {
8478     // clean upper bits of YMM registers
8479     vpxor(vec1, vec1);
8480     vpxor(vec2, vec2);
8481   }
8482 }
8483 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8484 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8485                                    Register limit, Register result, Register chr,
8486                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8487   ShortBranchVerifier sbv(this);
8488   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8489 
8490   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8491   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8492 
8493   if (is_array_equ) {
8494     // Check the input args
8495     cmpoop(ary1, ary2);
8496     jcc(Assembler::equal, TRUE_LABEL);
8497 
8498     // Need additional checks for arrays_equals.
8499     testptr(ary1, ary1);
8500     jcc(Assembler::zero, FALSE_LABEL);
8501     testptr(ary2, ary2);
8502     jcc(Assembler::zero, FALSE_LABEL);
8503 
8504     // Check the lengths
8505     movl(limit, Address(ary1, length_offset));
8506     cmpl(limit, Address(ary2, length_offset));
8507     jcc(Assembler::notEqual, FALSE_LABEL);
8508   }
8509 
8510   // count == 0
8511   testl(limit, limit);
8512   jcc(Assembler::zero, TRUE_LABEL);
8513 
8514   if (is_array_equ) {
8515     // Load array address
8516     lea(ary1, Address(ary1, base_offset));
8517     lea(ary2, Address(ary2, base_offset));
8518   }
8519 
8520   if (is_array_equ && is_char) {
8521     // arrays_equals when used for char[].
8522     shll(limit, 1);      // byte count != 0
8523   }
8524   movl(result, limit); // copy
8525 
8526   if (UseAVX >= 2) {
8527     // With AVX2, use 32-byte vector compare
8528     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8529 
8530     // Compare 32-byte vectors
8531     andl(result, 0x0000001f);  //   tail count (in bytes)
8532     andl(limit, 0xffffffe0);   // vector count (in bytes)
8533     jcc(Assembler::zero, COMPARE_TAIL);
8534 
8535     lea(ary1, Address(ary1, limit, Address::times_1));
8536     lea(ary2, Address(ary2, limit, Address::times_1));
8537     negptr(limit);
8538 
8539     bind(COMPARE_WIDE_VECTORS);
8540 
8541 #ifdef _LP64
8542     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8543       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8544 
8545       cmpl(limit, -64);
8546       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8547 
8548       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8549 
8550       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8551       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8552       kortestql(k7, k7);
8553       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8554       addptr(limit, 64);  // update since we already compared at this addr
8555       cmpl(limit, -64);
8556       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8557 
8558       // At this point we may still need to compare -limit+result bytes.
8559       // We could execute the next two instruction and just continue via non-wide path:
8560       //  cmpl(limit, 0);
8561       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8562       // But since we stopped at the points ary{1,2}+limit which are
8563       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8564       // (|limit| <= 32 and result < 32),
8565       // we may just compare the last 64 bytes.
8566       //
8567       addptr(result, -64);   // it is safe, bc we just came from this area
8568       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8569       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8570       kortestql(k7, k7);
8571       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8572 
8573       jmp(TRUE_LABEL);
8574 
8575       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8576 
8577     }//if (VM_Version::supports_avx512vlbw())
8578 #endif //_LP64
8579 
8580     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8581     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8582     vpxor(vec1, vec2);
8583 
8584     vptest(vec1, vec1);
8585     jcc(Assembler::notZero, FALSE_LABEL);
8586     addptr(limit, 32);
8587     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8588 
8589     testl(result, result);
8590     jcc(Assembler::zero, TRUE_LABEL);
8591 
8592     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8593     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8594     vpxor(vec1, vec2);
8595 
8596     vptest(vec1, vec1);
8597     jccb(Assembler::notZero, FALSE_LABEL);
8598     jmpb(TRUE_LABEL);
8599 
8600     bind(COMPARE_TAIL); // limit is zero
8601     movl(limit, result);
8602     // Fallthru to tail compare
8603   } else if (UseSSE42Intrinsics) {
8604     // With SSE4.2, use double quad vector compare
8605     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8606 
8607     // Compare 16-byte vectors
8608     andl(result, 0x0000000f);  //   tail count (in bytes)
8609     andl(limit, 0xfffffff0);   // vector count (in bytes)
8610     jcc(Assembler::zero, COMPARE_TAIL);
8611 
8612     lea(ary1, Address(ary1, limit, Address::times_1));
8613     lea(ary2, Address(ary2, limit, Address::times_1));
8614     negptr(limit);
8615 
8616     bind(COMPARE_WIDE_VECTORS);
8617     movdqu(vec1, Address(ary1, limit, Address::times_1));
8618     movdqu(vec2, Address(ary2, limit, Address::times_1));
8619     pxor(vec1, vec2);
8620 
8621     ptest(vec1, vec1);
8622     jcc(Assembler::notZero, FALSE_LABEL);
8623     addptr(limit, 16);
8624     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8625 
8626     testl(result, result);
8627     jcc(Assembler::zero, TRUE_LABEL);
8628 
8629     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8630     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8631     pxor(vec1, vec2);
8632 
8633     ptest(vec1, vec1);
8634     jccb(Assembler::notZero, FALSE_LABEL);
8635     jmpb(TRUE_LABEL);
8636 
8637     bind(COMPARE_TAIL); // limit is zero
8638     movl(limit, result);
8639     // Fallthru to tail compare
8640   }
8641 
8642   // Compare 4-byte vectors
8643   andl(limit, 0xfffffffc); // vector count (in bytes)
8644   jccb(Assembler::zero, COMPARE_CHAR);
8645 
8646   lea(ary1, Address(ary1, limit, Address::times_1));
8647   lea(ary2, Address(ary2, limit, Address::times_1));
8648   negptr(limit);
8649 
8650   bind(COMPARE_VECTORS);
8651   movl(chr, Address(ary1, limit, Address::times_1));
8652   cmpl(chr, Address(ary2, limit, Address::times_1));
8653   jccb(Assembler::notEqual, FALSE_LABEL);
8654   addptr(limit, 4);
8655   jcc(Assembler::notZero, COMPARE_VECTORS);
8656 
8657   // Compare trailing char (final 2 bytes), if any
8658   bind(COMPARE_CHAR);
8659   testl(result, 0x2);   // tail  char
8660   jccb(Assembler::zero, COMPARE_BYTE);
8661   load_unsigned_short(chr, Address(ary1, 0));
8662   load_unsigned_short(limit, Address(ary2, 0));
8663   cmpl(chr, limit);
8664   jccb(Assembler::notEqual, FALSE_LABEL);
8665 
8666   if (is_array_equ && is_char) {
8667     bind(COMPARE_BYTE);
8668   } else {
8669     lea(ary1, Address(ary1, 2));
8670     lea(ary2, Address(ary2, 2));
8671 
8672     bind(COMPARE_BYTE);
8673     testl(result, 0x1);   // tail  byte
8674     jccb(Assembler::zero, TRUE_LABEL);
8675     load_unsigned_byte(chr, Address(ary1, 0));
8676     load_unsigned_byte(limit, Address(ary2, 0));
8677     cmpl(chr, limit);
8678     jccb(Assembler::notEqual, FALSE_LABEL);
8679   }
8680   bind(TRUE_LABEL);
8681   movl(result, 1);   // return true
8682   jmpb(DONE);
8683 
8684   bind(FALSE_LABEL);
8685   xorl(result, result); // return false
8686 
8687   // That's it
8688   bind(DONE);
8689   if (UseAVX >= 2) {
8690     // clean upper bits of YMM registers
8691     vpxor(vec1, vec1);
8692     vpxor(vec2, vec2);
8693   }
8694 }
8695 
8696 #endif
8697 
8698 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8699                                    Register to, Register value, Register count,
8700                                    Register rtmp, XMMRegister xtmp) {
8701   ShortBranchVerifier sbv(this);
8702   assert_different_registers(to, value, count, rtmp);
8703   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8704   Label L_fill_2_bytes, L_fill_4_bytes;
8705 
8706   int shift = -1;
8707   switch (t) {
8708     case T_BYTE:
8709       shift = 2;
8710       break;
8711     case T_SHORT:
8712       shift = 1;
8713       break;
8714     case T_INT:
8715       shift = 0;
8716       break;
8717     default: ShouldNotReachHere();
8718   }
8719 
8720   if (t == T_BYTE) {
8721     andl(value, 0xff);
8722     movl(rtmp, value);
8723     shll(rtmp, 8);
8724     orl(value, rtmp);
8725   }
8726   if (t == T_SHORT) {
8727     andl(value, 0xffff);
8728   }
8729   if (t == T_BYTE || t == T_SHORT) {
8730     movl(rtmp, value);
8731     shll(rtmp, 16);
8732     orl(value, rtmp);
8733   }
8734 
8735   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8736   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8737   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8738     // align source address at 4 bytes address boundary
8739     if (t == T_BYTE) {
8740       // One byte misalignment happens only for byte arrays
8741       testptr(to, 1);
8742       jccb(Assembler::zero, L_skip_align1);
8743       movb(Address(to, 0), value);
8744       increment(to);
8745       decrement(count);
8746       BIND(L_skip_align1);
8747     }
8748     // Two bytes misalignment happens only for byte and short (char) arrays
8749     testptr(to, 2);
8750     jccb(Assembler::zero, L_skip_align2);
8751     movw(Address(to, 0), value);
8752     addptr(to, 2);
8753     subl(count, 1<<(shift-1));
8754     BIND(L_skip_align2);
8755   }
8756   if (UseSSE < 2) {
8757     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8758     // Fill 32-byte chunks
8759     subl(count, 8 << shift);
8760     jcc(Assembler::less, L_check_fill_8_bytes);
8761     align(16);
8762 
8763     BIND(L_fill_32_bytes_loop);
8764 
8765     for (int i = 0; i < 32; i += 4) {
8766       movl(Address(to, i), value);
8767     }
8768 
8769     addptr(to, 32);
8770     subl(count, 8 << shift);
8771     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8772     BIND(L_check_fill_8_bytes);
8773     addl(count, 8 << shift);
8774     jccb(Assembler::zero, L_exit);
8775     jmpb(L_fill_8_bytes);
8776 
8777     //
8778     // length is too short, just fill qwords
8779     //
8780     BIND(L_fill_8_bytes_loop);
8781     movl(Address(to, 0), value);
8782     movl(Address(to, 4), value);
8783     addptr(to, 8);
8784     BIND(L_fill_8_bytes);
8785     subl(count, 1 << (shift + 1));
8786     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8787     // fall through to fill 4 bytes
8788   } else {
8789     Label L_fill_32_bytes;
8790     if (!UseUnalignedLoadStores) {
8791       // align to 8 bytes, we know we are 4 byte aligned to start
8792       testptr(to, 4);
8793       jccb(Assembler::zero, L_fill_32_bytes);
8794       movl(Address(to, 0), value);
8795       addptr(to, 4);
8796       subl(count, 1<<shift);
8797     }
8798     BIND(L_fill_32_bytes);
8799     {
8800       assert( UseSSE >= 2, "supported cpu only" );
8801       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8802       if (UseAVX > 2) {
8803         movl(rtmp, 0xffff);
8804         kmovwl(k1, rtmp);
8805       }
8806       movdl(xtmp, value);
8807       if (UseAVX > 2 && UseUnalignedLoadStores) {
8808         // Fill 64-byte chunks
8809         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8810         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8811 
8812         subl(count, 16 << shift);
8813         jcc(Assembler::less, L_check_fill_32_bytes);
8814         align(16);
8815 
8816         BIND(L_fill_64_bytes_loop);
8817         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8818         addptr(to, 64);
8819         subl(count, 16 << shift);
8820         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8821 
8822         BIND(L_check_fill_32_bytes);
8823         addl(count, 8 << shift);
8824         jccb(Assembler::less, L_check_fill_8_bytes);
8825         vmovdqu(Address(to, 0), xtmp);
8826         addptr(to, 32);
8827         subl(count, 8 << shift);
8828 
8829         BIND(L_check_fill_8_bytes);
8830       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8831         // Fill 64-byte chunks
8832         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8833         vpbroadcastd(xtmp, xtmp);
8834 
8835         subl(count, 16 << shift);
8836         jcc(Assembler::less, L_check_fill_32_bytes);
8837         align(16);
8838 
8839         BIND(L_fill_64_bytes_loop);
8840         vmovdqu(Address(to, 0), xtmp);
8841         vmovdqu(Address(to, 32), xtmp);
8842         addptr(to, 64);
8843         subl(count, 16 << shift);
8844         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8845 
8846         BIND(L_check_fill_32_bytes);
8847         addl(count, 8 << shift);
8848         jccb(Assembler::less, L_check_fill_8_bytes);
8849         vmovdqu(Address(to, 0), xtmp);
8850         addptr(to, 32);
8851         subl(count, 8 << shift);
8852 
8853         BIND(L_check_fill_8_bytes);
8854         // clean upper bits of YMM registers
8855         movdl(xtmp, value);
8856         pshufd(xtmp, xtmp, 0);
8857       } else {
8858         // Fill 32-byte chunks
8859         pshufd(xtmp, xtmp, 0);
8860 
8861         subl(count, 8 << shift);
8862         jcc(Assembler::less, L_check_fill_8_bytes);
8863         align(16);
8864 
8865         BIND(L_fill_32_bytes_loop);
8866 
8867         if (UseUnalignedLoadStores) {
8868           movdqu(Address(to, 0), xtmp);
8869           movdqu(Address(to, 16), xtmp);
8870         } else {
8871           movq(Address(to, 0), xtmp);
8872           movq(Address(to, 8), xtmp);
8873           movq(Address(to, 16), xtmp);
8874           movq(Address(to, 24), xtmp);
8875         }
8876 
8877         addptr(to, 32);
8878         subl(count, 8 << shift);
8879         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8880 
8881         BIND(L_check_fill_8_bytes);
8882       }
8883       addl(count, 8 << shift);
8884       jccb(Assembler::zero, L_exit);
8885       jmpb(L_fill_8_bytes);
8886 
8887       //
8888       // length is too short, just fill qwords
8889       //
8890       BIND(L_fill_8_bytes_loop);
8891       movq(Address(to, 0), xtmp);
8892       addptr(to, 8);
8893       BIND(L_fill_8_bytes);
8894       subl(count, 1 << (shift + 1));
8895       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8896     }
8897   }
8898   // fill trailing 4 bytes
8899   BIND(L_fill_4_bytes);
8900   testl(count, 1<<shift);
8901   jccb(Assembler::zero, L_fill_2_bytes);
8902   movl(Address(to, 0), value);
8903   if (t == T_BYTE || t == T_SHORT) {
8904     addptr(to, 4);
8905     BIND(L_fill_2_bytes);
8906     // fill trailing 2 bytes
8907     testl(count, 1<<(shift-1));
8908     jccb(Assembler::zero, L_fill_byte);
8909     movw(Address(to, 0), value);
8910     if (t == T_BYTE) {
8911       addptr(to, 2);
8912       BIND(L_fill_byte);
8913       // fill trailing byte
8914       testl(count, 1);
8915       jccb(Assembler::zero, L_exit);
8916       movb(Address(to, 0), value);
8917     } else {
8918       BIND(L_fill_byte);
8919     }
8920   } else {
8921     BIND(L_fill_2_bytes);
8922   }
8923   BIND(L_exit);
8924 }
8925 
8926 // encode char[] to byte[] in ISO_8859_1
8927    //@HotSpotIntrinsicCandidate
8928    //private static int implEncodeISOArray(byte[] sa, int sp,
8929    //byte[] da, int dp, int len) {
8930    //  int i = 0;
8931    //  for (; i < len; i++) {
8932    //    char c = StringUTF16.getChar(sa, sp++);
8933    //    if (c > '\u00FF')
8934    //      break;
8935    //    da[dp++] = (byte)c;
8936    //  }
8937    //  return i;
8938    //}
8939 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8940   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8941   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8942   Register tmp5, Register result) {
8943 
8944   // rsi: src
8945   // rdi: dst
8946   // rdx: len
8947   // rcx: tmp5
8948   // rax: result
8949   ShortBranchVerifier sbv(this);
8950   assert_different_registers(src, dst, len, tmp5, result);
8951   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8952 
8953   // set result
8954   xorl(result, result);
8955   // check for zero length
8956   testl(len, len);
8957   jcc(Assembler::zero, L_done);
8958 
8959   movl(result, len);
8960 
8961   // Setup pointers
8962   lea(src, Address(src, len, Address::times_2)); // char[]
8963   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8964   negptr(len);
8965 
8966   if (UseSSE42Intrinsics || UseAVX >= 2) {
8967     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8968     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8969 
8970     if (UseAVX >= 2) {
8971       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8972       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8973       movdl(tmp1Reg, tmp5);
8974       vpbroadcastd(tmp1Reg, tmp1Reg);
8975       jmp(L_chars_32_check);
8976 
8977       bind(L_copy_32_chars);
8978       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8979       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8980       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8981       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8982       jccb(Assembler::notZero, L_copy_32_chars_exit);
8983       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8984       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8985       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8986 
8987       bind(L_chars_32_check);
8988       addptr(len, 32);
8989       jcc(Assembler::lessEqual, L_copy_32_chars);
8990 
8991       bind(L_copy_32_chars_exit);
8992       subptr(len, 16);
8993       jccb(Assembler::greater, L_copy_16_chars_exit);
8994 
8995     } else if (UseSSE42Intrinsics) {
8996       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8997       movdl(tmp1Reg, tmp5);
8998       pshufd(tmp1Reg, tmp1Reg, 0);
8999       jmpb(L_chars_16_check);
9000     }
9001 
9002     bind(L_copy_16_chars);
9003     if (UseAVX >= 2) {
9004       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9005       vptest(tmp2Reg, tmp1Reg);
9006       jcc(Assembler::notZero, L_copy_16_chars_exit);
9007       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9008       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9009     } else {
9010       if (UseAVX > 0) {
9011         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9012         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9013         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9014       } else {
9015         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9016         por(tmp2Reg, tmp3Reg);
9017         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9018         por(tmp2Reg, tmp4Reg);
9019       }
9020       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9021       jccb(Assembler::notZero, L_copy_16_chars_exit);
9022       packuswb(tmp3Reg, tmp4Reg);
9023     }
9024     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9025 
9026     bind(L_chars_16_check);
9027     addptr(len, 16);
9028     jcc(Assembler::lessEqual, L_copy_16_chars);
9029 
9030     bind(L_copy_16_chars_exit);
9031     if (UseAVX >= 2) {
9032       // clean upper bits of YMM registers
9033       vpxor(tmp2Reg, tmp2Reg);
9034       vpxor(tmp3Reg, tmp3Reg);
9035       vpxor(tmp4Reg, tmp4Reg);
9036       movdl(tmp1Reg, tmp5);
9037       pshufd(tmp1Reg, tmp1Reg, 0);
9038     }
9039     subptr(len, 8);
9040     jccb(Assembler::greater, L_copy_8_chars_exit);
9041 
9042     bind(L_copy_8_chars);
9043     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9044     ptest(tmp3Reg, tmp1Reg);
9045     jccb(Assembler::notZero, L_copy_8_chars_exit);
9046     packuswb(tmp3Reg, tmp1Reg);
9047     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9048     addptr(len, 8);
9049     jccb(Assembler::lessEqual, L_copy_8_chars);
9050 
9051     bind(L_copy_8_chars_exit);
9052     subptr(len, 8);
9053     jccb(Assembler::zero, L_done);
9054   }
9055 
9056   bind(L_copy_1_char);
9057   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9058   testl(tmp5, 0xff00);      // check if Unicode char
9059   jccb(Assembler::notZero, L_copy_1_char_exit);
9060   movb(Address(dst, len, Address::times_1, 0), tmp5);
9061   addptr(len, 1);
9062   jccb(Assembler::less, L_copy_1_char);
9063 
9064   bind(L_copy_1_char_exit);
9065   addptr(result, len); // len is negative count of not processed elements
9066 
9067   bind(L_done);
9068 }
9069 
9070 #ifdef _LP64
9071 /**
9072  * Helper for multiply_to_len().
9073  */
9074 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9075   addq(dest_lo, src1);
9076   adcq(dest_hi, 0);
9077   addq(dest_lo, src2);
9078   adcq(dest_hi, 0);
9079 }
9080 
9081 /**
9082  * Multiply 64 bit by 64 bit first loop.
9083  */
9084 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9085                                            Register y, Register y_idx, Register z,
9086                                            Register carry, Register product,
9087                                            Register idx, Register kdx) {
9088   //
9089   //  jlong carry, x[], y[], z[];
9090   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9091   //    huge_128 product = y[idx] * x[xstart] + carry;
9092   //    z[kdx] = (jlong)product;
9093   //    carry  = (jlong)(product >>> 64);
9094   //  }
9095   //  z[xstart] = carry;
9096   //
9097 
9098   Label L_first_loop, L_first_loop_exit;
9099   Label L_one_x, L_one_y, L_multiply;
9100 
9101   decrementl(xstart);
9102   jcc(Assembler::negative, L_one_x);
9103 
9104   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9105   rorq(x_xstart, 32); // convert big-endian to little-endian
9106 
9107   bind(L_first_loop);
9108   decrementl(idx);
9109   jcc(Assembler::negative, L_first_loop_exit);
9110   decrementl(idx);
9111   jcc(Assembler::negative, L_one_y);
9112   movq(y_idx, Address(y, idx, Address::times_4,  0));
9113   rorq(y_idx, 32); // convert big-endian to little-endian
9114   bind(L_multiply);
9115   movq(product, x_xstart);
9116   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9117   addq(product, carry);
9118   adcq(rdx, 0);
9119   subl(kdx, 2);
9120   movl(Address(z, kdx, Address::times_4,  4), product);
9121   shrq(product, 32);
9122   movl(Address(z, kdx, Address::times_4,  0), product);
9123   movq(carry, rdx);
9124   jmp(L_first_loop);
9125 
9126   bind(L_one_y);
9127   movl(y_idx, Address(y,  0));
9128   jmp(L_multiply);
9129 
9130   bind(L_one_x);
9131   movl(x_xstart, Address(x,  0));
9132   jmp(L_first_loop);
9133 
9134   bind(L_first_loop_exit);
9135 }
9136 
9137 /**
9138  * Multiply 64 bit by 64 bit and add 128 bit.
9139  */
9140 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9141                                             Register yz_idx, Register idx,
9142                                             Register carry, Register product, int offset) {
9143   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9144   //     z[kdx] = (jlong)product;
9145 
9146   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9147   rorq(yz_idx, 32); // convert big-endian to little-endian
9148   movq(product, x_xstart);
9149   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9150   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9151   rorq(yz_idx, 32); // convert big-endian to little-endian
9152 
9153   add2_with_carry(rdx, product, carry, yz_idx);
9154 
9155   movl(Address(z, idx, Address::times_4,  offset+4), product);
9156   shrq(product, 32);
9157   movl(Address(z, idx, Address::times_4,  offset), product);
9158 
9159 }
9160 
9161 /**
9162  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9163  */
9164 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9165                                              Register yz_idx, Register idx, Register jdx,
9166                                              Register carry, Register product,
9167                                              Register carry2) {
9168   //   jlong carry, x[], y[], z[];
9169   //   int kdx = ystart+1;
9170   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9171   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9172   //     z[kdx+idx+1] = (jlong)product;
9173   //     jlong carry2  = (jlong)(product >>> 64);
9174   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9175   //     z[kdx+idx] = (jlong)product;
9176   //     carry  = (jlong)(product >>> 64);
9177   //   }
9178   //   idx += 2;
9179   //   if (idx > 0) {
9180   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9181   //     z[kdx+idx] = (jlong)product;
9182   //     carry  = (jlong)(product >>> 64);
9183   //   }
9184   //
9185 
9186   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9187 
9188   movl(jdx, idx);
9189   andl(jdx, 0xFFFFFFFC);
9190   shrl(jdx, 2);
9191 
9192   bind(L_third_loop);
9193   subl(jdx, 1);
9194   jcc(Assembler::negative, L_third_loop_exit);
9195   subl(idx, 4);
9196 
9197   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9198   movq(carry2, rdx);
9199 
9200   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9201   movq(carry, rdx);
9202   jmp(L_third_loop);
9203 
9204   bind (L_third_loop_exit);
9205 
9206   andl (idx, 0x3);
9207   jcc(Assembler::zero, L_post_third_loop_done);
9208 
9209   Label L_check_1;
9210   subl(idx, 2);
9211   jcc(Assembler::negative, L_check_1);
9212 
9213   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9214   movq(carry, rdx);
9215 
9216   bind (L_check_1);
9217   addl (idx, 0x2);
9218   andl (idx, 0x1);
9219   subl(idx, 1);
9220   jcc(Assembler::negative, L_post_third_loop_done);
9221 
9222   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9223   movq(product, x_xstart);
9224   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9225   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9226 
9227   add2_with_carry(rdx, product, yz_idx, carry);
9228 
9229   movl(Address(z, idx, Address::times_4,  0), product);
9230   shrq(product, 32);
9231 
9232   shlq(rdx, 32);
9233   orq(product, rdx);
9234   movq(carry, product);
9235 
9236   bind(L_post_third_loop_done);
9237 }
9238 
9239 /**
9240  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9241  *
9242  */
9243 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9244                                                   Register carry, Register carry2,
9245                                                   Register idx, Register jdx,
9246                                                   Register yz_idx1, Register yz_idx2,
9247                                                   Register tmp, Register tmp3, Register tmp4) {
9248   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9249 
9250   //   jlong carry, x[], y[], z[];
9251   //   int kdx = ystart+1;
9252   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9253   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9254   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9255   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9256   //     carry  = (jlong)(tmp4 >>> 64);
9257   //     z[kdx+idx+1] = (jlong)tmp3;
9258   //     z[kdx+idx] = (jlong)tmp4;
9259   //   }
9260   //   idx += 2;
9261   //   if (idx > 0) {
9262   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9263   //     z[kdx+idx] = (jlong)yz_idx1;
9264   //     carry  = (jlong)(yz_idx1 >>> 64);
9265   //   }
9266   //
9267 
9268   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9269 
9270   movl(jdx, idx);
9271   andl(jdx, 0xFFFFFFFC);
9272   shrl(jdx, 2);
9273 
9274   bind(L_third_loop);
9275   subl(jdx, 1);
9276   jcc(Assembler::negative, L_third_loop_exit);
9277   subl(idx, 4);
9278 
9279   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9280   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9281   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9282   rorxq(yz_idx2, yz_idx2, 32);
9283 
9284   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9285   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9286 
9287   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9288   rorxq(yz_idx1, yz_idx1, 32);
9289   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9290   rorxq(yz_idx2, yz_idx2, 32);
9291 
9292   if (VM_Version::supports_adx()) {
9293     adcxq(tmp3, carry);
9294     adoxq(tmp3, yz_idx1);
9295 
9296     adcxq(tmp4, tmp);
9297     adoxq(tmp4, yz_idx2);
9298 
9299     movl(carry, 0); // does not affect flags
9300     adcxq(carry2, carry);
9301     adoxq(carry2, carry);
9302   } else {
9303     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9304     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9305   }
9306   movq(carry, carry2);
9307 
9308   movl(Address(z, idx, Address::times_4, 12), tmp3);
9309   shrq(tmp3, 32);
9310   movl(Address(z, idx, Address::times_4,  8), tmp3);
9311 
9312   movl(Address(z, idx, Address::times_4,  4), tmp4);
9313   shrq(tmp4, 32);
9314   movl(Address(z, idx, Address::times_4,  0), tmp4);
9315 
9316   jmp(L_third_loop);
9317 
9318   bind (L_third_loop_exit);
9319 
9320   andl (idx, 0x3);
9321   jcc(Assembler::zero, L_post_third_loop_done);
9322 
9323   Label L_check_1;
9324   subl(idx, 2);
9325   jcc(Assembler::negative, L_check_1);
9326 
9327   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9328   rorxq(yz_idx1, yz_idx1, 32);
9329   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9330   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9331   rorxq(yz_idx2, yz_idx2, 32);
9332 
9333   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9334 
9335   movl(Address(z, idx, Address::times_4,  4), tmp3);
9336   shrq(tmp3, 32);
9337   movl(Address(z, idx, Address::times_4,  0), tmp3);
9338   movq(carry, tmp4);
9339 
9340   bind (L_check_1);
9341   addl (idx, 0x2);
9342   andl (idx, 0x1);
9343   subl(idx, 1);
9344   jcc(Assembler::negative, L_post_third_loop_done);
9345   movl(tmp4, Address(y, idx, Address::times_4,  0));
9346   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9347   movl(tmp4, Address(z, idx, Address::times_4,  0));
9348 
9349   add2_with_carry(carry2, tmp3, tmp4, carry);
9350 
9351   movl(Address(z, idx, Address::times_4,  0), tmp3);
9352   shrq(tmp3, 32);
9353 
9354   shlq(carry2, 32);
9355   orq(tmp3, carry2);
9356   movq(carry, tmp3);
9357 
9358   bind(L_post_third_loop_done);
9359 }
9360 
9361 /**
9362  * Code for BigInteger::multiplyToLen() instrinsic.
9363  *
9364  * rdi: x
9365  * rax: xlen
9366  * rsi: y
9367  * rcx: ylen
9368  * r8:  z
9369  * r11: zlen
9370  * r12: tmp1
9371  * r13: tmp2
9372  * r14: tmp3
9373  * r15: tmp4
9374  * rbx: tmp5
9375  *
9376  */
9377 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9378                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9379   ShortBranchVerifier sbv(this);
9380   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9381 
9382   push(tmp1);
9383   push(tmp2);
9384   push(tmp3);
9385   push(tmp4);
9386   push(tmp5);
9387 
9388   push(xlen);
9389   push(zlen);
9390 
9391   const Register idx = tmp1;
9392   const Register kdx = tmp2;
9393   const Register xstart = tmp3;
9394 
9395   const Register y_idx = tmp4;
9396   const Register carry = tmp5;
9397   const Register product  = xlen;
9398   const Register x_xstart = zlen;  // reuse register
9399 
9400   // First Loop.
9401   //
9402   //  final static long LONG_MASK = 0xffffffffL;
9403   //  int xstart = xlen - 1;
9404   //  int ystart = ylen - 1;
9405   //  long carry = 0;
9406   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9407   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9408   //    z[kdx] = (int)product;
9409   //    carry = product >>> 32;
9410   //  }
9411   //  z[xstart] = (int)carry;
9412   //
9413 
9414   movl(idx, ylen);      // idx = ylen;
9415   movl(kdx, zlen);      // kdx = xlen+ylen;
9416   xorq(carry, carry);   // carry = 0;
9417 
9418   Label L_done;
9419 
9420   movl(xstart, xlen);
9421   decrementl(xstart);
9422   jcc(Assembler::negative, L_done);
9423 
9424   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9425 
9426   Label L_second_loop;
9427   testl(kdx, kdx);
9428   jcc(Assembler::zero, L_second_loop);
9429 
9430   Label L_carry;
9431   subl(kdx, 1);
9432   jcc(Assembler::zero, L_carry);
9433 
9434   movl(Address(z, kdx, Address::times_4,  0), carry);
9435   shrq(carry, 32);
9436   subl(kdx, 1);
9437 
9438   bind(L_carry);
9439   movl(Address(z, kdx, Address::times_4,  0), carry);
9440 
9441   // Second and third (nested) loops.
9442   //
9443   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9444   //   carry = 0;
9445   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9446   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9447   //                    (z[k] & LONG_MASK) + carry;
9448   //     z[k] = (int)product;
9449   //     carry = product >>> 32;
9450   //   }
9451   //   z[i] = (int)carry;
9452   // }
9453   //
9454   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9455 
9456   const Register jdx = tmp1;
9457 
9458   bind(L_second_loop);
9459   xorl(carry, carry);    // carry = 0;
9460   movl(jdx, ylen);       // j = ystart+1
9461 
9462   subl(xstart, 1);       // i = xstart-1;
9463   jcc(Assembler::negative, L_done);
9464 
9465   push (z);
9466 
9467   Label L_last_x;
9468   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9469   subl(xstart, 1);       // i = xstart-1;
9470   jcc(Assembler::negative, L_last_x);
9471 
9472   if (UseBMI2Instructions) {
9473     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9474     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9475   } else {
9476     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9477     rorq(x_xstart, 32);  // convert big-endian to little-endian
9478   }
9479 
9480   Label L_third_loop_prologue;
9481   bind(L_third_loop_prologue);
9482 
9483   push (x);
9484   push (xstart);
9485   push (ylen);
9486 
9487 
9488   if (UseBMI2Instructions) {
9489     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9490   } else { // !UseBMI2Instructions
9491     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9492   }
9493 
9494   pop(ylen);
9495   pop(xlen);
9496   pop(x);
9497   pop(z);
9498 
9499   movl(tmp3, xlen);
9500   addl(tmp3, 1);
9501   movl(Address(z, tmp3, Address::times_4,  0), carry);
9502   subl(tmp3, 1);
9503   jccb(Assembler::negative, L_done);
9504 
9505   shrq(carry, 32);
9506   movl(Address(z, tmp3, Address::times_4,  0), carry);
9507   jmp(L_second_loop);
9508 
9509   // Next infrequent code is moved outside loops.
9510   bind(L_last_x);
9511   if (UseBMI2Instructions) {
9512     movl(rdx, Address(x,  0));
9513   } else {
9514     movl(x_xstart, Address(x,  0));
9515   }
9516   jmp(L_third_loop_prologue);
9517 
9518   bind(L_done);
9519 
9520   pop(zlen);
9521   pop(xlen);
9522 
9523   pop(tmp5);
9524   pop(tmp4);
9525   pop(tmp3);
9526   pop(tmp2);
9527   pop(tmp1);
9528 }
9529 
9530 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9531   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9532   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9533   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9534   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9535   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9536   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9537   Label SAME_TILL_END, DONE;
9538   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9539 
9540   //scale is in rcx in both Win64 and Unix
9541   ShortBranchVerifier sbv(this);
9542 
9543   shlq(length);
9544   xorq(result, result);
9545 
9546   if ((UseAVX > 2) &&
9547       VM_Version::supports_avx512vlbw()) {
9548     set_vector_masking();  // opening of the stub context for programming mask registers
9549     cmpq(length, 64);
9550     jcc(Assembler::less, VECTOR32_TAIL);
9551     movq(tmp1, length);
9552     andq(tmp1, 0x3F);      // tail count
9553     andq(length, ~(0x3F)); //vector count
9554 
9555     bind(VECTOR64_LOOP);
9556     // AVX512 code to compare 64 byte vectors.
9557     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9558     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9559     kortestql(k7, k7);
9560     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9561     addq(result, 64);
9562     subq(length, 64);
9563     jccb(Assembler::notZero, VECTOR64_LOOP);
9564 
9565     //bind(VECTOR64_TAIL);
9566     testq(tmp1, tmp1);
9567     jcc(Assembler::zero, SAME_TILL_END);
9568 
9569     bind(VECTOR64_TAIL);
9570     // AVX512 code to compare upto 63 byte vectors.
9571     // Save k1
9572     kmovql(k3, k1);
9573     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9574     shlxq(tmp2, tmp2, tmp1);
9575     notq(tmp2);
9576     kmovql(k1, tmp2);
9577 
9578     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9579     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9580 
9581     ktestql(k7, k1);
9582     // Restore k1
9583     kmovql(k1, k3);
9584     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9585 
9586     bind(VECTOR64_NOT_EQUAL);
9587     kmovql(tmp1, k7);
9588     notq(tmp1);
9589     tzcntq(tmp1, tmp1);
9590     addq(result, tmp1);
9591     shrq(result);
9592     jmp(DONE);
9593     bind(VECTOR32_TAIL);
9594     clear_vector_masking();   // closing of the stub context for programming mask registers
9595   }
9596 
9597   cmpq(length, 8);
9598   jcc(Assembler::equal, VECTOR8_LOOP);
9599   jcc(Assembler::less, VECTOR4_TAIL);
9600 
9601   if (UseAVX >= 2) {
9602 
9603     cmpq(length, 16);
9604     jcc(Assembler::equal, VECTOR16_LOOP);
9605     jcc(Assembler::less, VECTOR8_LOOP);
9606 
9607     cmpq(length, 32);
9608     jccb(Assembler::less, VECTOR16_TAIL);
9609 
9610     subq(length, 32);
9611     bind(VECTOR32_LOOP);
9612     vmovdqu(rymm0, Address(obja, result));
9613     vmovdqu(rymm1, Address(objb, result));
9614     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9615     vptest(rymm2, rymm2);
9616     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9617     addq(result, 32);
9618     subq(length, 32);
9619     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9620     addq(length, 32);
9621     jcc(Assembler::equal, SAME_TILL_END);
9622     //falling through if less than 32 bytes left //close the branch here.
9623 
9624     bind(VECTOR16_TAIL);
9625     cmpq(length, 16);
9626     jccb(Assembler::less, VECTOR8_TAIL);
9627     bind(VECTOR16_LOOP);
9628     movdqu(rymm0, Address(obja, result));
9629     movdqu(rymm1, Address(objb, result));
9630     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9631     ptest(rymm2, rymm2);
9632     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9633     addq(result, 16);
9634     subq(length, 16);
9635     jcc(Assembler::equal, SAME_TILL_END);
9636     //falling through if less than 16 bytes left
9637   } else {//regular intrinsics
9638 
9639     cmpq(length, 16);
9640     jccb(Assembler::less, VECTOR8_TAIL);
9641 
9642     subq(length, 16);
9643     bind(VECTOR16_LOOP);
9644     movdqu(rymm0, Address(obja, result));
9645     movdqu(rymm1, Address(objb, result));
9646     pxor(rymm0, rymm1);
9647     ptest(rymm0, rymm0);
9648     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9649     addq(result, 16);
9650     subq(length, 16);
9651     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9652     addq(length, 16);
9653     jcc(Assembler::equal, SAME_TILL_END);
9654     //falling through if less than 16 bytes left
9655   }
9656 
9657   bind(VECTOR8_TAIL);
9658   cmpq(length, 8);
9659   jccb(Assembler::less, VECTOR4_TAIL);
9660   bind(VECTOR8_LOOP);
9661   movq(tmp1, Address(obja, result));
9662   movq(tmp2, Address(objb, result));
9663   xorq(tmp1, tmp2);
9664   testq(tmp1, tmp1);
9665   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9666   addq(result, 8);
9667   subq(length, 8);
9668   jcc(Assembler::equal, SAME_TILL_END);
9669   //falling through if less than 8 bytes left
9670 
9671   bind(VECTOR4_TAIL);
9672   cmpq(length, 4);
9673   jccb(Assembler::less, BYTES_TAIL);
9674   bind(VECTOR4_LOOP);
9675   movl(tmp1, Address(obja, result));
9676   xorl(tmp1, Address(objb, result));
9677   testl(tmp1, tmp1);
9678   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9679   addq(result, 4);
9680   subq(length, 4);
9681   jcc(Assembler::equal, SAME_TILL_END);
9682   //falling through if less than 4 bytes left
9683 
9684   bind(BYTES_TAIL);
9685   bind(BYTES_LOOP);
9686   load_unsigned_byte(tmp1, Address(obja, result));
9687   load_unsigned_byte(tmp2, Address(objb, result));
9688   xorl(tmp1, tmp2);
9689   testl(tmp1, tmp1);
9690   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9691   decq(length);
9692   jccb(Assembler::zero, SAME_TILL_END);
9693   incq(result);
9694   load_unsigned_byte(tmp1, Address(obja, result));
9695   load_unsigned_byte(tmp2, Address(objb, result));
9696   xorl(tmp1, tmp2);
9697   testl(tmp1, tmp1);
9698   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9699   decq(length);
9700   jccb(Assembler::zero, SAME_TILL_END);
9701   incq(result);
9702   load_unsigned_byte(tmp1, Address(obja, result));
9703   load_unsigned_byte(tmp2, Address(objb, result));
9704   xorl(tmp1, tmp2);
9705   testl(tmp1, tmp1);
9706   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9707   jmpb(SAME_TILL_END);
9708 
9709   if (UseAVX >= 2) {
9710     bind(VECTOR32_NOT_EQUAL);
9711     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9712     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9713     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9714     vpmovmskb(tmp1, rymm0);
9715     bsfq(tmp1, tmp1);
9716     addq(result, tmp1);
9717     shrq(result);
9718     jmpb(DONE);
9719   }
9720 
9721   bind(VECTOR16_NOT_EQUAL);
9722   if (UseAVX >= 2) {
9723     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9724     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9725     pxor(rymm0, rymm2);
9726   } else {
9727     pcmpeqb(rymm2, rymm2);
9728     pxor(rymm0, rymm1);
9729     pcmpeqb(rymm0, rymm1);
9730     pxor(rymm0, rymm2);
9731   }
9732   pmovmskb(tmp1, rymm0);
9733   bsfq(tmp1, tmp1);
9734   addq(result, tmp1);
9735   shrq(result);
9736   jmpb(DONE);
9737 
9738   bind(VECTOR8_NOT_EQUAL);
9739   bind(VECTOR4_NOT_EQUAL);
9740   bsfq(tmp1, tmp1);
9741   shrq(tmp1, 3);
9742   addq(result, tmp1);
9743   bind(BYTES_NOT_EQUAL);
9744   shrq(result);
9745   jmpb(DONE);
9746 
9747   bind(SAME_TILL_END);
9748   mov64(result, -1);
9749 
9750   bind(DONE);
9751 }
9752 
9753 //Helper functions for square_to_len()
9754 
9755 /**
9756  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9757  * Preserves x and z and modifies rest of the registers.
9758  */
9759 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9760   // Perform square and right shift by 1
9761   // Handle odd xlen case first, then for even xlen do the following
9762   // jlong carry = 0;
9763   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9764   //     huge_128 product = x[j:j+1] * x[j:j+1];
9765   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9766   //     z[i+2:i+3] = (jlong)(product >>> 1);
9767   //     carry = (jlong)product;
9768   // }
9769 
9770   xorq(tmp5, tmp5);     // carry
9771   xorq(rdxReg, rdxReg);
9772   xorl(tmp1, tmp1);     // index for x
9773   xorl(tmp4, tmp4);     // index for z
9774 
9775   Label L_first_loop, L_first_loop_exit;
9776 
9777   testl(xlen, 1);
9778   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9779 
9780   // Square and right shift by 1 the odd element using 32 bit multiply
9781   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9782   imulq(raxReg, raxReg);
9783   shrq(raxReg, 1);
9784   adcq(tmp5, 0);
9785   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9786   incrementl(tmp1);
9787   addl(tmp4, 2);
9788 
9789   // Square and  right shift by 1 the rest using 64 bit multiply
9790   bind(L_first_loop);
9791   cmpptr(tmp1, xlen);
9792   jccb(Assembler::equal, L_first_loop_exit);
9793 
9794   // Square
9795   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9796   rorq(raxReg, 32);    // convert big-endian to little-endian
9797   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9798 
9799   // Right shift by 1 and save carry
9800   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9801   rcrq(rdxReg, 1);
9802   rcrq(raxReg, 1);
9803   adcq(tmp5, 0);
9804 
9805   // Store result in z
9806   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9807   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9808 
9809   // Update indices for x and z
9810   addl(tmp1, 2);
9811   addl(tmp4, 4);
9812   jmp(L_first_loop);
9813 
9814   bind(L_first_loop_exit);
9815 }
9816 
9817 
9818 /**
9819  * Perform the following multiply add operation using BMI2 instructions
9820  * carry:sum = sum + op1*op2 + carry
9821  * op2 should be in rdx
9822  * op2 is preserved, all other registers are modified
9823  */
9824 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9825   // assert op2 is rdx
9826   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9827   addq(sum, carry);
9828   adcq(tmp2, 0);
9829   addq(sum, op1);
9830   adcq(tmp2, 0);
9831   movq(carry, tmp2);
9832 }
9833 
9834 /**
9835  * Perform the following multiply add operation:
9836  * carry:sum = sum + op1*op2 + carry
9837  * Preserves op1, op2 and modifies rest of registers
9838  */
9839 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9840   // rdx:rax = op1 * op2
9841   movq(raxReg, op2);
9842   mulq(op1);
9843 
9844   //  rdx:rax = sum + carry + rdx:rax
9845   addq(sum, carry);
9846   adcq(rdxReg, 0);
9847   addq(sum, raxReg);
9848   adcq(rdxReg, 0);
9849 
9850   // carry:sum = rdx:sum
9851   movq(carry, rdxReg);
9852 }
9853 
9854 /**
9855  * Add 64 bit long carry into z[] with carry propogation.
9856  * Preserves z and carry register values and modifies rest of registers.
9857  *
9858  */
9859 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9860   Label L_fourth_loop, L_fourth_loop_exit;
9861 
9862   movl(tmp1, 1);
9863   subl(zlen, 2);
9864   addq(Address(z, zlen, Address::times_4, 0), carry);
9865 
9866   bind(L_fourth_loop);
9867   jccb(Assembler::carryClear, L_fourth_loop_exit);
9868   subl(zlen, 2);
9869   jccb(Assembler::negative, L_fourth_loop_exit);
9870   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9871   jmp(L_fourth_loop);
9872   bind(L_fourth_loop_exit);
9873 }
9874 
9875 /**
9876  * Shift z[] left by 1 bit.
9877  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9878  *
9879  */
9880 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9881 
9882   Label L_fifth_loop, L_fifth_loop_exit;
9883 
9884   // Fifth loop
9885   // Perform primitiveLeftShift(z, zlen, 1)
9886 
9887   const Register prev_carry = tmp1;
9888   const Register new_carry = tmp4;
9889   const Register value = tmp2;
9890   const Register zidx = tmp3;
9891 
9892   // int zidx, carry;
9893   // long value;
9894   // carry = 0;
9895   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9896   //    (carry:value)  = (z[i] << 1) | carry ;
9897   //    z[i] = value;
9898   // }
9899 
9900   movl(zidx, zlen);
9901   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9902 
9903   bind(L_fifth_loop);
9904   decl(zidx);  // Use decl to preserve carry flag
9905   decl(zidx);
9906   jccb(Assembler::negative, L_fifth_loop_exit);
9907 
9908   if (UseBMI2Instructions) {
9909      movq(value, Address(z, zidx, Address::times_4, 0));
9910      rclq(value, 1);
9911      rorxq(value, value, 32);
9912      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9913   }
9914   else {
9915     // clear new_carry
9916     xorl(new_carry, new_carry);
9917 
9918     // Shift z[i] by 1, or in previous carry and save new carry
9919     movq(value, Address(z, zidx, Address::times_4, 0));
9920     shlq(value, 1);
9921     adcl(new_carry, 0);
9922 
9923     orq(value, prev_carry);
9924     rorq(value, 0x20);
9925     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9926 
9927     // Set previous carry = new carry
9928     movl(prev_carry, new_carry);
9929   }
9930   jmp(L_fifth_loop);
9931 
9932   bind(L_fifth_loop_exit);
9933 }
9934 
9935 
9936 /**
9937  * Code for BigInteger::squareToLen() intrinsic
9938  *
9939  * rdi: x
9940  * rsi: len
9941  * r8:  z
9942  * rcx: zlen
9943  * r12: tmp1
9944  * r13: tmp2
9945  * r14: tmp3
9946  * r15: tmp4
9947  * rbx: tmp5
9948  *
9949  */
9950 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) {
9951 
9952   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;
9953   push(tmp1);
9954   push(tmp2);
9955   push(tmp3);
9956   push(tmp4);
9957   push(tmp5);
9958 
9959   // First loop
9960   // Store the squares, right shifted one bit (i.e., divided by 2).
9961   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9962 
9963   // Add in off-diagonal sums.
9964   //
9965   // Second, third (nested) and fourth loops.
9966   // zlen +=2;
9967   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9968   //    carry = 0;
9969   //    long op2 = x[xidx:xidx+1];
9970   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9971   //       k -= 2;
9972   //       long op1 = x[j:j+1];
9973   //       long sum = z[k:k+1];
9974   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9975   //       z[k:k+1] = sum;
9976   //    }
9977   //    add_one_64(z, k, carry, tmp_regs);
9978   // }
9979 
9980   const Register carry = tmp5;
9981   const Register sum = tmp3;
9982   const Register op1 = tmp4;
9983   Register op2 = tmp2;
9984 
9985   push(zlen);
9986   push(len);
9987   addl(zlen,2);
9988   bind(L_second_loop);
9989   xorq(carry, carry);
9990   subl(zlen, 4);
9991   subl(len, 2);
9992   push(zlen);
9993   push(len);
9994   cmpl(len, 0);
9995   jccb(Assembler::lessEqual, L_second_loop_exit);
9996 
9997   // Multiply an array by one 64 bit long.
9998   if (UseBMI2Instructions) {
9999     op2 = rdxReg;
10000     movq(op2, Address(x, len, Address::times_4,  0));
10001     rorxq(op2, op2, 32);
10002   }
10003   else {
10004     movq(op2, Address(x, len, Address::times_4,  0));
10005     rorq(op2, 32);
10006   }
10007 
10008   bind(L_third_loop);
10009   decrementl(len);
10010   jccb(Assembler::negative, L_third_loop_exit);
10011   decrementl(len);
10012   jccb(Assembler::negative, L_last_x);
10013 
10014   movq(op1, Address(x, len, Address::times_4,  0));
10015   rorq(op1, 32);
10016 
10017   bind(L_multiply);
10018   subl(zlen, 2);
10019   movq(sum, Address(z, zlen, Address::times_4,  0));
10020 
10021   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10022   if (UseBMI2Instructions) {
10023     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10024   }
10025   else {
10026     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10027   }
10028 
10029   movq(Address(z, zlen, Address::times_4, 0), sum);
10030 
10031   jmp(L_third_loop);
10032   bind(L_third_loop_exit);
10033 
10034   // Fourth loop
10035   // Add 64 bit long carry into z with carry propogation.
10036   // Uses offsetted zlen.
10037   add_one_64(z, zlen, carry, tmp1);
10038 
10039   pop(len);
10040   pop(zlen);
10041   jmp(L_second_loop);
10042 
10043   // Next infrequent code is moved outside loops.
10044   bind(L_last_x);
10045   movl(op1, Address(x, 0));
10046   jmp(L_multiply);
10047 
10048   bind(L_second_loop_exit);
10049   pop(len);
10050   pop(zlen);
10051   pop(len);
10052   pop(zlen);
10053 
10054   // Fifth loop
10055   // Shift z left 1 bit.
10056   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10057 
10058   // z[zlen-1] |= x[len-1] & 1;
10059   movl(tmp3, Address(x, len, Address::times_4, -4));
10060   andl(tmp3, 1);
10061   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10062 
10063   pop(tmp5);
10064   pop(tmp4);
10065   pop(tmp3);
10066   pop(tmp2);
10067   pop(tmp1);
10068 }
10069 
10070 /**
10071  * Helper function for mul_add()
10072  * Multiply the in[] by int k and add to out[] starting at offset offs using
10073  * 128 bit by 32 bit multiply and return the carry in tmp5.
10074  * Only quad int aligned length of in[] is operated on in this function.
10075  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10076  * This function preserves out, in and k registers.
10077  * len and offset point to the appropriate index in "in" & "out" correspondingly
10078  * tmp5 has the carry.
10079  * other registers are temporary and are modified.
10080  *
10081  */
10082 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10083   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10084   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10085 
10086   Label L_first_loop, L_first_loop_exit;
10087 
10088   movl(tmp1, len);
10089   shrl(tmp1, 2);
10090 
10091   bind(L_first_loop);
10092   subl(tmp1, 1);
10093   jccb(Assembler::negative, L_first_loop_exit);
10094 
10095   subl(len, 4);
10096   subl(offset, 4);
10097 
10098   Register op2 = tmp2;
10099   const Register sum = tmp3;
10100   const Register op1 = tmp4;
10101   const Register carry = tmp5;
10102 
10103   if (UseBMI2Instructions) {
10104     op2 = rdxReg;
10105   }
10106 
10107   movq(op1, Address(in, len, Address::times_4,  8));
10108   rorq(op1, 32);
10109   movq(sum, Address(out, offset, Address::times_4,  8));
10110   rorq(sum, 32);
10111   if (UseBMI2Instructions) {
10112     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10113   }
10114   else {
10115     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10116   }
10117   // Store back in big endian from little endian
10118   rorq(sum, 0x20);
10119   movq(Address(out, offset, Address::times_4,  8), sum);
10120 
10121   movq(op1, Address(in, len, Address::times_4,  0));
10122   rorq(op1, 32);
10123   movq(sum, Address(out, offset, Address::times_4,  0));
10124   rorq(sum, 32);
10125   if (UseBMI2Instructions) {
10126     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10127   }
10128   else {
10129     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10130   }
10131   // Store back in big endian from little endian
10132   rorq(sum, 0x20);
10133   movq(Address(out, offset, Address::times_4,  0), sum);
10134 
10135   jmp(L_first_loop);
10136   bind(L_first_loop_exit);
10137 }
10138 
10139 /**
10140  * Code for BigInteger::mulAdd() intrinsic
10141  *
10142  * rdi: out
10143  * rsi: in
10144  * r11: offs (out.length - offset)
10145  * rcx: len
10146  * r8:  k
10147  * r12: tmp1
10148  * r13: tmp2
10149  * r14: tmp3
10150  * r15: tmp4
10151  * rbx: tmp5
10152  * Multiply the in[] by word k and add to out[], return the carry in rax
10153  */
10154 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10155    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10156    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10157 
10158   Label L_carry, L_last_in, L_done;
10159 
10160 // carry = 0;
10161 // for (int j=len-1; j >= 0; j--) {
10162 //    long product = (in[j] & LONG_MASK) * kLong +
10163 //                   (out[offs] & LONG_MASK) + carry;
10164 //    out[offs--] = (int)product;
10165 //    carry = product >>> 32;
10166 // }
10167 //
10168   push(tmp1);
10169   push(tmp2);
10170   push(tmp3);
10171   push(tmp4);
10172   push(tmp5);
10173 
10174   Register op2 = tmp2;
10175   const Register sum = tmp3;
10176   const Register op1 = tmp4;
10177   const Register carry =  tmp5;
10178 
10179   if (UseBMI2Instructions) {
10180     op2 = rdxReg;
10181     movl(op2, k);
10182   }
10183   else {
10184     movl(op2, k);
10185   }
10186 
10187   xorq(carry, carry);
10188 
10189   //First loop
10190 
10191   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10192   //The carry is in tmp5
10193   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10194 
10195   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10196   decrementl(len);
10197   jccb(Assembler::negative, L_carry);
10198   decrementl(len);
10199   jccb(Assembler::negative, L_last_in);
10200 
10201   movq(op1, Address(in, len, Address::times_4,  0));
10202   rorq(op1, 32);
10203 
10204   subl(offs, 2);
10205   movq(sum, Address(out, offs, Address::times_4,  0));
10206   rorq(sum, 32);
10207 
10208   if (UseBMI2Instructions) {
10209     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10210   }
10211   else {
10212     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10213   }
10214 
10215   // Store back in big endian from little endian
10216   rorq(sum, 0x20);
10217   movq(Address(out, offs, Address::times_4,  0), sum);
10218 
10219   testl(len, len);
10220   jccb(Assembler::zero, L_carry);
10221 
10222   //Multiply the last in[] entry, if any
10223   bind(L_last_in);
10224   movl(op1, Address(in, 0));
10225   movl(sum, Address(out, offs, Address::times_4,  -4));
10226 
10227   movl(raxReg, k);
10228   mull(op1); //tmp4 * eax -> edx:eax
10229   addl(sum, carry);
10230   adcl(rdxReg, 0);
10231   addl(sum, raxReg);
10232   adcl(rdxReg, 0);
10233   movl(carry, rdxReg);
10234 
10235   movl(Address(out, offs, Address::times_4,  -4), sum);
10236 
10237   bind(L_carry);
10238   //return tmp5/carry as carry in rax
10239   movl(rax, carry);
10240 
10241   bind(L_done);
10242   pop(tmp5);
10243   pop(tmp4);
10244   pop(tmp3);
10245   pop(tmp2);
10246   pop(tmp1);
10247 }
10248 #endif
10249 
10250 /**
10251  * Emits code to update CRC-32 with a byte value according to constants in table
10252  *
10253  * @param [in,out]crc   Register containing the crc.
10254  * @param [in]val       Register containing the byte to fold into the CRC.
10255  * @param [in]table     Register containing the table of crc constants.
10256  *
10257  * uint32_t crc;
10258  * val = crc_table[(val ^ crc) & 0xFF];
10259  * crc = val ^ (crc >> 8);
10260  *
10261  */
10262 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10263   xorl(val, crc);
10264   andl(val, 0xFF);
10265   shrl(crc, 8); // unsigned shift
10266   xorl(crc, Address(table, val, Address::times_4, 0));
10267 }
10268 
10269 /**
10270  * Fold 128-bit data chunk
10271  */
10272 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10273   if (UseAVX > 0) {
10274     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10275     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10276     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10277     pxor(xcrc, xtmp);
10278   } else {
10279     movdqa(xtmp, xcrc);
10280     pclmulhdq(xtmp, xK);   // [123:64]
10281     pclmulldq(xcrc, xK);   // [63:0]
10282     pxor(xcrc, xtmp);
10283     movdqu(xtmp, Address(buf, offset));
10284     pxor(xcrc, xtmp);
10285   }
10286 }
10287 
10288 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10289   if (UseAVX > 0) {
10290     vpclmulhdq(xtmp, xK, xcrc);
10291     vpclmulldq(xcrc, xK, xcrc);
10292     pxor(xcrc, xbuf);
10293     pxor(xcrc, xtmp);
10294   } else {
10295     movdqa(xtmp, xcrc);
10296     pclmulhdq(xtmp, xK);
10297     pclmulldq(xcrc, xK);
10298     pxor(xcrc, xbuf);
10299     pxor(xcrc, xtmp);
10300   }
10301 }
10302 
10303 /**
10304  * 8-bit folds to compute 32-bit CRC
10305  *
10306  * uint64_t xcrc;
10307  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10308  */
10309 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10310   movdl(tmp, xcrc);
10311   andl(tmp, 0xFF);
10312   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10313   psrldq(xcrc, 1); // unsigned shift one byte
10314   pxor(xcrc, xtmp);
10315 }
10316 
10317 /**
10318  * uint32_t crc;
10319  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10320  */
10321 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10322   movl(tmp, crc);
10323   andl(tmp, 0xFF);
10324   shrl(crc, 8);
10325   xorl(crc, Address(table, tmp, Address::times_4, 0));
10326 }
10327 
10328 /**
10329  * @param crc   register containing existing CRC (32-bit)
10330  * @param buf   register pointing to input byte buffer (byte*)
10331  * @param len   register containing number of bytes
10332  * @param table register that will contain address of CRC table
10333  * @param tmp   scratch register
10334  */
10335 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10336   assert_different_registers(crc, buf, len, table, tmp, rax);
10337 
10338   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10339   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10340 
10341   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10342   // context for the registers used, where all instructions below are using 128-bit mode
10343   // On EVEX without VL and BW, these instructions will all be AVX.
10344   if (VM_Version::supports_avx512vlbw()) {
10345     movl(tmp, 0xffff);
10346     kmovwl(k1, tmp);
10347   }
10348 
10349   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10350   notl(crc); // ~crc
10351   cmpl(len, 16);
10352   jcc(Assembler::less, L_tail);
10353 
10354   // Align buffer to 16 bytes
10355   movl(tmp, buf);
10356   andl(tmp, 0xF);
10357   jccb(Assembler::zero, L_aligned);
10358   subl(tmp,  16);
10359   addl(len, tmp);
10360 
10361   align(4);
10362   BIND(L_align_loop);
10363   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10364   update_byte_crc32(crc, rax, table);
10365   increment(buf);
10366   incrementl(tmp);
10367   jccb(Assembler::less, L_align_loop);
10368 
10369   BIND(L_aligned);
10370   movl(tmp, len); // save
10371   shrl(len, 4);
10372   jcc(Assembler::zero, L_tail_restore);
10373 
10374   // Fold crc into first bytes of vector
10375   movdqa(xmm1, Address(buf, 0));
10376   movdl(rax, xmm1);
10377   xorl(crc, rax);
10378   if (VM_Version::supports_sse4_1()) {
10379     pinsrd(xmm1, crc, 0);
10380   } else {
10381     pinsrw(xmm1, crc, 0);
10382     shrl(crc, 16);
10383     pinsrw(xmm1, crc, 1);
10384   }
10385   addptr(buf, 16);
10386   subl(len, 4); // len > 0
10387   jcc(Assembler::less, L_fold_tail);
10388 
10389   movdqa(xmm2, Address(buf,  0));
10390   movdqa(xmm3, Address(buf, 16));
10391   movdqa(xmm4, Address(buf, 32));
10392   addptr(buf, 48);
10393   subl(len, 3);
10394   jcc(Assembler::lessEqual, L_fold_512b);
10395 
10396   // Fold total 512 bits of polynomial on each iteration,
10397   // 128 bits per each of 4 parallel streams.
10398   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10399 
10400   align(32);
10401   BIND(L_fold_512b_loop);
10402   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10403   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10404   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10405   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10406   addptr(buf, 64);
10407   subl(len, 4);
10408   jcc(Assembler::greater, L_fold_512b_loop);
10409 
10410   // Fold 512 bits to 128 bits.
10411   BIND(L_fold_512b);
10412   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10413   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10414   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10415   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10416 
10417   // Fold the rest of 128 bits data chunks
10418   BIND(L_fold_tail);
10419   addl(len, 3);
10420   jccb(Assembler::lessEqual, L_fold_128b);
10421   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10422 
10423   BIND(L_fold_tail_loop);
10424   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10425   addptr(buf, 16);
10426   decrementl(len);
10427   jccb(Assembler::greater, L_fold_tail_loop);
10428 
10429   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10430   BIND(L_fold_128b);
10431   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10432   if (UseAVX > 0) {
10433     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10434     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10435     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10436   } else {
10437     movdqa(xmm2, xmm0);
10438     pclmulqdq(xmm2, xmm1, 0x1);
10439     movdqa(xmm3, xmm0);
10440     pand(xmm3, xmm2);
10441     pclmulqdq(xmm0, xmm3, 0x1);
10442   }
10443   psrldq(xmm1, 8);
10444   psrldq(xmm2, 4);
10445   pxor(xmm0, xmm1);
10446   pxor(xmm0, xmm2);
10447 
10448   // 8 8-bit folds to compute 32-bit CRC.
10449   for (int j = 0; j < 4; j++) {
10450     fold_8bit_crc32(xmm0, table, xmm1, rax);
10451   }
10452   movdl(crc, xmm0); // mov 32 bits to general register
10453   for (int j = 0; j < 4; j++) {
10454     fold_8bit_crc32(crc, table, rax);
10455   }
10456 
10457   BIND(L_tail_restore);
10458   movl(len, tmp); // restore
10459   BIND(L_tail);
10460   andl(len, 0xf);
10461   jccb(Assembler::zero, L_exit);
10462 
10463   // Fold the rest of bytes
10464   align(4);
10465   BIND(L_tail_loop);
10466   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10467   update_byte_crc32(crc, rax, table);
10468   increment(buf);
10469   decrementl(len);
10470   jccb(Assembler::greater, L_tail_loop);
10471 
10472   BIND(L_exit);
10473   notl(crc); // ~c
10474 }
10475 
10476 #ifdef _LP64
10477 // S. Gueron / Information Processing Letters 112 (2012) 184
10478 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10479 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10480 // Output: the 64-bit carry-less product of B * CONST
10481 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10482                                      Register tmp1, Register tmp2, Register tmp3) {
10483   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10484   if (n > 0) {
10485     addq(tmp3, n * 256 * 8);
10486   }
10487   //    Q1 = TABLEExt[n][B & 0xFF];
10488   movl(tmp1, in);
10489   andl(tmp1, 0x000000FF);
10490   shll(tmp1, 3);
10491   addq(tmp1, tmp3);
10492   movq(tmp1, Address(tmp1, 0));
10493 
10494   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10495   movl(tmp2, in);
10496   shrl(tmp2, 8);
10497   andl(tmp2, 0x000000FF);
10498   shll(tmp2, 3);
10499   addq(tmp2, tmp3);
10500   movq(tmp2, Address(tmp2, 0));
10501 
10502   shlq(tmp2, 8);
10503   xorq(tmp1, tmp2);
10504 
10505   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10506   movl(tmp2, in);
10507   shrl(tmp2, 16);
10508   andl(tmp2, 0x000000FF);
10509   shll(tmp2, 3);
10510   addq(tmp2, tmp3);
10511   movq(tmp2, Address(tmp2, 0));
10512 
10513   shlq(tmp2, 16);
10514   xorq(tmp1, tmp2);
10515 
10516   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10517   shrl(in, 24);
10518   andl(in, 0x000000FF);
10519   shll(in, 3);
10520   addq(in, tmp3);
10521   movq(in, Address(in, 0));
10522 
10523   shlq(in, 24);
10524   xorq(in, tmp1);
10525   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10526 }
10527 
10528 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10529                                       Register in_out,
10530                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10531                                       XMMRegister w_xtmp2,
10532                                       Register tmp1,
10533                                       Register n_tmp2, Register n_tmp3) {
10534   if (is_pclmulqdq_supported) {
10535     movdl(w_xtmp1, in_out); // modified blindly
10536 
10537     movl(tmp1, const_or_pre_comp_const_index);
10538     movdl(w_xtmp2, tmp1);
10539     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10540 
10541     movdq(in_out, w_xtmp1);
10542   } else {
10543     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10544   }
10545 }
10546 
10547 // Recombination Alternative 2: No bit-reflections
10548 // T1 = (CRC_A * U1) << 1
10549 // T2 = (CRC_B * U2) << 1
10550 // C1 = T1 >> 32
10551 // C2 = T2 >> 32
10552 // T1 = T1 & 0xFFFFFFFF
10553 // T2 = T2 & 0xFFFFFFFF
10554 // T1 = CRC32(0, T1)
10555 // T2 = CRC32(0, T2)
10556 // C1 = C1 ^ T1
10557 // C2 = C2 ^ T2
10558 // CRC = C1 ^ C2 ^ CRC_C
10559 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,
10560                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10561                                      Register tmp1, Register tmp2,
10562                                      Register n_tmp3) {
10563   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10564   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10565   shlq(in_out, 1);
10566   movl(tmp1, in_out);
10567   shrq(in_out, 32);
10568   xorl(tmp2, tmp2);
10569   crc32(tmp2, tmp1, 4);
10570   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10571   shlq(in1, 1);
10572   movl(tmp1, in1);
10573   shrq(in1, 32);
10574   xorl(tmp2, tmp2);
10575   crc32(tmp2, tmp1, 4);
10576   xorl(in1, tmp2);
10577   xorl(in_out, in1);
10578   xorl(in_out, in2);
10579 }
10580 
10581 // Set N to predefined value
10582 // Subtract from a lenght of a buffer
10583 // execute in a loop:
10584 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10585 // for i = 1 to N do
10586 //  CRC_A = CRC32(CRC_A, A[i])
10587 //  CRC_B = CRC32(CRC_B, B[i])
10588 //  CRC_C = CRC32(CRC_C, C[i])
10589 // end for
10590 // Recombine
10591 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,
10592                                        Register in_out1, Register in_out2, Register in_out3,
10593                                        Register tmp1, Register tmp2, Register tmp3,
10594                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10595                                        Register tmp4, Register tmp5,
10596                                        Register n_tmp6) {
10597   Label L_processPartitions;
10598   Label L_processPartition;
10599   Label L_exit;
10600 
10601   bind(L_processPartitions);
10602   cmpl(in_out1, 3 * size);
10603   jcc(Assembler::less, L_exit);
10604     xorl(tmp1, tmp1);
10605     xorl(tmp2, tmp2);
10606     movq(tmp3, in_out2);
10607     addq(tmp3, size);
10608 
10609     bind(L_processPartition);
10610       crc32(in_out3, Address(in_out2, 0), 8);
10611       crc32(tmp1, Address(in_out2, size), 8);
10612       crc32(tmp2, Address(in_out2, size * 2), 8);
10613       addq(in_out2, 8);
10614       cmpq(in_out2, tmp3);
10615       jcc(Assembler::less, L_processPartition);
10616     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10617             w_xtmp1, w_xtmp2, w_xtmp3,
10618             tmp4, tmp5,
10619             n_tmp6);
10620     addq(in_out2, 2 * size);
10621     subl(in_out1, 3 * size);
10622     jmp(L_processPartitions);
10623 
10624   bind(L_exit);
10625 }
10626 #else
10627 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10628                                      Register tmp1, Register tmp2, Register tmp3,
10629                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10630   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10631   if (n > 0) {
10632     addl(tmp3, n * 256 * 8);
10633   }
10634   //    Q1 = TABLEExt[n][B & 0xFF];
10635   movl(tmp1, in_out);
10636   andl(tmp1, 0x000000FF);
10637   shll(tmp1, 3);
10638   addl(tmp1, tmp3);
10639   movq(xtmp1, Address(tmp1, 0));
10640 
10641   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10642   movl(tmp2, in_out);
10643   shrl(tmp2, 8);
10644   andl(tmp2, 0x000000FF);
10645   shll(tmp2, 3);
10646   addl(tmp2, tmp3);
10647   movq(xtmp2, Address(tmp2, 0));
10648 
10649   psllq(xtmp2, 8);
10650   pxor(xtmp1, xtmp2);
10651 
10652   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10653   movl(tmp2, in_out);
10654   shrl(tmp2, 16);
10655   andl(tmp2, 0x000000FF);
10656   shll(tmp2, 3);
10657   addl(tmp2, tmp3);
10658   movq(xtmp2, Address(tmp2, 0));
10659 
10660   psllq(xtmp2, 16);
10661   pxor(xtmp1, xtmp2);
10662 
10663   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10664   shrl(in_out, 24);
10665   andl(in_out, 0x000000FF);
10666   shll(in_out, 3);
10667   addl(in_out, tmp3);
10668   movq(xtmp2, Address(in_out, 0));
10669 
10670   psllq(xtmp2, 24);
10671   pxor(xtmp1, xtmp2); // Result in CXMM
10672   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10673 }
10674 
10675 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10676                                       Register in_out,
10677                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10678                                       XMMRegister w_xtmp2,
10679                                       Register tmp1,
10680                                       Register n_tmp2, Register n_tmp3) {
10681   if (is_pclmulqdq_supported) {
10682     movdl(w_xtmp1, in_out);
10683 
10684     movl(tmp1, const_or_pre_comp_const_index);
10685     movdl(w_xtmp2, tmp1);
10686     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10687     // Keep result in XMM since GPR is 32 bit in length
10688   } else {
10689     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10690   }
10691 }
10692 
10693 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,
10694                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10695                                      Register tmp1, Register tmp2,
10696                                      Register n_tmp3) {
10697   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10698   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10699 
10700   psllq(w_xtmp1, 1);
10701   movdl(tmp1, w_xtmp1);
10702   psrlq(w_xtmp1, 32);
10703   movdl(in_out, w_xtmp1);
10704 
10705   xorl(tmp2, tmp2);
10706   crc32(tmp2, tmp1, 4);
10707   xorl(in_out, tmp2);
10708 
10709   psllq(w_xtmp2, 1);
10710   movdl(tmp1, w_xtmp2);
10711   psrlq(w_xtmp2, 32);
10712   movdl(in1, w_xtmp2);
10713 
10714   xorl(tmp2, tmp2);
10715   crc32(tmp2, tmp1, 4);
10716   xorl(in1, tmp2);
10717   xorl(in_out, in1);
10718   xorl(in_out, in2);
10719 }
10720 
10721 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,
10722                                        Register in_out1, Register in_out2, Register in_out3,
10723                                        Register tmp1, Register tmp2, Register tmp3,
10724                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10725                                        Register tmp4, Register tmp5,
10726                                        Register n_tmp6) {
10727   Label L_processPartitions;
10728   Label L_processPartition;
10729   Label L_exit;
10730 
10731   bind(L_processPartitions);
10732   cmpl(in_out1, 3 * size);
10733   jcc(Assembler::less, L_exit);
10734     xorl(tmp1, tmp1);
10735     xorl(tmp2, tmp2);
10736     movl(tmp3, in_out2);
10737     addl(tmp3, size);
10738 
10739     bind(L_processPartition);
10740       crc32(in_out3, Address(in_out2, 0), 4);
10741       crc32(tmp1, Address(in_out2, size), 4);
10742       crc32(tmp2, Address(in_out2, size*2), 4);
10743       crc32(in_out3, Address(in_out2, 0+4), 4);
10744       crc32(tmp1, Address(in_out2, size+4), 4);
10745       crc32(tmp2, Address(in_out2, size*2+4), 4);
10746       addl(in_out2, 8);
10747       cmpl(in_out2, tmp3);
10748       jcc(Assembler::less, L_processPartition);
10749 
10750         push(tmp3);
10751         push(in_out1);
10752         push(in_out2);
10753         tmp4 = tmp3;
10754         tmp5 = in_out1;
10755         n_tmp6 = in_out2;
10756 
10757       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10758             w_xtmp1, w_xtmp2, w_xtmp3,
10759             tmp4, tmp5,
10760             n_tmp6);
10761 
10762         pop(in_out2);
10763         pop(in_out1);
10764         pop(tmp3);
10765 
10766     addl(in_out2, 2 * size);
10767     subl(in_out1, 3 * size);
10768     jmp(L_processPartitions);
10769 
10770   bind(L_exit);
10771 }
10772 #endif //LP64
10773 
10774 #ifdef _LP64
10775 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10776 // Input: A buffer I of L bytes.
10777 // Output: the CRC32C value of the buffer.
10778 // Notations:
10779 // Write L = 24N + r, with N = floor (L/24).
10780 // r = L mod 24 (0 <= r < 24).
10781 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10782 // N quadwords, and R consists of r bytes.
10783 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10784 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10785 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10786 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10787 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10788                                           Register tmp1, Register tmp2, Register tmp3,
10789                                           Register tmp4, Register tmp5, Register tmp6,
10790                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10791                                           bool is_pclmulqdq_supported) {
10792   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10793   Label L_wordByWord;
10794   Label L_byteByByteProlog;
10795   Label L_byteByByte;
10796   Label L_exit;
10797 
10798   if (is_pclmulqdq_supported ) {
10799     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10800     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10801 
10802     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10803     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10804 
10805     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10806     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10807     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10808   } else {
10809     const_or_pre_comp_const_index[0] = 1;
10810     const_or_pre_comp_const_index[1] = 0;
10811 
10812     const_or_pre_comp_const_index[2] = 3;
10813     const_or_pre_comp_const_index[3] = 2;
10814 
10815     const_or_pre_comp_const_index[4] = 5;
10816     const_or_pre_comp_const_index[5] = 4;
10817    }
10818   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10819                     in2, in1, in_out,
10820                     tmp1, tmp2, tmp3,
10821                     w_xtmp1, w_xtmp2, w_xtmp3,
10822                     tmp4, tmp5,
10823                     tmp6);
10824   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10825                     in2, in1, in_out,
10826                     tmp1, tmp2, tmp3,
10827                     w_xtmp1, w_xtmp2, w_xtmp3,
10828                     tmp4, tmp5,
10829                     tmp6);
10830   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10831                     in2, in1, in_out,
10832                     tmp1, tmp2, tmp3,
10833                     w_xtmp1, w_xtmp2, w_xtmp3,
10834                     tmp4, tmp5,
10835                     tmp6);
10836   movl(tmp1, in2);
10837   andl(tmp1, 0x00000007);
10838   negl(tmp1);
10839   addl(tmp1, in2);
10840   addq(tmp1, in1);
10841 
10842   BIND(L_wordByWord);
10843   cmpq(in1, tmp1);
10844   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10845     crc32(in_out, Address(in1, 0), 4);
10846     addq(in1, 4);
10847     jmp(L_wordByWord);
10848 
10849   BIND(L_byteByByteProlog);
10850   andl(in2, 0x00000007);
10851   movl(tmp2, 1);
10852 
10853   BIND(L_byteByByte);
10854   cmpl(tmp2, in2);
10855   jccb(Assembler::greater, L_exit);
10856     crc32(in_out, Address(in1, 0), 1);
10857     incq(in1);
10858     incl(tmp2);
10859     jmp(L_byteByByte);
10860 
10861   BIND(L_exit);
10862 }
10863 #else
10864 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10865                                           Register tmp1, Register  tmp2, Register tmp3,
10866                                           Register tmp4, Register  tmp5, Register tmp6,
10867                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10868                                           bool is_pclmulqdq_supported) {
10869   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10870   Label L_wordByWord;
10871   Label L_byteByByteProlog;
10872   Label L_byteByByte;
10873   Label L_exit;
10874 
10875   if (is_pclmulqdq_supported) {
10876     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10877     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10878 
10879     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10880     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10881 
10882     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10883     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10884   } else {
10885     const_or_pre_comp_const_index[0] = 1;
10886     const_or_pre_comp_const_index[1] = 0;
10887 
10888     const_or_pre_comp_const_index[2] = 3;
10889     const_or_pre_comp_const_index[3] = 2;
10890 
10891     const_or_pre_comp_const_index[4] = 5;
10892     const_or_pre_comp_const_index[5] = 4;
10893   }
10894   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10895                     in2, in1, in_out,
10896                     tmp1, tmp2, tmp3,
10897                     w_xtmp1, w_xtmp2, w_xtmp3,
10898                     tmp4, tmp5,
10899                     tmp6);
10900   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10901                     in2, in1, in_out,
10902                     tmp1, tmp2, tmp3,
10903                     w_xtmp1, w_xtmp2, w_xtmp3,
10904                     tmp4, tmp5,
10905                     tmp6);
10906   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10907                     in2, in1, in_out,
10908                     tmp1, tmp2, tmp3,
10909                     w_xtmp1, w_xtmp2, w_xtmp3,
10910                     tmp4, tmp5,
10911                     tmp6);
10912   movl(tmp1, in2);
10913   andl(tmp1, 0x00000007);
10914   negl(tmp1);
10915   addl(tmp1, in2);
10916   addl(tmp1, in1);
10917 
10918   BIND(L_wordByWord);
10919   cmpl(in1, tmp1);
10920   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10921     crc32(in_out, Address(in1,0), 4);
10922     addl(in1, 4);
10923     jmp(L_wordByWord);
10924 
10925   BIND(L_byteByByteProlog);
10926   andl(in2, 0x00000007);
10927   movl(tmp2, 1);
10928 
10929   BIND(L_byteByByte);
10930   cmpl(tmp2, in2);
10931   jccb(Assembler::greater, L_exit);
10932     movb(tmp1, Address(in1, 0));
10933     crc32(in_out, tmp1, 1);
10934     incl(in1);
10935     incl(tmp2);
10936     jmp(L_byteByByte);
10937 
10938   BIND(L_exit);
10939 }
10940 #endif // LP64
10941 #undef BIND
10942 #undef BLOCK_COMMENT
10943 
10944 // Compress char[] array to byte[].
10945 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10946 //   @HotSpotIntrinsicCandidate
10947 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10948 //     for (int i = 0; i < len; i++) {
10949 //       int c = src[srcOff++];
10950 //       if (c >>> 8 != 0) {
10951 //         return 0;
10952 //       }
10953 //       dst[dstOff++] = (byte)c;
10954 //     }
10955 //     return len;
10956 //   }
10957 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10958   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10959   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10960   Register tmp5, Register result) {
10961   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10962 
10963   // rsi: src
10964   // rdi: dst
10965   // rdx: len
10966   // rcx: tmp5
10967   // rax: result
10968 
10969   // rsi holds start addr of source char[] to be compressed
10970   // rdi holds start addr of destination byte[]
10971   // rdx holds length
10972 
10973   assert(len != result, "");
10974 
10975   // save length for return
10976   push(len);
10977 
10978   if ((UseAVX > 2) && // AVX512
10979     VM_Version::supports_avx512vlbw() &&
10980     VM_Version::supports_bmi2()) {
10981 
10982     set_vector_masking();  // opening of the stub context for programming mask registers
10983 
10984     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10985 
10986     // alignement
10987     Label post_alignement;
10988 
10989     // if length of the string is less than 16, handle it in an old fashioned
10990     // way
10991     testl(len, -32);
10992     jcc(Assembler::zero, below_threshold);
10993 
10994     // First check whether a character is compressable ( <= 0xFF).
10995     // Create mask to test for Unicode chars inside zmm vector
10996     movl(result, 0x00FF);
10997     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10998 
10999     // Save k1
11000     kmovql(k3, k1);
11001 
11002     testl(len, -64);
11003     jcc(Assembler::zero, post_alignement);
11004 
11005     movl(tmp5, dst);
11006     andl(tmp5, (32 - 1));
11007     negl(tmp5);
11008     andl(tmp5, (32 - 1));
11009 
11010     // bail out when there is nothing to be done
11011     testl(tmp5, 0xFFFFFFFF);
11012     jcc(Assembler::zero, post_alignement);
11013 
11014     // ~(~0 << len), where len is the # of remaining elements to process
11015     movl(result, 0xFFFFFFFF);
11016     shlxl(result, result, tmp5);
11017     notl(result);
11018     kmovdl(k1, result);
11019 
11020     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11021     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11022     ktestd(k2, k1);
11023     jcc(Assembler::carryClear, restore_k1_return_zero);
11024 
11025     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11026 
11027     addptr(src, tmp5);
11028     addptr(src, tmp5);
11029     addptr(dst, tmp5);
11030     subl(len, tmp5);
11031 
11032     bind(post_alignement);
11033     // end of alignement
11034 
11035     movl(tmp5, len);
11036     andl(tmp5, (32 - 1));    // tail count (in chars)
11037     andl(len, ~(32 - 1));    // vector count (in chars)
11038     jcc(Assembler::zero, copy_loop_tail);
11039 
11040     lea(src, Address(src, len, Address::times_2));
11041     lea(dst, Address(dst, len, Address::times_1));
11042     negptr(len);
11043 
11044     bind(copy_32_loop);
11045     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11046     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11047     kortestdl(k2, k2);
11048     jcc(Assembler::carryClear, restore_k1_return_zero);
11049 
11050     // All elements in current processed chunk are valid candidates for
11051     // compression. Write a truncated byte elements to the memory.
11052     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11053     addptr(len, 32);
11054     jcc(Assembler::notZero, copy_32_loop);
11055 
11056     bind(copy_loop_tail);
11057     // bail out when there is nothing to be done
11058     testl(tmp5, 0xFFFFFFFF);
11059     // Restore k1
11060     kmovql(k1, k3);
11061     jcc(Assembler::zero, return_length);
11062 
11063     movl(len, tmp5);
11064 
11065     // ~(~0 << len), where len is the # of remaining elements to process
11066     movl(result, 0xFFFFFFFF);
11067     shlxl(result, result, len);
11068     notl(result);
11069 
11070     kmovdl(k1, result);
11071 
11072     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11073     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11074     ktestd(k2, k1);
11075     jcc(Assembler::carryClear, restore_k1_return_zero);
11076 
11077     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11078     // Restore k1
11079     kmovql(k1, k3);
11080     jmp(return_length);
11081 
11082     bind(restore_k1_return_zero);
11083     // Restore k1
11084     kmovql(k1, k3);
11085     jmp(return_zero);
11086 
11087     clear_vector_masking();   // closing of the stub context for programming mask registers
11088   }
11089   if (UseSSE42Intrinsics) {
11090     Label copy_32_loop, copy_16, copy_tail;
11091 
11092     bind(below_threshold);
11093 
11094     movl(result, len);
11095 
11096     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11097 
11098     // vectored compression
11099     andl(len, 0xfffffff0);    // vector count (in chars)
11100     andl(result, 0x0000000f);    // tail count (in chars)
11101     testl(len, len);
11102     jccb(Assembler::zero, copy_16);
11103 
11104     // compress 16 chars per iter
11105     movdl(tmp1Reg, tmp5);
11106     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11107     pxor(tmp4Reg, tmp4Reg);
11108 
11109     lea(src, Address(src, len, Address::times_2));
11110     lea(dst, Address(dst, len, Address::times_1));
11111     negptr(len);
11112 
11113     bind(copy_32_loop);
11114     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11115     por(tmp4Reg, tmp2Reg);
11116     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11117     por(tmp4Reg, tmp3Reg);
11118     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11119     jcc(Assembler::notZero, return_zero);
11120     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11121     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11122     addptr(len, 16);
11123     jcc(Assembler::notZero, copy_32_loop);
11124 
11125     // compress next vector of 8 chars (if any)
11126     bind(copy_16);
11127     movl(len, result);
11128     andl(len, 0xfffffff8);    // vector count (in chars)
11129     andl(result, 0x00000007);    // tail count (in chars)
11130     testl(len, len);
11131     jccb(Assembler::zero, copy_tail);
11132 
11133     movdl(tmp1Reg, tmp5);
11134     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11135     pxor(tmp3Reg, tmp3Reg);
11136 
11137     movdqu(tmp2Reg, Address(src, 0));
11138     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11139     jccb(Assembler::notZero, return_zero);
11140     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11141     movq(Address(dst, 0), tmp2Reg);
11142     addptr(src, 16);
11143     addptr(dst, 8);
11144 
11145     bind(copy_tail);
11146     movl(len, result);
11147   }
11148   // compress 1 char per iter
11149   testl(len, len);
11150   jccb(Assembler::zero, return_length);
11151   lea(src, Address(src, len, Address::times_2));
11152   lea(dst, Address(dst, len, Address::times_1));
11153   negptr(len);
11154 
11155   bind(copy_chars_loop);
11156   load_unsigned_short(result, Address(src, len, Address::times_2));
11157   testl(result, 0xff00);      // check if Unicode char
11158   jccb(Assembler::notZero, return_zero);
11159   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11160   increment(len);
11161   jcc(Assembler::notZero, copy_chars_loop);
11162 
11163   // if compression succeeded, return length
11164   bind(return_length);
11165   pop(result);
11166   jmpb(done);
11167 
11168   // if compression failed, return 0
11169   bind(return_zero);
11170   xorl(result, result);
11171   addptr(rsp, wordSize);
11172 
11173   bind(done);
11174 }
11175 
11176 // Inflate byte[] array to char[].
11177 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11178 //   @HotSpotIntrinsicCandidate
11179 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11180 //     for (int i = 0; i < len; i++) {
11181 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11182 //     }
11183 //   }
11184 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11185   XMMRegister tmp1, Register tmp2) {
11186   Label copy_chars_loop, done, below_threshold;
11187   // rsi: src
11188   // rdi: dst
11189   // rdx: len
11190   // rcx: tmp2
11191 
11192   // rsi holds start addr of source byte[] to be inflated
11193   // rdi holds start addr of destination char[]
11194   // rdx holds length
11195   assert_different_registers(src, dst, len, tmp2);
11196 
11197   if ((UseAVX > 2) && // AVX512
11198     VM_Version::supports_avx512vlbw() &&
11199     VM_Version::supports_bmi2()) {
11200 
11201     set_vector_masking();  // opening of the stub context for programming mask registers
11202 
11203     Label copy_32_loop, copy_tail;
11204     Register tmp3_aliased = len;
11205 
11206     // if length of the string is less than 16, handle it in an old fashioned
11207     // way
11208     testl(len, -16);
11209     jcc(Assembler::zero, below_threshold);
11210 
11211     // In order to use only one arithmetic operation for the main loop we use
11212     // this pre-calculation
11213     movl(tmp2, len);
11214     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11215     andl(len, -32);     // vector count
11216     jccb(Assembler::zero, copy_tail);
11217 
11218     lea(src, Address(src, len, Address::times_1));
11219     lea(dst, Address(dst, len, Address::times_2));
11220     negptr(len);
11221 
11222 
11223     // inflate 32 chars per iter
11224     bind(copy_32_loop);
11225     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11226     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11227     addptr(len, 32);
11228     jcc(Assembler::notZero, copy_32_loop);
11229 
11230     bind(copy_tail);
11231     // bail out when there is nothing to be done
11232     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11233     jcc(Assembler::zero, done);
11234 
11235     // Save k1
11236     kmovql(k2, k1);
11237 
11238     // ~(~0 << length), where length is the # of remaining elements to process
11239     movl(tmp3_aliased, -1);
11240     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11241     notl(tmp3_aliased);
11242     kmovdl(k1, tmp3_aliased);
11243     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11244     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11245 
11246     // Restore k1
11247     kmovql(k1, k2);
11248     jmp(done);
11249 
11250     clear_vector_masking();   // closing of the stub context for programming mask registers
11251   }
11252   if (UseSSE42Intrinsics) {
11253     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11254 
11255     movl(tmp2, len);
11256 
11257     if (UseAVX > 1) {
11258       andl(tmp2, (16 - 1));
11259       andl(len, -16);
11260       jccb(Assembler::zero, copy_new_tail);
11261     } else {
11262       andl(tmp2, 0x00000007);   // tail count (in chars)
11263       andl(len, 0xfffffff8);    // vector count (in chars)
11264       jccb(Assembler::zero, copy_tail);
11265     }
11266 
11267     // vectored inflation
11268     lea(src, Address(src, len, Address::times_1));
11269     lea(dst, Address(dst, len, Address::times_2));
11270     negptr(len);
11271 
11272     if (UseAVX > 1) {
11273       bind(copy_16_loop);
11274       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11275       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11276       addptr(len, 16);
11277       jcc(Assembler::notZero, copy_16_loop);
11278 
11279       bind(below_threshold);
11280       bind(copy_new_tail);
11281       if ((UseAVX > 2) &&
11282         VM_Version::supports_avx512vlbw() &&
11283         VM_Version::supports_bmi2()) {
11284         movl(tmp2, len);
11285       } else {
11286         movl(len, tmp2);
11287       }
11288       andl(tmp2, 0x00000007);
11289       andl(len, 0xFFFFFFF8);
11290       jccb(Assembler::zero, copy_tail);
11291 
11292       pmovzxbw(tmp1, Address(src, 0));
11293       movdqu(Address(dst, 0), tmp1);
11294       addptr(src, 8);
11295       addptr(dst, 2 * 8);
11296 
11297       jmp(copy_tail, true);
11298     }
11299 
11300     // inflate 8 chars per iter
11301     bind(copy_8_loop);
11302     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11303     movdqu(Address(dst, len, Address::times_2), tmp1);
11304     addptr(len, 8);
11305     jcc(Assembler::notZero, copy_8_loop);
11306 
11307     bind(copy_tail);
11308     movl(len, tmp2);
11309 
11310     cmpl(len, 4);
11311     jccb(Assembler::less, copy_bytes);
11312 
11313     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11314     pmovzxbw(tmp1, tmp1);
11315     movq(Address(dst, 0), tmp1);
11316     subptr(len, 4);
11317     addptr(src, 4);
11318     addptr(dst, 8);
11319 
11320     bind(copy_bytes);
11321   }
11322   testl(len, len);
11323   jccb(Assembler::zero, done);
11324   lea(src, Address(src, len, Address::times_1));
11325   lea(dst, Address(dst, len, Address::times_2));
11326   negptr(len);
11327 
11328   // inflate 1 char per iter
11329   bind(copy_chars_loop);
11330   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11331   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11332   increment(len);
11333   jcc(Assembler::notZero, copy_chars_loop);
11334 
11335   bind(done);
11336 }
11337 
11338 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11339   switch (cond) {
11340     // Note some conditions are synonyms for others
11341     case Assembler::zero:         return Assembler::notZero;
11342     case Assembler::notZero:      return Assembler::zero;
11343     case Assembler::less:         return Assembler::greaterEqual;
11344     case Assembler::lessEqual:    return Assembler::greater;
11345     case Assembler::greater:      return Assembler::lessEqual;
11346     case Assembler::greaterEqual: return Assembler::less;
11347     case Assembler::below:        return Assembler::aboveEqual;
11348     case Assembler::belowEqual:   return Assembler::above;
11349     case Assembler::above:        return Assembler::belowEqual;
11350     case Assembler::aboveEqual:   return Assembler::below;
11351     case Assembler::overflow:     return Assembler::noOverflow;
11352     case Assembler::noOverflow:   return Assembler::overflow;
11353     case Assembler::negative:     return Assembler::positive;
11354     case Assembler::positive:     return Assembler::negative;
11355     case Assembler::parity:       return Assembler::noParity;
11356     case Assembler::noParity:     return Assembler::parity;
11357   }
11358   ShouldNotReachHere(); return Assembler::overflow;
11359 }
11360 
11361 SkipIfEqual::SkipIfEqual(
11362     MacroAssembler* masm, const bool* flag_addr, bool value) {
11363   _masm = masm;
11364   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11365   _masm->jcc(Assembler::equal, _label);
11366 }
11367 
11368 SkipIfEqual::~SkipIfEqual() {
11369   _masm->bind(_label);
11370 }
11371 
11372 // 32-bit Windows has its own fast-path implementation
11373 // of get_thread
11374 #if !defined(WIN32) || defined(_LP64)
11375 
11376 // This is simply a call to Thread::current()
11377 void MacroAssembler::get_thread(Register thread) {
11378   if (thread != rax) {
11379     push(rax);
11380   }
11381   LP64_ONLY(push(rdi);)
11382   LP64_ONLY(push(rsi);)
11383   push(rdx);
11384   push(rcx);
11385 #ifdef _LP64
11386   push(r8);
11387   push(r9);
11388   push(r10);
11389   push(r11);
11390 #endif
11391 
11392   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11393 
11394 #ifdef _LP64
11395   pop(r11);
11396   pop(r10);
11397   pop(r9);
11398   pop(r8);
11399 #endif
11400   pop(rcx);
11401   pop(rdx);
11402   LP64_ONLY(pop(rsi);)
11403   LP64_ONLY(pop(rdi);)
11404   if (thread != rax) {
11405     mov(thread, rax);
11406     pop(rax);
11407   }
11408 }
11409 
11410 #endif