1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/jvm.h"
  36 #include "prims/methodHandles.hpp"
  37 #include "runtime/biasedLocking.hpp"
  38 #include "runtime/interfaceSupport.hpp"
  39 #include "runtime/objectMonitor.hpp"
  40 #include "runtime/os.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "runtime/stubRoutines.hpp"
  43 #include "runtime/thread.hpp"
  44 #include "utilities/macros.hpp"
  45 #if INCLUDE_ALL_GCS
  46 #include "gc/g1/g1CollectedHeap.inline.hpp"
  47 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  48 #include "gc/g1/heapRegion.hpp"
  49 #include "gc/shenandoah/shenandoahConnectionMatrix.inline.hpp"
  50 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  51 #include "gc/shenandoah/shenandoahHeapRegion.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   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 841   pop_CPU_state();
 842   mov(rsp, rbp);
 843   pop(rbp);
 844 }
 845 
 846 void MacroAssembler::print_state() {
 847   address rip = pc();
 848   pusha();            // get regs on stack
 849   push(rbp);
 850   movq(rbp, rsp);
 851   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 852   push_CPU_state();   // keeps alignment at 16 bytes
 853 
 854   lea(c_rarg0, InternalAddress(rip));
 855   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 856   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 857 
 858   pop_CPU_state();
 859   mov(rsp, rbp);
 860   pop(rbp);
 861   popa();
 862 }
 863 
 864 #ifndef PRODUCT
 865 extern "C" void findpc(intptr_t x);
 866 #endif
 867 
 868 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 869   // In order to get locks to work, we need to fake a in_VM state
 870   if (ShowMessageBoxOnError) {
 871     JavaThread* thread = JavaThread::current();
 872     JavaThreadState saved_state = thread->thread_state();
 873     thread->set_thread_state(_thread_in_vm);
 874 #ifndef PRODUCT
 875     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 876       ttyLocker ttyl;
 877       BytecodeCounter::print();
 878     }
 879 #endif
 880     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 881     // XXX correct this offset for amd64
 882     // This is the value of eip which points to where verify_oop will return.
 883     if (os::message_box(msg, "Execution stopped, print registers?")) {
 884       print_state64(pc, regs);
 885       BREAKPOINT;
 886       assert(false, "start up GDB");
 887     }
 888     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 889   } else {
 890     ttyLocker ttyl;
 891     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 892                     msg);
 893     assert(false, "DEBUG MESSAGE: %s", msg);
 894   }
 895 }
 896 
 897 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 898   ttyLocker ttyl;
 899   FlagSetting fs(Debugging, true);
 900   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 901 #ifndef PRODUCT
 902   tty->cr();
 903   findpc(pc);
 904   tty->cr();
 905 #endif
 906 #define PRINT_REG(rax, value) \
 907   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 908   PRINT_REG(rax, regs[15]);
 909   PRINT_REG(rbx, regs[12]);
 910   PRINT_REG(rcx, regs[14]);
 911   PRINT_REG(rdx, regs[13]);
 912   PRINT_REG(rdi, regs[8]);
 913   PRINT_REG(rsi, regs[9]);
 914   PRINT_REG(rbp, regs[10]);
 915   PRINT_REG(rsp, regs[11]);
 916   PRINT_REG(r8 , regs[7]);
 917   PRINT_REG(r9 , regs[6]);
 918   PRINT_REG(r10, regs[5]);
 919   PRINT_REG(r11, regs[4]);
 920   PRINT_REG(r12, regs[3]);
 921   PRINT_REG(r13, regs[2]);
 922   PRINT_REG(r14, regs[1]);
 923   PRINT_REG(r15, regs[0]);
 924 #undef PRINT_REG
 925   // Print some words near top of staack.
 926   int64_t* rsp = (int64_t*) regs[11];
 927   int64_t* dump_sp = rsp;
 928   for (int col1 = 0; col1 < 8; col1++) {
 929     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 930     os::print_location(tty, *dump_sp++);
 931   }
 932   for (int row = 0; row < 25; row++) {
 933     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 934     for (int col = 0; col < 4; col++) {
 935       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 936     }
 937     tty->cr();
 938   }
 939   // Print some instructions around pc:
 940   Disassembler::decode((address)pc-64, (address)pc);
 941   tty->print_cr("--------");
 942   Disassembler::decode((address)pc, (address)pc+32);
 943 }
 944 
 945 #endif // _LP64
 946 
 947 // Now versions that are common to 32/64 bit
 948 
 949 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 950   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 951 }
 952 
 953 void MacroAssembler::addptr(Register dst, Register src) {
 954   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 955 }
 956 
 957 void MacroAssembler::addptr(Address dst, Register src) {
 958   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 959 }
 960 
 961 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 962   if (reachable(src)) {
 963     Assembler::addsd(dst, as_Address(src));
 964   } else {
 965     lea(rscratch1, src);
 966     Assembler::addsd(dst, Address(rscratch1, 0));
 967   }
 968 }
 969 
 970 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 971   if (reachable(src)) {
 972     addss(dst, as_Address(src));
 973   } else {
 974     lea(rscratch1, src);
 975     addss(dst, Address(rscratch1, 0));
 976   }
 977 }
 978 
 979 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 980   if (reachable(src)) {
 981     Assembler::addpd(dst, as_Address(src));
 982   } else {
 983     lea(rscratch1, src);
 984     Assembler::addpd(dst, Address(rscratch1, 0));
 985   }
 986 }
 987 
 988 void MacroAssembler::align(int modulus) {
 989   align(modulus, offset());
 990 }
 991 
 992 void MacroAssembler::align(int modulus, int target) {
 993   if (target % modulus != 0) {
 994     nop(modulus - (target % modulus));
 995   }
 996 }
 997 
 998 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 999   // Used in sign-masking with aligned address.
1000   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1001   if (reachable(src)) {
1002     Assembler::andpd(dst, as_Address(src));
1003   } else {
1004     lea(rscratch1, src);
1005     Assembler::andpd(dst, Address(rscratch1, 0));
1006   }
1007 }
1008 
1009 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1010   // Used in sign-masking with aligned address.
1011   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1012   if (reachable(src)) {
1013     Assembler::andps(dst, as_Address(src));
1014   } else {
1015     lea(rscratch1, src);
1016     Assembler::andps(dst, Address(rscratch1, 0));
1017   }
1018 }
1019 
1020 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1021   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1022 }
1023 
1024 void MacroAssembler::atomic_incl(Address counter_addr) {
1025   if (os::is_MP())
1026     lock();
1027   incrementl(counter_addr);
1028 }
1029 
1030 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1031   if (reachable(counter_addr)) {
1032     atomic_incl(as_Address(counter_addr));
1033   } else {
1034     lea(scr, counter_addr);
1035     atomic_incl(Address(scr, 0));
1036   }
1037 }
1038 
1039 #ifdef _LP64
1040 void MacroAssembler::atomic_incq(Address counter_addr) {
1041   if (os::is_MP())
1042     lock();
1043   incrementq(counter_addr);
1044 }
1045 
1046 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1047   if (reachable(counter_addr)) {
1048     atomic_incq(as_Address(counter_addr));
1049   } else {
1050     lea(scr, counter_addr);
1051     atomic_incq(Address(scr, 0));
1052   }
1053 }
1054 #endif
1055 
1056 // Writes to stack successive pages until offset reached to check for
1057 // stack overflow + shadow pages.  This clobbers tmp.
1058 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1059   movptr(tmp, rsp);
1060   // Bang stack for total size given plus shadow page size.
1061   // Bang one page at a time because large size can bang beyond yellow and
1062   // red zones.
1063   Label loop;
1064   bind(loop);
1065   movl(Address(tmp, (-os::vm_page_size())), size );
1066   subptr(tmp, os::vm_page_size());
1067   subl(size, os::vm_page_size());
1068   jcc(Assembler::greater, loop);
1069 
1070   // Bang down shadow pages too.
1071   // At this point, (tmp-0) is the last address touched, so don't
1072   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1073   // was post-decremented.)  Skip this address by starting at i=1, and
1074   // touch a few more pages below.  N.B.  It is important to touch all
1075   // the way down including all pages in the shadow zone.
1076   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1077     // this could be any sized move but this is can be a debugging crumb
1078     // so the bigger the better.
1079     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1080   }
1081 }
1082 
1083 void MacroAssembler::reserved_stack_check() {
1084     // testing if reserved zone needs to be enabled
1085     Label no_reserved_zone_enabling;
1086     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1087     NOT_LP64(get_thread(rsi);)
1088 
1089     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1090     jcc(Assembler::below, no_reserved_zone_enabling);
1091 
1092     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1093     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1094     should_not_reach_here();
1095 
1096     bind(no_reserved_zone_enabling);
1097 }
1098 
1099 int MacroAssembler::biased_locking_enter(Register lock_reg,
1100                                          Register obj_reg,
1101                                          Register swap_reg,
1102                                          Register tmp_reg,
1103                                          bool swap_reg_contains_mark,
1104                                          Label& done,
1105                                          Label* slow_case,
1106                                          BiasedLockingCounters* counters) {
1107   assert(UseBiasedLocking, "why call this otherwise?");
1108   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1109   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1110   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1111   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1112   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1113   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1114 
1115   shenandoah_store_addr_check(obj_reg);
1116 
1117   if (PrintBiasedLockingStatistics && counters == NULL) {
1118     counters = BiasedLocking::counters();
1119   }
1120   // Biased locking
1121   // See whether the lock is currently biased toward our thread and
1122   // whether the epoch is still valid
1123   // Note that the runtime guarantees sufficient alignment of JavaThread
1124   // pointers to allow age to be placed into low bits
1125   // First check to see whether biasing is even enabled for this object
1126   Label cas_label;
1127   int null_check_offset = -1;
1128   if (!swap_reg_contains_mark) {
1129     null_check_offset = offset();
1130     movptr(swap_reg, mark_addr);
1131   }
1132   movptr(tmp_reg, swap_reg);
1133   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1134   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1135   jcc(Assembler::notEqual, cas_label);
1136   // The bias pattern is present in the object's header. Need to check
1137   // whether the bias owner and the epoch are both still current.
1138 #ifndef _LP64
1139   // Note that because there is no current thread register on x86_32 we
1140   // need to store off the mark word we read out of the object to
1141   // avoid reloading it and needing to recheck invariants below. This
1142   // store is unfortunate but it makes the overall code shorter and
1143   // simpler.
1144   movptr(saved_mark_addr, swap_reg);
1145 #endif
1146   if (swap_reg_contains_mark) {
1147     null_check_offset = offset();
1148   }
1149   load_prototype_header(tmp_reg, obj_reg);
1150 #ifdef _LP64
1151   orptr(tmp_reg, r15_thread);
1152   xorptr(tmp_reg, swap_reg);
1153   Register header_reg = tmp_reg;
1154 #else
1155   xorptr(tmp_reg, swap_reg);
1156   get_thread(swap_reg);
1157   xorptr(swap_reg, tmp_reg);
1158   Register header_reg = swap_reg;
1159 #endif
1160   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1161   if (counters != NULL) {
1162     cond_inc32(Assembler::zero,
1163                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1164   }
1165   jcc(Assembler::equal, done);
1166 
1167   Label try_revoke_bias;
1168   Label try_rebias;
1169 
1170   // At this point we know that the header has the bias pattern and
1171   // that we are not the bias owner in the current epoch. We need to
1172   // figure out more details about the state of the header in order to
1173   // know what operations can be legally performed on the object's
1174   // header.
1175 
1176   // If the low three bits in the xor result aren't clear, that means
1177   // the prototype header is no longer biased and we have to revoke
1178   // the bias on this object.
1179   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1180   jccb_if_possible(Assembler::notZero, try_revoke_bias);
1181 
1182   // Biasing is still enabled for this data type. See whether the
1183   // epoch of the current bias is still valid, meaning that the epoch
1184   // bits of the mark word are equal to the epoch bits of the
1185   // prototype header. (Note that the prototype header's epoch bits
1186   // only change at a safepoint.) If not, attempt to rebias the object
1187   // toward the current thread. Note that we must be absolutely sure
1188   // that the current epoch is invalid in order to do this because
1189   // otherwise the manipulations it performs on the mark word are
1190   // illegal.
1191   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1192   jccb_if_possible(Assembler::notZero, try_rebias);
1193 
1194   // The epoch of the current bias is still valid but we know nothing
1195   // about the owner; it might be set or it might be clear. Try to
1196   // acquire the bias of the object using an atomic operation. If this
1197   // fails we will go in to the runtime to revoke the object's bias.
1198   // Note that we first construct the presumed unbiased header so we
1199   // don't accidentally blow away another thread's valid bias.
1200   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1201   andptr(swap_reg,
1202          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1203 #ifdef _LP64
1204   movptr(tmp_reg, swap_reg);
1205   orptr(tmp_reg, r15_thread);
1206 #else
1207   get_thread(tmp_reg);
1208   orptr(tmp_reg, swap_reg);
1209 #endif
1210   if (os::is_MP()) {
1211     lock();
1212   }
1213   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1214   // If the biasing toward our thread failed, this means that
1215   // another thread succeeded in biasing it toward itself and we
1216   // need to revoke that bias. The revocation will occur in the
1217   // interpreter runtime in the slow case.
1218   if (counters != NULL) {
1219     cond_inc32(Assembler::zero,
1220                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1221   }
1222   if (slow_case != NULL) {
1223     jcc(Assembler::notZero, *slow_case);
1224   }
1225   jmp(done);
1226 
1227   bind(try_rebias);
1228   // At this point we know the epoch has expired, meaning that the
1229   // current "bias owner", if any, is actually invalid. Under these
1230   // circumstances _only_, we are allowed to use the current header's
1231   // value as the comparison value when doing the cas to acquire the
1232   // bias in the current epoch. In other words, we allow transfer of
1233   // the bias from one thread to another directly in this situation.
1234   //
1235   // FIXME: due to a lack of registers we currently blow away the age
1236   // bits in this situation. Should attempt to preserve them.
1237   load_prototype_header(tmp_reg, obj_reg);
1238 #ifdef _LP64
1239   orptr(tmp_reg, r15_thread);
1240 #else
1241   get_thread(swap_reg);
1242   orptr(tmp_reg, swap_reg);
1243   movptr(swap_reg, saved_mark_addr);
1244 #endif
1245   if (os::is_MP()) {
1246     lock();
1247   }
1248   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1249   // If the biasing toward our thread failed, then another thread
1250   // succeeded in biasing it toward itself and we need to revoke that
1251   // bias. The revocation will occur in the runtime in the slow case.
1252   if (counters != NULL) {
1253     cond_inc32(Assembler::zero,
1254                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1255   }
1256   if (slow_case != NULL) {
1257     jcc(Assembler::notZero, *slow_case);
1258   }
1259   jmp(done);
1260 
1261   bind(try_revoke_bias);
1262   // The prototype mark in the klass doesn't have the bias bit set any
1263   // more, indicating that objects of this data type are not supposed
1264   // to be biased any more. We are going to try to reset the mark of
1265   // this object to the prototype value and fall through to the
1266   // CAS-based locking scheme. Note that if our CAS fails, it means
1267   // that another thread raced us for the privilege of revoking the
1268   // bias of this particular object, so it's okay to continue in the
1269   // normal locking code.
1270   //
1271   // FIXME: due to a lack of registers we currently blow away the age
1272   // bits in this situation. Should attempt to preserve them.
1273   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1274   load_prototype_header(tmp_reg, obj_reg);
1275   if (os::is_MP()) {
1276     lock();
1277   }
1278   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1279   // Fall through to the normal CAS-based lock, because no matter what
1280   // the result of the above CAS, some thread must have succeeded in
1281   // removing the bias bit from the object's header.
1282   if (counters != NULL) {
1283     cond_inc32(Assembler::zero,
1284                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1285   }
1286 
1287   bind(cas_label);
1288 
1289   return null_check_offset;
1290 }
1291 
1292 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1293   assert(UseBiasedLocking, "why call this otherwise?");
1294 
1295   // Check for biased locking unlock case, which is a no-op
1296   // Note: we do not have to check the thread ID for two reasons.
1297   // First, the interpreter checks for IllegalMonitorStateException at
1298   // a higher level. Second, if the bias was revoked while we held the
1299   // lock, the object could not be rebiased toward another thread, so
1300   // the bias bit would be clear.
1301   shenandoah_store_addr_check(obj_reg); // Access mark word
1302   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1303   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1304   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1305   jcc(Assembler::equal, done);
1306 }
1307 
1308 #ifdef COMPILER2
1309 
1310 #if INCLUDE_RTM_OPT
1311 
1312 // Update rtm_counters based on abort status
1313 // input: abort_status
1314 //        rtm_counters (RTMLockingCounters*)
1315 // flags are killed
1316 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1317 
1318   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1319   if (PrintPreciseRTMLockingStatistics) {
1320     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1321       Label check_abort;
1322       testl(abort_status, (1<<i));
1323       jccb(Assembler::equal, check_abort);
1324       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1325       bind(check_abort);
1326     }
1327   }
1328 }
1329 
1330 // Branch if (random & (count-1) != 0), count is 2^n
1331 // tmp, scr and flags are killed
1332 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1333   assert(tmp == rax, "");
1334   assert(scr == rdx, "");
1335   rdtsc(); // modifies EDX:EAX
1336   andptr(tmp, count-1);
1337   jccb(Assembler::notZero, brLabel);
1338 }
1339 
1340 // Perform abort ratio calculation, set no_rtm bit if high ratio
1341 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1342 // tmpReg, rtm_counters_Reg and flags are killed
1343 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1344                                                  Register rtm_counters_Reg,
1345                                                  RTMLockingCounters* rtm_counters,
1346                                                  Metadata* method_data) {
1347   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1348 
1349   if (RTMLockingCalculationDelay > 0) {
1350     // Delay calculation
1351     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1352     testptr(tmpReg, tmpReg);
1353     jccb(Assembler::equal, L_done);
1354   }
1355   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1356   //   Aborted transactions = abort_count * 100
1357   //   All transactions = total_count *  RTMTotalCountIncrRate
1358   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1359 
1360   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1361   cmpptr(tmpReg, RTMAbortThreshold);
1362   jccb(Assembler::below, L_check_always_rtm2);
1363   imulptr(tmpReg, tmpReg, 100);
1364 
1365   Register scrReg = rtm_counters_Reg;
1366   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1367   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1368   imulptr(scrReg, scrReg, RTMAbortRatio);
1369   cmpptr(tmpReg, scrReg);
1370   jccb(Assembler::below, L_check_always_rtm1);
1371   if (method_data != NULL) {
1372     // set rtm_state to "no rtm" in MDO
1373     mov_metadata(tmpReg, method_data);
1374     if (os::is_MP()) {
1375       lock();
1376     }
1377     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1378   }
1379   jmpb(L_done);
1380   bind(L_check_always_rtm1);
1381   // Reload RTMLockingCounters* address
1382   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1383   bind(L_check_always_rtm2);
1384   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1385   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1386   jccb(Assembler::below, L_done);
1387   if (method_data != NULL) {
1388     // set rtm_state to "always rtm" in MDO
1389     mov_metadata(tmpReg, method_data);
1390     if (os::is_MP()) {
1391       lock();
1392     }
1393     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1394   }
1395   bind(L_done);
1396 }
1397 
1398 // Update counters and perform abort ratio calculation
1399 // input:  abort_status_Reg
1400 // rtm_counters_Reg, flags are killed
1401 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1402                                    Register rtm_counters_Reg,
1403                                    RTMLockingCounters* rtm_counters,
1404                                    Metadata* method_data,
1405                                    bool profile_rtm) {
1406 
1407   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1408   // update rtm counters based on rax value at abort
1409   // reads abort_status_Reg, updates flags
1410   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1411   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1412   if (profile_rtm) {
1413     // Save abort status because abort_status_Reg is used by following code.
1414     if (RTMRetryCount > 0) {
1415       push(abort_status_Reg);
1416     }
1417     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1418     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1419     // restore abort status
1420     if (RTMRetryCount > 0) {
1421       pop(abort_status_Reg);
1422     }
1423   }
1424 }
1425 
1426 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1427 // inputs: retry_count_Reg
1428 //       : abort_status_Reg
1429 // output: retry_count_Reg decremented by 1
1430 // flags are killed
1431 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1432   Label doneRetry;
1433   assert(abort_status_Reg == rax, "");
1434   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1435   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1436   // if reason is in 0x6 and retry count != 0 then retry
1437   andptr(abort_status_Reg, 0x6);
1438   jccb(Assembler::zero, doneRetry);
1439   testl(retry_count_Reg, retry_count_Reg);
1440   jccb(Assembler::zero, doneRetry);
1441   pause();
1442   decrementl(retry_count_Reg);
1443   jmp(retryLabel);
1444   bind(doneRetry);
1445 }
1446 
1447 // Spin and retry if lock is busy,
1448 // inputs: box_Reg (monitor address)
1449 //       : retry_count_Reg
1450 // output: retry_count_Reg decremented by 1
1451 //       : clear z flag if retry count exceeded
1452 // tmp_Reg, scr_Reg, flags are killed
1453 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1454                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1455   Label SpinLoop, SpinExit, doneRetry;
1456   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1457 
1458   testl(retry_count_Reg, retry_count_Reg);
1459   jccb(Assembler::zero, doneRetry);
1460   decrementl(retry_count_Reg);
1461   movptr(scr_Reg, RTMSpinLoopCount);
1462 
1463   bind(SpinLoop);
1464   pause();
1465   decrementl(scr_Reg);
1466   jccb(Assembler::lessEqual, SpinExit);
1467   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1468   testptr(tmp_Reg, tmp_Reg);
1469   jccb(Assembler::notZero, SpinLoop);
1470 
1471   bind(SpinExit);
1472   jmp(retryLabel);
1473   bind(doneRetry);
1474   incrementl(retry_count_Reg); // clear z flag
1475 }
1476 
1477 // Use RTM for normal stack locks
1478 // Input: objReg (object to lock)
1479 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1480                                        Register retry_on_abort_count_Reg,
1481                                        RTMLockingCounters* stack_rtm_counters,
1482                                        Metadata* method_data, bool profile_rtm,
1483                                        Label& DONE_LABEL, Label& IsInflated) {
1484   assert(UseRTMForStackLocks, "why call this otherwise?");
1485   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1486   assert(tmpReg == rax, "");
1487   assert(scrReg == rdx, "");
1488   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1489 
1490   if (RTMRetryCount > 0) {
1491     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1492     bind(L_rtm_retry);
1493   }
1494   shenandoah_store_addr_check(objReg); // Access mark word
1495   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1496   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1497   jcc(Assembler::notZero, IsInflated);
1498 
1499   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1500     Label L_noincrement;
1501     if (RTMTotalCountIncrRate > 1) {
1502       // tmpReg, scrReg and flags are killed
1503       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1504     }
1505     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1506     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1507     bind(L_noincrement);
1508   }
1509   xbegin(L_on_abort);
1510   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1511   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1512   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1513   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1514 
1515   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1516   if (UseRTMXendForLockBusy) {
1517     xend();
1518     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1519     jmp(L_decrement_retry);
1520   }
1521   else {
1522     xabort(0);
1523   }
1524   bind(L_on_abort);
1525   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1526     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1527   }
1528   bind(L_decrement_retry);
1529   if (RTMRetryCount > 0) {
1530     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1531     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1532   }
1533 }
1534 
1535 // Use RTM for inflating locks
1536 // inputs: objReg (object to lock)
1537 //         boxReg (on-stack box address (displaced header location) - KILLED)
1538 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1539 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1540                                           Register scrReg, Register retry_on_busy_count_Reg,
1541                                           Register retry_on_abort_count_Reg,
1542                                           RTMLockingCounters* rtm_counters,
1543                                           Metadata* method_data, bool profile_rtm,
1544                                           Label& DONE_LABEL) {
1545   assert(UseRTMLocking, "why call this otherwise?");
1546   assert(tmpReg == rax, "");
1547   assert(scrReg == rdx, "");
1548   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1549   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1550 
1551   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1552   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1553   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1554 
1555   if (RTMRetryCount > 0) {
1556     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1557     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1558     bind(L_rtm_retry);
1559   }
1560   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1561     Label L_noincrement;
1562     if (RTMTotalCountIncrRate > 1) {
1563       // tmpReg, scrReg and flags are killed
1564       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1565     }
1566     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1567     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1568     bind(L_noincrement);
1569   }
1570   xbegin(L_on_abort);
1571   shenandoah_store_addr_check(objReg); // Access mark word
1572   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1573   movptr(tmpReg, Address(tmpReg, owner_offset));
1574   testptr(tmpReg, tmpReg);
1575   jcc(Assembler::zero, DONE_LABEL);
1576   if (UseRTMXendForLockBusy) {
1577     xend();
1578     jmp(L_decrement_retry);
1579   }
1580   else {
1581     xabort(0);
1582   }
1583   bind(L_on_abort);
1584   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1585   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1586     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1587   }
1588   if (RTMRetryCount > 0) {
1589     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1590     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1591   }
1592 
1593   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1594   testptr(tmpReg, tmpReg) ;
1595   jccb(Assembler::notZero, L_decrement_retry) ;
1596 
1597   // Appears unlocked - try to swing _owner from null to non-null.
1598   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1599 #ifdef _LP64
1600   Register threadReg = r15_thread;
1601 #else
1602   get_thread(scrReg);
1603   Register threadReg = scrReg;
1604 #endif
1605   if (os::is_MP()) {
1606     lock();
1607   }
1608   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1609 
1610   if (RTMRetryCount > 0) {
1611     // success done else retry
1612     jccb(Assembler::equal, DONE_LABEL) ;
1613     bind(L_decrement_retry);
1614     // Spin and retry if lock is busy.
1615     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1616   }
1617   else {
1618     bind(L_decrement_retry);
1619   }
1620 }
1621 
1622 #endif //  INCLUDE_RTM_OPT
1623 
1624 // Fast_Lock and Fast_Unlock used by C2
1625 
1626 // Because the transitions from emitted code to the runtime
1627 // monitorenter/exit helper stubs are so slow it's critical that
1628 // we inline both the stack-locking fast-path and the inflated fast path.
1629 //
1630 // See also: cmpFastLock and cmpFastUnlock.
1631 //
1632 // What follows is a specialized inline transliteration of the code
1633 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1634 // another option would be to emit TrySlowEnter and TrySlowExit methods
1635 // at startup-time.  These methods would accept arguments as
1636 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1637 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1638 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1639 // In practice, however, the # of lock sites is bounded and is usually small.
1640 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1641 // if the processor uses simple bimodal branch predictors keyed by EIP
1642 // Since the helper routines would be called from multiple synchronization
1643 // sites.
1644 //
1645 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1646 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1647 // to those specialized methods.  That'd give us a mostly platform-independent
1648 // implementation that the JITs could optimize and inline at their pleasure.
1649 // Done correctly, the only time we'd need to cross to native could would be
1650 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1651 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1652 // (b) explicit barriers or fence operations.
1653 //
1654 // TODO:
1655 //
1656 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1657 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1658 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1659 //    the lock operators would typically be faster than reifying Self.
1660 //
1661 // *  Ideally I'd define the primitives as:
1662 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1663 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1664 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1665 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1666 //    Furthermore the register assignments are overconstrained, possibly resulting in
1667 //    sub-optimal code near the synchronization site.
1668 //
1669 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1670 //    Alternately, use a better sp-proximity test.
1671 //
1672 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1673 //    Either one is sufficient to uniquely identify a thread.
1674 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1675 //
1676 // *  Intrinsify notify() and notifyAll() for the common cases where the
1677 //    object is locked by the calling thread but the waitlist is empty.
1678 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1679 //
1680 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1681 //    But beware of excessive branch density on AMD Opterons.
1682 //
1683 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1684 //    or failure of the fast-path.  If the fast-path fails then we pass
1685 //    control to the slow-path, typically in C.  In Fast_Lock and
1686 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1687 //    will emit a conditional branch immediately after the node.
1688 //    So we have branches to branches and lots of ICC.ZF games.
1689 //    Instead, it might be better to have C2 pass a "FailureLabel"
1690 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1691 //    will drop through the node.  ICC.ZF is undefined at exit.
1692 //    In the case of failure, the node will branch directly to the
1693 //    FailureLabel
1694 
1695 
1696 // obj: object to lock
1697 // box: on-stack box address (displaced header location) - KILLED
1698 // rax,: tmp -- KILLED
1699 // scr: tmp -- KILLED
1700 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1701                                Register scrReg, Register cx1Reg, Register cx2Reg,
1702                                BiasedLockingCounters* counters,
1703                                RTMLockingCounters* rtm_counters,
1704                                RTMLockingCounters* stack_rtm_counters,
1705                                Metadata* method_data,
1706                                bool use_rtm, bool profile_rtm) {
1707   // Ensure the register assignments are disjoint
1708   assert(tmpReg == rax, "");
1709 
1710   if (use_rtm) {
1711     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1712   } else {
1713     assert(cx1Reg == noreg, "");
1714     assert(cx2Reg == noreg, "");
1715     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1716   }
1717 
1718   shenandoah_store_addr_check(objReg); // Access mark word
1719 
1720   if (counters != NULL) {
1721     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1722   }
1723   if (EmitSync & 1) {
1724       // set box->dhw = markOopDesc::unused_mark()
1725       // Force all sync thru slow-path: slow_enter() and slow_exit()
1726       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1727       cmpptr (rsp, (int32_t)NULL_WORD);
1728   } else {
1729     // Possible cases that we'll encounter in fast_lock
1730     // ------------------------------------------------
1731     // * Inflated
1732     //    -- unlocked
1733     //    -- Locked
1734     //       = by self
1735     //       = by other
1736     // * biased
1737     //    -- by Self
1738     //    -- by other
1739     // * neutral
1740     // * stack-locked
1741     //    -- by self
1742     //       = sp-proximity test hits
1743     //       = sp-proximity test generates false-negative
1744     //    -- by other
1745     //
1746 
1747     Label IsInflated, DONE_LABEL;
1748 
1749     // it's stack-locked, biased or neutral
1750     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1751     // order to reduce the number of conditional branches in the most common cases.
1752     // Beware -- there's a subtle invariant that fetch of the markword
1753     // at [FETCH], below, will never observe a biased encoding (*101b).
1754     // If this invariant is not held we risk exclusion (safety) failure.
1755     if (UseBiasedLocking && !UseOptoBiasInlining) {
1756       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1757     }
1758 
1759 #if INCLUDE_RTM_OPT
1760     if (UseRTMForStackLocks && use_rtm) {
1761       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1762                         stack_rtm_counters, method_data, profile_rtm,
1763                         DONE_LABEL, IsInflated);
1764     }
1765 #endif // INCLUDE_RTM_OPT
1766 
1767     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1768     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1769     jccb_if_possible(Assembler::notZero, IsInflated);
1770 
1771     // Attempt stack-locking ...
1772     orptr (tmpReg, markOopDesc::unlocked_value);
1773     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1774     if (os::is_MP()) {
1775       lock();
1776     }
1777     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1778     if (counters != NULL) {
1779       cond_inc32(Assembler::equal,
1780                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1781     }
1782     jcc(Assembler::equal, DONE_LABEL);           // Success
1783 
1784     // Recursive locking.
1785     // The object is stack-locked: markword contains stack pointer to BasicLock.
1786     // Locked by current thread if difference with current SP is less than one page.
1787     subptr(tmpReg, rsp);
1788     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1789     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1790     movptr(Address(boxReg, 0), tmpReg);
1791     if (counters != NULL) {
1792       cond_inc32(Assembler::equal,
1793                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1794     }
1795     jmp(DONE_LABEL);
1796 
1797     bind(IsInflated);
1798     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1799 
1800 #if INCLUDE_RTM_OPT
1801     // Use the same RTM locking code in 32- and 64-bit VM.
1802     if (use_rtm) {
1803       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1804                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1805     } else {
1806 #endif // INCLUDE_RTM_OPT
1807 
1808 #ifndef _LP64
1809     // The object is inflated.
1810 
1811     // boxReg refers to the on-stack BasicLock in the current frame.
1812     // We'd like to write:
1813     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1814     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1815     // additional latency as we have another ST in the store buffer that must drain.
1816 
1817     if (EmitSync & 8192) {
1818        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1819        get_thread (scrReg);
1820        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1821        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1822        if (os::is_MP()) {
1823          lock();
1824        }
1825        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1826     } else
1827     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1828        // register juggle because we need tmpReg for cmpxchgptr below
1829        movptr(scrReg, boxReg);
1830        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1831 
1832        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1833        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1834           // prefetchw [eax + Offset(_owner)-2]
1835           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1836        }
1837 
1838        if ((EmitSync & 64) == 0) {
1839          // Optimistic form: consider XORL tmpReg,tmpReg
1840          movptr(tmpReg, NULL_WORD);
1841        } else {
1842          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1843          // Test-And-CAS instead of CAS
1844          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1845          testptr(tmpReg, tmpReg);                   // Locked ?
1846          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1847        }
1848 
1849        // Appears unlocked - try to swing _owner from null to non-null.
1850        // Ideally, I'd manifest "Self" with get_thread and then attempt
1851        // to CAS the register containing Self into m->Owner.
1852        // But we don't have enough registers, so instead we can either try to CAS
1853        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1854        // we later store "Self" into m->Owner.  Transiently storing a stack address
1855        // (rsp or the address of the box) into  m->owner is harmless.
1856        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1857        if (os::is_MP()) {
1858          lock();
1859        }
1860        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1861        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1862        // If we weren't able to swing _owner from NULL to the BasicLock
1863        // then take the slow path.
1864        jccb_if_possible(Assembler::notZero, DONE_LABEL);
1865        // update _owner from BasicLock to thread
1866        get_thread (scrReg);                    // beware: clobbers ICCs
1867        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1868        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1869 
1870        // If the CAS fails we can either retry or pass control to the slow-path.
1871        // We use the latter tactic.
1872        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1873        // If the CAS was successful ...
1874        //   Self has acquired the lock
1875        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1876        // Intentional fall-through into DONE_LABEL ...
1877     } else {
1878        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1879        movptr(boxReg, tmpReg);
1880 
1881        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1882        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1883           // prefetchw [eax + Offset(_owner)-2]
1884           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1885        }
1886 
1887        if ((EmitSync & 64) == 0) {
1888          // Optimistic form
1889          xorptr  (tmpReg, tmpReg);
1890        } else {
1891          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1892          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1893          testptr(tmpReg, tmpReg);                   // Locked ?
1894          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1895        }
1896 
1897        // Appears unlocked - try to swing _owner from null to non-null.
1898        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1899        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1900        get_thread (scrReg);
1901        if (os::is_MP()) {
1902          lock();
1903        }
1904        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1905 
1906        // If the CAS fails we can either retry or pass control to the slow-path.
1907        // We use the latter tactic.
1908        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1909        // If the CAS was successful ...
1910        //   Self has acquired the lock
1911        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1912        // Intentional fall-through into DONE_LABEL ...
1913     }
1914 #else // _LP64
1915     // It's inflated
1916     movq(scrReg, tmpReg);
1917     xorq(tmpReg, tmpReg);
1918 
1919     if (os::is_MP()) {
1920       lock();
1921     }
1922     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1923     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1924     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1925     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1926     // Intentional fall-through into DONE_LABEL ...
1927     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1928 #endif // _LP64
1929 #if INCLUDE_RTM_OPT
1930     } // use_rtm()
1931 #endif
1932     // DONE_LABEL is a hot target - we'd really like to place it at the
1933     // start of cache line by padding with NOPs.
1934     // See the AMD and Intel software optimization manuals for the
1935     // most efficient "long" NOP encodings.
1936     // Unfortunately none of our alignment mechanisms suffice.
1937     bind(DONE_LABEL);
1938 
1939     // At DONE_LABEL the icc ZFlag is set as follows ...
1940     // Fast_Unlock uses the same protocol.
1941     // ZFlag == 1 -> Success
1942     // ZFlag == 0 -> Failure - force control through the slow-path
1943   }
1944 }
1945 
1946 // obj: object to unlock
1947 // box: box address (displaced header location), killed.  Must be EAX.
1948 // tmp: killed, cannot be obj nor box.
1949 //
1950 // Some commentary on balanced locking:
1951 //
1952 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1953 // Methods that don't have provably balanced locking are forced to run in the
1954 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1955 // The interpreter provides two properties:
1956 // I1:  At return-time the interpreter automatically and quietly unlocks any
1957 //      objects acquired the current activation (frame).  Recall that the
1958 //      interpreter maintains an on-stack list of locks currently held by
1959 //      a frame.
1960 // I2:  If a method attempts to unlock an object that is not held by the
1961 //      the frame the interpreter throws IMSX.
1962 //
1963 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1964 // B() doesn't have provably balanced locking so it runs in the interpreter.
1965 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1966 // is still locked by A().
1967 //
1968 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1969 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1970 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1971 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1972 // Arguably given that the spec legislates the JNI case as undefined our implementation
1973 // could reasonably *avoid* checking owner in Fast_Unlock().
1974 // In the interest of performance we elide m->Owner==Self check in unlock.
1975 // A perfectly viable alternative is to elide the owner check except when
1976 // Xcheck:jni is enabled.
1977 
1978 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1979   assert(boxReg == rax, "");
1980   assert_different_registers(objReg, boxReg, tmpReg);
1981 
1982   shenandoah_store_addr_check(objReg); // Access mark word
1983 
1984   if (EmitSync & 4) {
1985     // Disable - inhibit all inlining.  Force control through the slow-path
1986     cmpptr (rsp, 0);
1987   } else {
1988     Label DONE_LABEL, Stacked, CheckSucc;
1989 
1990     // Critically, the biased locking test must have precedence over
1991     // and appear before the (box->dhw == 0) recursive stack-lock test.
1992     if (UseBiasedLocking && !UseOptoBiasInlining) {
1993        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1994     }
1995 
1996 #if INCLUDE_RTM_OPT
1997     if (UseRTMForStackLocks && use_rtm) {
1998       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1999       Label L_regular_unlock;
2000       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
2001       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
2002       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
2003       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2004       xend();                                       // otherwise end...
2005       jmp(DONE_LABEL);                              // ... and we're done
2006       bind(L_regular_unlock);
2007     }
2008 #endif
2009 
2010     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2011     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2012     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2013     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2014     jccb  (Assembler::zero, Stacked);
2015 
2016     // It's inflated.
2017 #if INCLUDE_RTM_OPT
2018     if (use_rtm) {
2019       Label L_regular_inflated_unlock;
2020       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2021       movptr(boxReg, Address(tmpReg, owner_offset));
2022       testptr(boxReg, boxReg);
2023       jccb(Assembler::notZero, L_regular_inflated_unlock);
2024       xend();
2025       jmpb_if_possible(DONE_LABEL);
2026       bind(L_regular_inflated_unlock);
2027     }
2028 #endif
2029 
2030     // Despite our balanced locking property we still check that m->_owner == Self
2031     // as java routines or native JNI code called by this thread might
2032     // have released the lock.
2033     // Refer to the comments in synchronizer.cpp for how we might encode extra
2034     // state in _succ so we can avoid fetching EntryList|cxq.
2035     //
2036     // I'd like to add more cases in fast_lock() and fast_unlock() --
2037     // such as recursive enter and exit -- but we have to be wary of
2038     // I$ bloat, T$ effects and BP$ effects.
2039     //
2040     // If there's no contention try a 1-0 exit.  That is, exit without
2041     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2042     // we detect and recover from the race that the 1-0 exit admits.
2043     //
2044     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2045     // before it STs null into _owner, releasing the lock.  Updates
2046     // to data protected by the critical section must be visible before
2047     // we drop the lock (and thus before any other thread could acquire
2048     // the lock and observe the fields protected by the lock).
2049     // IA32's memory-model is SPO, so STs are ordered with respect to
2050     // each other and there's no need for an explicit barrier (fence).
2051     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2052 #ifndef _LP64
2053     get_thread (boxReg);
2054     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2055       // prefetchw [ebx + Offset(_owner)-2]
2056       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2057     }
2058 
2059     // Note that we could employ various encoding schemes to reduce
2060     // the number of loads below (currently 4) to just 2 or 3.
2061     // Refer to the comments in synchronizer.cpp.
2062     // In practice the chain of fetches doesn't seem to impact performance, however.
2063     xorptr(boxReg, boxReg);
2064     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2065        // Attempt to reduce branch density - AMD's branch predictor.
2066        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2067        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2068        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2069        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2070        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2071        jmpb_if_possible(DONE_LABEL);
2072     } else {
2073        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2074        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2075        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2076        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2077        jccb  (Assembler::notZero, CheckSucc);
2078        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2079        jmpb_if_possible(DONE_LABEL);
2080     }
2081 
2082     // The Following code fragment (EmitSync & 65536) improves the performance of
2083     // contended applications and contended synchronization microbenchmarks.
2084     // Unfortunately the emission of the code - even though not executed - causes regressions
2085     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2086     // with an equal number of never-executed NOPs results in the same regression.
2087     // We leave it off by default.
2088 
2089     if ((EmitSync & 65536) != 0) {
2090        Label LSuccess, LGoSlowPath ;
2091 
2092        bind  (CheckSucc);
2093 
2094        // Optional pre-test ... it's safe to elide this
2095        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2096        jccb(Assembler::zero, LGoSlowPath);
2097 
2098        // We have a classic Dekker-style idiom:
2099        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2100        // There are a number of ways to implement the barrier:
2101        // (1) lock:andl &m->_owner, 0
2102        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2103        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2104        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2105        // (2) If supported, an explicit MFENCE is appealing.
2106        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2107        //     particularly if the write-buffer is full as might be the case if
2108        //     if stores closely precede the fence or fence-equivalent instruction.
2109        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2110        //     as the situation has changed with Nehalem and Shanghai.
2111        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2112        //     The $lines underlying the top-of-stack should be in M-state.
2113        //     The locked add instruction is serializing, of course.
2114        // (4) Use xchg, which is serializing
2115        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2116        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2117        //     The integer condition codes will tell us if succ was 0.
2118        //     Since _succ and _owner should reside in the same $line and
2119        //     we just stored into _owner, it's likely that the $line
2120        //     remains in M-state for the lock:orl.
2121        //
2122        // We currently use (3), although it's likely that switching to (2)
2123        // is correct for the future.
2124 
2125        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2126        if (os::is_MP()) {
2127          lock(); addptr(Address(rsp, 0), 0);
2128        }
2129        // Ratify _succ remains non-null
2130        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2131        jccb  (Assembler::notZero, LSuccess);
2132 
2133        xorptr(boxReg, boxReg);                  // box is really EAX
2134        if (os::is_MP()) { lock(); }
2135        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2136        // There's no successor so we tried to regrab the lock with the
2137        // placeholder value. If that didn't work, then another thread
2138        // grabbed the lock so we're done (and exit was a success).
2139        jccb  (Assembler::notEqual, LSuccess);
2140        // Since we're low on registers we installed rsp as a placeholding in _owner.
2141        // Now install Self over rsp.  This is safe as we're transitioning from
2142        // non-null to non=null
2143        get_thread (boxReg);
2144        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2145        // Intentional fall-through into LGoSlowPath ...
2146 
2147        bind  (LGoSlowPath);
2148        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2149        jmpb_if_possible(DONE_LABEL);
2150 
2151        bind  (LSuccess);
2152        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2153        jmpb_if_possible(DONE_LABEL);
2154     }
2155 
2156     bind (Stacked);
2157     // It's not inflated and it's not recursively stack-locked and it's not biased.
2158     // It must be stack-locked.
2159     // Try to reset the header to displaced header.
2160     // The "box" value on the stack is stable, so we can reload
2161     // and be assured we observe the same value as above.
2162     movptr(tmpReg, Address(boxReg, 0));
2163     if (os::is_MP()) {
2164       lock();
2165     }
2166     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2167     // Intention fall-thru into DONE_LABEL
2168 
2169     // DONE_LABEL is a hot target - we'd really like to place it at the
2170     // start of cache line by padding with NOPs.
2171     // See the AMD and Intel software optimization manuals for the
2172     // most efficient "long" NOP encodings.
2173     // Unfortunately none of our alignment mechanisms suffice.
2174     if ((EmitSync & 65536) == 0) {
2175        bind (CheckSucc);
2176     }
2177 #else // _LP64
2178     // It's inflated
2179     if (EmitSync & 1024) {
2180       // Emit code to check that _owner == Self
2181       // We could fold the _owner test into subsequent code more efficiently
2182       // than using a stand-alone check, but since _owner checking is off by
2183       // default we don't bother. We also might consider predicating the
2184       // _owner==Self check on Xcheck:jni or running on a debug build.
2185       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2186       xorptr(boxReg, r15_thread);
2187     } else {
2188       xorptr(boxReg, boxReg);
2189     }
2190     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2191     jccb_if_possible(Assembler::notZero, DONE_LABEL);
2192     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2193     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2194     jccb  (Assembler::notZero, CheckSucc);
2195     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2196     jmpb_if_possible(DONE_LABEL);
2197 
2198     if ((EmitSync & 65536) == 0) {
2199       // Try to avoid passing control into the slow_path ...
2200       Label LSuccess, LGoSlowPath ;
2201       bind  (CheckSucc);
2202 
2203       // The following optional optimization can be elided if necessary
2204       // Effectively: if (succ == null) goto SlowPath
2205       // The code reduces the window for a race, however,
2206       // and thus benefits performance.
2207       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2208       jccb  (Assembler::zero, LGoSlowPath);
2209 
2210       xorptr(boxReg, boxReg);
2211       if ((EmitSync & 16) && os::is_MP()) {
2212         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2213       } else {
2214         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2215         if (os::is_MP()) {
2216           // Memory barrier/fence
2217           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2218           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2219           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2220           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2221           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2222           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2223           lock(); addl(Address(rsp, 0), 0);
2224         }
2225       }
2226       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2227       jccb  (Assembler::notZero, LSuccess);
2228 
2229       // Rare inopportune interleaving - race.
2230       // The successor vanished in the small window above.
2231       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2232       // We need to ensure progress and succession.
2233       // Try to reacquire the lock.
2234       // If that fails then the new owner is responsible for succession and this
2235       // thread needs to take no further action and can exit via the fast path (success).
2236       // If the re-acquire succeeds then pass control into the slow path.
2237       // As implemented, this latter mode is horrible because we generated more
2238       // coherence traffic on the lock *and* artifically extended the critical section
2239       // length while by virtue of passing control into the slow path.
2240 
2241       // box is really RAX -- the following CMPXCHG depends on that binding
2242       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2243       if (os::is_MP()) { lock(); }
2244       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2245       // There's no successor so we tried to regrab the lock.
2246       // If that didn't work, then another thread grabbed the
2247       // lock so we're done (and exit was a success).
2248       jccb  (Assembler::notEqual, LSuccess);
2249       // Intentional fall-through into slow-path
2250 
2251       bind  (LGoSlowPath);
2252       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2253       jmpb_if_possible(DONE_LABEL);
2254 
2255       bind  (LSuccess);
2256       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2257       jmpb_if_possible  (DONE_LABEL);
2258     }
2259 
2260     bind  (Stacked);
2261     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2262     if (os::is_MP()) { lock(); }
2263     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2264 
2265     if (EmitSync & 65536) {
2266        bind (CheckSucc);
2267     }
2268 #endif
2269     bind(DONE_LABEL);
2270   }
2271 }
2272 #endif // COMPILER2
2273 
2274 void MacroAssembler::c2bool(Register x) {
2275   // implements x == 0 ? 0 : 1
2276   // note: must only look at least-significant byte of x
2277   //       since C-style booleans are stored in one byte
2278   //       only! (was bug)
2279   andl(x, 0xFF);
2280   setb(Assembler::notZero, x);
2281 }
2282 
2283 // Wouldn't need if AddressLiteral version had new name
2284 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2285   Assembler::call(L, rtype);
2286 }
2287 
2288 void MacroAssembler::call(Register entry) {
2289   Assembler::call(entry);
2290 }
2291 
2292 void MacroAssembler::call(AddressLiteral entry) {
2293   if (reachable(entry)) {
2294     Assembler::call_literal(entry.target(), entry.rspec());
2295   } else {
2296     lea(rscratch1, entry);
2297     Assembler::call(rscratch1);
2298   }
2299 }
2300 
2301 void MacroAssembler::ic_call(address entry, jint method_index) {
2302   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2303   movptr(rax, (intptr_t)Universe::non_oop_word());
2304   call(AddressLiteral(entry, rh));
2305 }
2306 
2307 // Implementation of call_VM versions
2308 
2309 void MacroAssembler::call_VM(Register oop_result,
2310                              address entry_point,
2311                              bool check_exceptions) {
2312   Label C, E;
2313   call(C, relocInfo::none);
2314   jmp(E);
2315 
2316   bind(C);
2317   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2318   ret(0);
2319 
2320   bind(E);
2321 }
2322 
2323 void MacroAssembler::call_VM(Register oop_result,
2324                              address entry_point,
2325                              Register arg_1,
2326                              bool check_exceptions) {
2327   Label C, E;
2328   call(C, relocInfo::none);
2329   jmp(E);
2330 
2331   bind(C);
2332   pass_arg1(this, arg_1);
2333   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2334   ret(0);
2335 
2336   bind(E);
2337 }
2338 
2339 void MacroAssembler::call_VM(Register oop_result,
2340                              address entry_point,
2341                              Register arg_1,
2342                              Register arg_2,
2343                              bool check_exceptions) {
2344   Label C, E;
2345   call(C, relocInfo::none);
2346   jmp(E);
2347 
2348   bind(C);
2349 
2350   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2351 
2352   pass_arg2(this, arg_2);
2353   pass_arg1(this, arg_1);
2354   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2355   ret(0);
2356 
2357   bind(E);
2358 }
2359 
2360 void MacroAssembler::call_VM(Register oop_result,
2361                              address entry_point,
2362                              Register arg_1,
2363                              Register arg_2,
2364                              Register arg_3,
2365                              bool check_exceptions) {
2366   Label C, E;
2367   call(C, relocInfo::none);
2368   jmp(E);
2369 
2370   bind(C);
2371 
2372   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2373   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2374   pass_arg3(this, arg_3);
2375 
2376   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2377   pass_arg2(this, arg_2);
2378 
2379   pass_arg1(this, arg_1);
2380   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2381   ret(0);
2382 
2383   bind(E);
2384 }
2385 
2386 void MacroAssembler::call_VM(Register oop_result,
2387                              Register last_java_sp,
2388                              address entry_point,
2389                              int number_of_arguments,
2390                              bool check_exceptions) {
2391   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2392   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2393 }
2394 
2395 void MacroAssembler::call_VM(Register oop_result,
2396                              Register last_java_sp,
2397                              address entry_point,
2398                              Register arg_1,
2399                              bool check_exceptions) {
2400   pass_arg1(this, arg_1);
2401   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2402 }
2403 
2404 void MacroAssembler::call_VM(Register oop_result,
2405                              Register last_java_sp,
2406                              address entry_point,
2407                              Register arg_1,
2408                              Register arg_2,
2409                              bool check_exceptions) {
2410 
2411   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2412   pass_arg2(this, arg_2);
2413   pass_arg1(this, arg_1);
2414   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2415 }
2416 
2417 void MacroAssembler::call_VM(Register oop_result,
2418                              Register last_java_sp,
2419                              address entry_point,
2420                              Register arg_1,
2421                              Register arg_2,
2422                              Register arg_3,
2423                              bool check_exceptions) {
2424   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2425   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2426   pass_arg3(this, arg_3);
2427   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2428   pass_arg2(this, arg_2);
2429   pass_arg1(this, arg_1);
2430   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2431 }
2432 
2433 void MacroAssembler::super_call_VM(Register oop_result,
2434                                    Register last_java_sp,
2435                                    address entry_point,
2436                                    int number_of_arguments,
2437                                    bool check_exceptions) {
2438   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2439   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2440 }
2441 
2442 void MacroAssembler::super_call_VM(Register oop_result,
2443                                    Register last_java_sp,
2444                                    address entry_point,
2445                                    Register arg_1,
2446                                    bool check_exceptions) {
2447   pass_arg1(this, arg_1);
2448   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2449 }
2450 
2451 void MacroAssembler::super_call_VM(Register oop_result,
2452                                    Register last_java_sp,
2453                                    address entry_point,
2454                                    Register arg_1,
2455                                    Register arg_2,
2456                                    bool check_exceptions) {
2457 
2458   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2459   pass_arg2(this, arg_2);
2460   pass_arg1(this, arg_1);
2461   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2462 }
2463 
2464 void MacroAssembler::super_call_VM(Register oop_result,
2465                                    Register last_java_sp,
2466                                    address entry_point,
2467                                    Register arg_1,
2468                                    Register arg_2,
2469                                    Register arg_3,
2470                                    bool check_exceptions) {
2471   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2472   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2473   pass_arg3(this, arg_3);
2474   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2475   pass_arg2(this, arg_2);
2476   pass_arg1(this, arg_1);
2477   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2478 }
2479 
2480 void MacroAssembler::call_VM_base(Register oop_result,
2481                                   Register java_thread,
2482                                   Register last_java_sp,
2483                                   address  entry_point,
2484                                   int      number_of_arguments,
2485                                   bool     check_exceptions) {
2486   // determine java_thread register
2487   if (!java_thread->is_valid()) {
2488 #ifdef _LP64
2489     java_thread = r15_thread;
2490 #else
2491     java_thread = rdi;
2492     get_thread(java_thread);
2493 #endif // LP64
2494   }
2495   // determine last_java_sp register
2496   if (!last_java_sp->is_valid()) {
2497     last_java_sp = rsp;
2498   }
2499   // debugging support
2500   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2501   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2502 #ifdef ASSERT
2503   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2504   // r12 is the heapbase.
2505   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2506 #endif // ASSERT
2507 
2508   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2509   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2510 
2511   // push java thread (becomes first argument of C function)
2512 
2513   NOT_LP64(push(java_thread); number_of_arguments++);
2514   LP64_ONLY(mov(c_rarg0, r15_thread));
2515 
2516   // set last Java frame before call
2517   assert(last_java_sp != rbp, "can't use ebp/rbp");
2518 
2519   // Only interpreter should have to set fp
2520   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2521 
2522   // do the call, remove parameters
2523   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2524 
2525   // restore the thread (cannot use the pushed argument since arguments
2526   // may be overwritten by C code generated by an optimizing compiler);
2527   // however can use the register value directly if it is callee saved.
2528   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2529     // rdi & rsi (also r15) are callee saved -> nothing to do
2530 #ifdef ASSERT
2531     guarantee(java_thread != rax, "change this code");
2532     push(rax);
2533     { Label L;
2534       get_thread(rax);
2535       cmpptr(java_thread, rax);
2536       jcc(Assembler::equal, L);
2537       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2538       bind(L);
2539     }
2540     pop(rax);
2541 #endif
2542   } else {
2543     get_thread(java_thread);
2544   }
2545   // reset last Java frame
2546   // Only interpreter should have to clear fp
2547   reset_last_Java_frame(java_thread, true);
2548 
2549    // C++ interp handles this in the interpreter
2550   check_and_handle_popframe(java_thread);
2551   check_and_handle_earlyret(java_thread);
2552 
2553   if (check_exceptions) {
2554     // check for pending exceptions (java_thread is set upon return)
2555     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2556 #ifndef _LP64
2557     jump_cc(Assembler::notEqual,
2558             RuntimeAddress(StubRoutines::forward_exception_entry()));
2559 #else
2560     // This used to conditionally jump to forward_exception however it is
2561     // possible if we relocate that the branch will not reach. So we must jump
2562     // around so we can always reach
2563 
2564     Label ok;
2565     jcc(Assembler::equal, ok);
2566     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2567     bind(ok);
2568 #endif // LP64
2569   }
2570 
2571   // get oop result if there is one and reset the value in the thread
2572   if (oop_result->is_valid()) {
2573     get_vm_result(oop_result, java_thread);
2574   }
2575 }
2576 
2577 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2578 
2579   // Calculate the value for last_Java_sp
2580   // somewhat subtle. call_VM does an intermediate call
2581   // which places a return address on the stack just under the
2582   // stack pointer as the user finsihed with it. This allows
2583   // use to retrieve last_Java_pc from last_Java_sp[-1].
2584   // On 32bit we then have to push additional args on the stack to accomplish
2585   // the actual requested call. On 64bit call_VM only can use register args
2586   // so the only extra space is the return address that call_VM created.
2587   // This hopefully explains the calculations here.
2588 
2589 #ifdef _LP64
2590   // We've pushed one address, correct last_Java_sp
2591   lea(rax, Address(rsp, wordSize));
2592 #else
2593   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2594 #endif // LP64
2595 
2596   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2597 
2598 }
2599 
2600 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2601 void MacroAssembler::call_VM_leaf0(address entry_point) {
2602   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2603 }
2604 
2605 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2606   call_VM_leaf_base(entry_point, number_of_arguments);
2607 }
2608 
2609 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2610   pass_arg0(this, arg_0);
2611   call_VM_leaf(entry_point, 1);
2612 }
2613 
2614 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2615 
2616   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2617   pass_arg1(this, arg_1);
2618   pass_arg0(this, arg_0);
2619   call_VM_leaf(entry_point, 2);
2620 }
2621 
2622 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2623   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2624   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2625   pass_arg2(this, arg_2);
2626   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2627   pass_arg1(this, arg_1);
2628   pass_arg0(this, arg_0);
2629   call_VM_leaf(entry_point, 3);
2630 }
2631 
2632 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2633   pass_arg0(this, arg_0);
2634   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2635 }
2636 
2637 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2638 
2639   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2640   pass_arg1(this, arg_1);
2641   pass_arg0(this, arg_0);
2642   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2643 }
2644 
2645 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2646   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2647   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2648   pass_arg2(this, arg_2);
2649   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2650   pass_arg1(this, arg_1);
2651   pass_arg0(this, arg_0);
2652   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2653 }
2654 
2655 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2656   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2657   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2658   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2659   pass_arg3(this, arg_3);
2660   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2661   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2662   pass_arg2(this, arg_2);
2663   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2664   pass_arg1(this, arg_1);
2665   pass_arg0(this, arg_0);
2666   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2667 }
2668 
2669 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2670   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2671   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2672   verify_oop(oop_result, "broken oop in call_VM_base");
2673 }
2674 
2675 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2676   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2677   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2678 }
2679 
2680 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2681 }
2682 
2683 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2684 }
2685 
2686 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2687   if (reachable(src1)) {
2688     cmpl(as_Address(src1), imm);
2689   } else {
2690     lea(rscratch1, src1);
2691     cmpl(Address(rscratch1, 0), imm);
2692   }
2693 }
2694 
2695 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2696   assert(!src2.is_lval(), "use cmpptr");
2697   if (reachable(src2)) {
2698     cmpl(src1, as_Address(src2));
2699   } else {
2700     lea(rscratch1, src2);
2701     cmpl(src1, Address(rscratch1, 0));
2702   }
2703 }
2704 
2705 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2706   Assembler::cmpl(src1, imm);
2707 }
2708 
2709 void MacroAssembler::cmp32(Register src1, Address src2) {
2710   Assembler::cmpl(src1, src2);
2711 }
2712 
2713 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2714   ucomisd(opr1, opr2);
2715 
2716   Label L;
2717   if (unordered_is_less) {
2718     movl(dst, -1);
2719     jcc(Assembler::parity, L);
2720     jcc(Assembler::below , L);
2721     movl(dst, 0);
2722     jcc(Assembler::equal , L);
2723     increment(dst);
2724   } else { // unordered is greater
2725     movl(dst, 1);
2726     jcc(Assembler::parity, L);
2727     jcc(Assembler::above , L);
2728     movl(dst, 0);
2729     jcc(Assembler::equal , L);
2730     decrementl(dst);
2731   }
2732   bind(L);
2733 }
2734 
2735 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2736   ucomiss(opr1, opr2);
2737 
2738   Label L;
2739   if (unordered_is_less) {
2740     movl(dst, -1);
2741     jcc(Assembler::parity, L);
2742     jcc(Assembler::below , L);
2743     movl(dst, 0);
2744     jcc(Assembler::equal , L);
2745     increment(dst);
2746   } else { // unordered is greater
2747     movl(dst, 1);
2748     jcc(Assembler::parity, L);
2749     jcc(Assembler::above , L);
2750     movl(dst, 0);
2751     jcc(Assembler::equal , L);
2752     decrementl(dst);
2753   }
2754   bind(L);
2755 }
2756 
2757 
2758 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2759   if (reachable(src1)) {
2760     cmpb(as_Address(src1), imm);
2761   } else {
2762     lea(rscratch1, src1);
2763     cmpb(Address(rscratch1, 0), imm);
2764   }
2765 }
2766 
2767 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2768 #ifdef _LP64
2769   if (src2.is_lval()) {
2770     movptr(rscratch1, src2);
2771     Assembler::cmpq(src1, rscratch1);
2772   } else if (reachable(src2)) {
2773     cmpq(src1, as_Address(src2));
2774   } else {
2775     lea(rscratch1, src2);
2776     Assembler::cmpq(src1, Address(rscratch1, 0));
2777   }
2778 #else
2779   if (src2.is_lval()) {
2780     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2781   } else {
2782     cmpl(src1, as_Address(src2));
2783   }
2784 #endif // _LP64
2785 }
2786 
2787 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2788   assert(src2.is_lval(), "not a mem-mem compare");
2789 #ifdef _LP64
2790   // moves src2's literal address
2791   movptr(rscratch1, src2);
2792   Assembler::cmpq(src1, rscratch1);
2793 #else
2794   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2795 #endif // _LP64
2796 }
2797 
2798 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2799   if (reachable(adr)) {
2800     if (os::is_MP())
2801       lock();
2802     cmpxchgptr(reg, as_Address(adr));
2803   } else {
2804     lea(rscratch1, adr);
2805     if (os::is_MP())
2806       lock();
2807     cmpxchgptr(reg, Address(rscratch1, 0));
2808   }
2809 }
2810 
2811 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2812   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2813 }
2814 
2815 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2816   if (reachable(src)) {
2817     Assembler::comisd(dst, as_Address(src));
2818   } else {
2819     lea(rscratch1, src);
2820     Assembler::comisd(dst, Address(rscratch1, 0));
2821   }
2822 }
2823 
2824 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2825   if (reachable(src)) {
2826     Assembler::comiss(dst, as_Address(src));
2827   } else {
2828     lea(rscratch1, src);
2829     Assembler::comiss(dst, Address(rscratch1, 0));
2830   }
2831 }
2832 
2833 
2834 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2835   Condition negated_cond = negate_condition(cond);
2836   Label L;
2837   jcc(negated_cond, L);
2838   pushf(); // Preserve flags
2839   atomic_incl(counter_addr);
2840   popf();
2841   bind(L);
2842 }
2843 
2844 int MacroAssembler::corrected_idivl(Register reg) {
2845   // Full implementation of Java idiv and irem; checks for
2846   // special case as described in JVM spec., p.243 & p.271.
2847   // The function returns the (pc) offset of the idivl
2848   // instruction - may be needed for implicit exceptions.
2849   //
2850   //         normal case                           special case
2851   //
2852   // input : rax,: dividend                         min_int
2853   //         reg: divisor   (may not be rax,/rdx)   -1
2854   //
2855   // output: rax,: quotient  (= rax, idiv reg)       min_int
2856   //         rdx: remainder (= rax, irem reg)       0
2857   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2858   const int min_int = 0x80000000;
2859   Label normal_case, special_case;
2860 
2861   // check for special case
2862   cmpl(rax, min_int);
2863   jcc(Assembler::notEqual, normal_case);
2864   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2865   cmpl(reg, -1);
2866   jcc(Assembler::equal, special_case);
2867 
2868   // handle normal case
2869   bind(normal_case);
2870   cdql();
2871   int idivl_offset = offset();
2872   idivl(reg);
2873 
2874   // normal and special case exit
2875   bind(special_case);
2876 
2877   return idivl_offset;
2878 }
2879 
2880 
2881 
2882 void MacroAssembler::decrementl(Register reg, int value) {
2883   if (value == min_jint) {subl(reg, value) ; return; }
2884   if (value <  0) { incrementl(reg, -value); return; }
2885   if (value == 0) {                        ; return; }
2886   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2887   /* else */      { subl(reg, value)       ; return; }
2888 }
2889 
2890 void MacroAssembler::decrementl(Address dst, int value) {
2891   if (value == min_jint) {subl(dst, value) ; return; }
2892   if (value <  0) { incrementl(dst, -value); return; }
2893   if (value == 0) {                        ; return; }
2894   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2895   /* else */      { subl(dst, value)       ; return; }
2896 }
2897 
2898 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2899   assert (shift_value > 0, "illegal shift value");
2900   Label _is_positive;
2901   testl (reg, reg);
2902   jcc (Assembler::positive, _is_positive);
2903   int offset = (1 << shift_value) - 1 ;
2904 
2905   if (offset == 1) {
2906     incrementl(reg);
2907   } else {
2908     addl(reg, offset);
2909   }
2910 
2911   bind (_is_positive);
2912   sarl(reg, shift_value);
2913 }
2914 
2915 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2916   if (reachable(src)) {
2917     Assembler::divsd(dst, as_Address(src));
2918   } else {
2919     lea(rscratch1, src);
2920     Assembler::divsd(dst, Address(rscratch1, 0));
2921   }
2922 }
2923 
2924 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2925   if (reachable(src)) {
2926     Assembler::divss(dst, as_Address(src));
2927   } else {
2928     lea(rscratch1, src);
2929     Assembler::divss(dst, Address(rscratch1, 0));
2930   }
2931 }
2932 
2933 // !defined(COMPILER2) is because of stupid core builds
2934 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2935 void MacroAssembler::empty_FPU_stack() {
2936   if (VM_Version::supports_mmx()) {
2937     emms();
2938   } else {
2939     for (int i = 8; i-- > 0; ) ffree(i);
2940   }
2941 }
2942 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2943 
2944 
2945 // Defines obj, preserves var_size_in_bytes
2946 void MacroAssembler::eden_allocate(Register obj,
2947                                    Register var_size_in_bytes,
2948                                    int con_size_in_bytes,
2949                                    Register t1,
2950                                    Label& slow_case) {
2951   assert(obj == rax, "obj must be in rax, for cmpxchg");
2952   assert_different_registers(obj, var_size_in_bytes, t1);
2953   if (!Universe::heap()->supports_inline_contig_alloc()) {
2954     jmp(slow_case);
2955   } else {
2956     Register end = t1;
2957     Label retry;
2958     bind(retry);
2959     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2960     movptr(obj, heap_top);
2961     if (var_size_in_bytes == noreg) {
2962       lea(end, Address(obj, con_size_in_bytes));
2963     } else {
2964       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2965     }
2966     // if end < obj then we wrapped around => object too long => slow case
2967     cmpptr(end, obj);
2968     jcc(Assembler::below, slow_case);
2969     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2970     jcc(Assembler::above, slow_case);
2971     // Compare obj with the top addr, and if still equal, store the new top addr in
2972     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2973     // it otherwise. Use lock prefix for atomicity on MPs.
2974     locked_cmpxchgptr(end, heap_top);
2975     jcc(Assembler::notEqual, retry);
2976   }
2977 }
2978 
2979 void MacroAssembler::enter() {
2980   push(rbp);
2981   mov(rbp, rsp);
2982 }
2983 
2984 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2985 void MacroAssembler::fat_nop() {
2986   if (UseAddressNop) {
2987     addr_nop_5();
2988   } else {
2989     emit_int8(0x26); // es:
2990     emit_int8(0x2e); // cs:
2991     emit_int8(0x64); // fs:
2992     emit_int8(0x65); // gs:
2993     emit_int8((unsigned char)0x90);
2994   }
2995 }
2996 
2997 void MacroAssembler::fcmp(Register tmp) {
2998   fcmp(tmp, 1, true, true);
2999 }
3000 
3001 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3002   assert(!pop_right || pop_left, "usage error");
3003   if (VM_Version::supports_cmov()) {
3004     assert(tmp == noreg, "unneeded temp");
3005     if (pop_left) {
3006       fucomip(index);
3007     } else {
3008       fucomi(index);
3009     }
3010     if (pop_right) {
3011       fpop();
3012     }
3013   } else {
3014     assert(tmp != noreg, "need temp");
3015     if (pop_left) {
3016       if (pop_right) {
3017         fcompp();
3018       } else {
3019         fcomp(index);
3020       }
3021     } else {
3022       fcom(index);
3023     }
3024     // convert FPU condition into eflags condition via rax,
3025     save_rax(tmp);
3026     fwait(); fnstsw_ax();
3027     sahf();
3028     restore_rax(tmp);
3029   }
3030   // condition codes set as follows:
3031   //
3032   // CF (corresponds to C0) if x < y
3033   // PF (corresponds to C2) if unordered
3034   // ZF (corresponds to C3) if x = y
3035 }
3036 
3037 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3038   fcmp2int(dst, unordered_is_less, 1, true, true);
3039 }
3040 
3041 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3042   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3043   Label L;
3044   if (unordered_is_less) {
3045     movl(dst, -1);
3046     jcc(Assembler::parity, L);
3047     jcc(Assembler::below , L);
3048     movl(dst, 0);
3049     jcc(Assembler::equal , L);
3050     increment(dst);
3051   } else { // unordered is greater
3052     movl(dst, 1);
3053     jcc(Assembler::parity, L);
3054     jcc(Assembler::above , L);
3055     movl(dst, 0);
3056     jcc(Assembler::equal , L);
3057     decrementl(dst);
3058   }
3059   bind(L);
3060 }
3061 
3062 void MacroAssembler::fld_d(AddressLiteral src) {
3063   fld_d(as_Address(src));
3064 }
3065 
3066 void MacroAssembler::fld_s(AddressLiteral src) {
3067   fld_s(as_Address(src));
3068 }
3069 
3070 void MacroAssembler::fld_x(AddressLiteral src) {
3071   Assembler::fld_x(as_Address(src));
3072 }
3073 
3074 void MacroAssembler::fldcw(AddressLiteral src) {
3075   Assembler::fldcw(as_Address(src));
3076 }
3077 
3078 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3079   if (reachable(src)) {
3080     Assembler::mulpd(dst, as_Address(src));
3081   } else {
3082     lea(rscratch1, src);
3083     Assembler::mulpd(dst, Address(rscratch1, 0));
3084   }
3085 }
3086 
3087 void MacroAssembler::increase_precision() {
3088   subptr(rsp, BytesPerWord);
3089   fnstcw(Address(rsp, 0));
3090   movl(rax, Address(rsp, 0));
3091   orl(rax, 0x300);
3092   push(rax);
3093   fldcw(Address(rsp, 0));
3094   pop(rax);
3095 }
3096 
3097 void MacroAssembler::restore_precision() {
3098   fldcw(Address(rsp, 0));
3099   addptr(rsp, BytesPerWord);
3100 }
3101 
3102 void MacroAssembler::fpop() {
3103   ffree();
3104   fincstp();
3105 }
3106 
3107 void MacroAssembler::load_float(Address src) {
3108   if (UseSSE >= 1) {
3109     movflt(xmm0, src);
3110   } else {
3111     LP64_ONLY(ShouldNotReachHere());
3112     NOT_LP64(fld_s(src));
3113   }
3114 }
3115 
3116 void MacroAssembler::store_float(Address dst) {
3117   if (UseSSE >= 1) {
3118     movflt(dst, xmm0);
3119   } else {
3120     LP64_ONLY(ShouldNotReachHere());
3121     NOT_LP64(fstp_s(dst));
3122   }
3123 }
3124 
3125 void MacroAssembler::load_double(Address src) {
3126   if (UseSSE >= 2) {
3127     movdbl(xmm0, src);
3128   } else {
3129     LP64_ONLY(ShouldNotReachHere());
3130     NOT_LP64(fld_d(src));
3131   }
3132 }
3133 
3134 void MacroAssembler::store_double(Address dst) {
3135   if (UseSSE >= 2) {
3136     movdbl(dst, xmm0);
3137   } else {
3138     LP64_ONLY(ShouldNotReachHere());
3139     NOT_LP64(fstp_d(dst));
3140   }
3141 }
3142 
3143 void MacroAssembler::fremr(Register tmp) {
3144   save_rax(tmp);
3145   { Label L;
3146     bind(L);
3147     fprem();
3148     fwait(); fnstsw_ax();
3149 #ifdef _LP64
3150     testl(rax, 0x400);
3151     jcc(Assembler::notEqual, L);
3152 #else
3153     sahf();
3154     jcc(Assembler::parity, L);
3155 #endif // _LP64
3156   }
3157   restore_rax(tmp);
3158   // Result is in ST0.
3159   // Note: fxch & fpop to get rid of ST1
3160   // (otherwise FPU stack could overflow eventually)
3161   fxch(1);
3162   fpop();
3163 }
3164 
3165 // dst = c = a * b + c
3166 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3167   Assembler::vfmadd231sd(c, a, b);
3168   if (dst != c) {
3169     movdbl(dst, c);
3170   }
3171 }
3172 
3173 // dst = c = a * b + c
3174 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3175   Assembler::vfmadd231ss(c, a, b);
3176   if (dst != c) {
3177     movflt(dst, c);
3178   }
3179 }
3180 
3181 // dst = c = a * b + c
3182 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3183   Assembler::vfmadd231pd(c, a, b, vector_len);
3184   if (dst != c) {
3185     vmovdqu(dst, c);
3186   }
3187 }
3188 
3189 // dst = c = a * b + c
3190 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3191   Assembler::vfmadd231ps(c, a, b, vector_len);
3192   if (dst != c) {
3193     vmovdqu(dst, c);
3194   }
3195 }
3196 
3197 // dst = c = a * b + c
3198 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3199   Assembler::vfmadd231pd(c, a, b, vector_len);
3200   if (dst != c) {
3201     vmovdqu(dst, c);
3202   }
3203 }
3204 
3205 // dst = c = a * b + c
3206 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3207   Assembler::vfmadd231ps(c, a, b, vector_len);
3208   if (dst != c) {
3209     vmovdqu(dst, c);
3210   }
3211 }
3212 
3213 void MacroAssembler::incrementl(AddressLiteral dst) {
3214   if (reachable(dst)) {
3215     incrementl(as_Address(dst));
3216   } else {
3217     lea(rscratch1, dst);
3218     incrementl(Address(rscratch1, 0));
3219   }
3220 }
3221 
3222 void MacroAssembler::incrementl(ArrayAddress dst) {
3223   incrementl(as_Address(dst));
3224 }
3225 
3226 void MacroAssembler::incrementl(Register reg, int value) {
3227   if (value == min_jint) {addl(reg, value) ; return; }
3228   if (value <  0) { decrementl(reg, -value); return; }
3229   if (value == 0) {                        ; return; }
3230   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3231   /* else */      { addl(reg, value)       ; return; }
3232 }
3233 
3234 void MacroAssembler::incrementl(Address dst, int value) {
3235   if (value == min_jint) {addl(dst, value) ; return; }
3236   if (value <  0) { decrementl(dst, -value); return; }
3237   if (value == 0) {                        ; return; }
3238   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3239   /* else */      { addl(dst, value)       ; return; }
3240 }
3241 
3242 void MacroAssembler::jump(AddressLiteral dst) {
3243   if (reachable(dst)) {
3244     jmp_literal(dst.target(), dst.rspec());
3245   } else {
3246     lea(rscratch1, dst);
3247     jmp(rscratch1);
3248   }
3249 }
3250 
3251 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3252   if (reachable(dst)) {
3253     InstructionMark im(this);
3254     relocate(dst.reloc());
3255     const int short_size = 2;
3256     const int long_size = 6;
3257     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3258     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3259       // 0111 tttn #8-bit disp
3260       emit_int8(0x70 | cc);
3261       emit_int8((offs - short_size) & 0xFF);
3262     } else {
3263       // 0000 1111 1000 tttn #32-bit disp
3264       emit_int8(0x0F);
3265       emit_int8((unsigned char)(0x80 | cc));
3266       emit_int32(offs - long_size);
3267     }
3268   } else {
3269 #ifdef ASSERT
3270     warning("reversing conditional branch");
3271 #endif /* ASSERT */
3272     Label skip;
3273     jccb(reverse[cc], skip);
3274     lea(rscratch1, dst);
3275     Assembler::jmp(rscratch1);
3276     bind(skip);
3277   }
3278 }
3279 
3280 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3281   if (reachable(src)) {
3282     Assembler::ldmxcsr(as_Address(src));
3283   } else {
3284     lea(rscratch1, src);
3285     Assembler::ldmxcsr(Address(rscratch1, 0));
3286   }
3287 }
3288 
3289 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3290   int off;
3291   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3292     off = offset();
3293     movsbl(dst, src); // movsxb
3294   } else {
3295     off = load_unsigned_byte(dst, src);
3296     shll(dst, 24);
3297     sarl(dst, 24);
3298   }
3299   return off;
3300 }
3301 
3302 // Note: load_signed_short used to be called load_signed_word.
3303 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3304 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3305 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3306 int MacroAssembler::load_signed_short(Register dst, Address src) {
3307   int off;
3308   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3309     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3310     // version but this is what 64bit has always done. This seems to imply
3311     // that users are only using 32bits worth.
3312     off = offset();
3313     movswl(dst, src); // movsxw
3314   } else {
3315     off = load_unsigned_short(dst, src);
3316     shll(dst, 16);
3317     sarl(dst, 16);
3318   }
3319   return off;
3320 }
3321 
3322 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3323   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3324   // and "3.9 Partial Register Penalties", p. 22).
3325   int off;
3326   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3327     off = offset();
3328     movzbl(dst, src); // movzxb
3329   } else {
3330     xorl(dst, dst);
3331     off = offset();
3332     movb(dst, src);
3333   }
3334   return off;
3335 }
3336 
3337 // Note: load_unsigned_short used to be called load_unsigned_word.
3338 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3339   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3340   // and "3.9 Partial Register Penalties", p. 22).
3341   int off;
3342   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3343     off = offset();
3344     movzwl(dst, src); // movzxw
3345   } else {
3346     xorl(dst, dst);
3347     off = offset();
3348     movw(dst, src);
3349   }
3350   return off;
3351 }
3352 
3353 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3354   switch (size_in_bytes) {
3355 #ifndef _LP64
3356   case  8:
3357     assert(dst2 != noreg, "second dest register required");
3358     movl(dst,  src);
3359     movl(dst2, src.plus_disp(BytesPerInt));
3360     break;
3361 #else
3362   case  8:  movq(dst, src); break;
3363 #endif
3364   case  4:  movl(dst, src); break;
3365   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3366   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3367   default:  ShouldNotReachHere();
3368   }
3369 }
3370 
3371 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3372   switch (size_in_bytes) {
3373 #ifndef _LP64
3374   case  8:
3375     assert(src2 != noreg, "second source register required");
3376     movl(dst,                        src);
3377     movl(dst.plus_disp(BytesPerInt), src2);
3378     break;
3379 #else
3380   case  8:  movq(dst, src); break;
3381 #endif
3382   case  4:  movl(dst, src); break;
3383   case  2:  movw(dst, src); break;
3384   case  1:  movb(dst, src); break;
3385   default:  ShouldNotReachHere();
3386   }
3387 }
3388 
3389 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3390   if (reachable(dst)) {
3391     movl(as_Address(dst), src);
3392   } else {
3393     lea(rscratch1, dst);
3394     movl(Address(rscratch1, 0), src);
3395   }
3396 }
3397 
3398 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3399   if (reachable(src)) {
3400     movl(dst, as_Address(src));
3401   } else {
3402     lea(rscratch1, src);
3403     movl(dst, Address(rscratch1, 0));
3404   }
3405 }
3406 
3407 // C++ bool manipulation
3408 
3409 void MacroAssembler::movbool(Register dst, Address src) {
3410   if(sizeof(bool) == 1)
3411     movb(dst, src);
3412   else if(sizeof(bool) == 2)
3413     movw(dst, src);
3414   else if(sizeof(bool) == 4)
3415     movl(dst, src);
3416   else
3417     // unsupported
3418     ShouldNotReachHere();
3419 }
3420 
3421 void MacroAssembler::movbool(Address dst, bool boolconst) {
3422   if(sizeof(bool) == 1)
3423     movb(dst, (int) boolconst);
3424   else if(sizeof(bool) == 2)
3425     movw(dst, (int) boolconst);
3426   else if(sizeof(bool) == 4)
3427     movl(dst, (int) boolconst);
3428   else
3429     // unsupported
3430     ShouldNotReachHere();
3431 }
3432 
3433 void MacroAssembler::movbool(Address dst, Register src) {
3434   if(sizeof(bool) == 1)
3435     movb(dst, src);
3436   else if(sizeof(bool) == 2)
3437     movw(dst, src);
3438   else if(sizeof(bool) == 4)
3439     movl(dst, src);
3440   else
3441     // unsupported
3442     ShouldNotReachHere();
3443 }
3444 
3445 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3446   movb(as_Address(dst), src);
3447 }
3448 
3449 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3450   if (reachable(src)) {
3451     movdl(dst, as_Address(src));
3452   } else {
3453     lea(rscratch1, src);
3454     movdl(dst, Address(rscratch1, 0));
3455   }
3456 }
3457 
3458 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3459   if (reachable(src)) {
3460     movq(dst, as_Address(src));
3461   } else {
3462     lea(rscratch1, src);
3463     movq(dst, Address(rscratch1, 0));
3464   }
3465 }
3466 
3467 void MacroAssembler::setvectmask(Register dst, Register src) {
3468   Assembler::movl(dst, 1);
3469   Assembler::shlxl(dst, dst, src);
3470   Assembler::decl(dst);
3471   Assembler::kmovdl(k1, dst);
3472   Assembler::movl(dst, src);
3473 }
3474 
3475 void MacroAssembler::restorevectmask() {
3476   Assembler::knotwl(k1, k0);
3477 }
3478 
3479 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3480   if (reachable(src)) {
3481     if (UseXmmLoadAndClearUpper) {
3482       movsd (dst, as_Address(src));
3483     } else {
3484       movlpd(dst, as_Address(src));
3485     }
3486   } else {
3487     lea(rscratch1, src);
3488     if (UseXmmLoadAndClearUpper) {
3489       movsd (dst, Address(rscratch1, 0));
3490     } else {
3491       movlpd(dst, Address(rscratch1, 0));
3492     }
3493   }
3494 }
3495 
3496 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3497   if (reachable(src)) {
3498     movss(dst, as_Address(src));
3499   } else {
3500     lea(rscratch1, src);
3501     movss(dst, Address(rscratch1, 0));
3502   }
3503 }
3504 
3505 void MacroAssembler::movptr(Register dst, Register src) {
3506   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3507 }
3508 
3509 void MacroAssembler::movptr(Register dst, Address src) {
3510   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3511 }
3512 
3513 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3514 void MacroAssembler::movptr(Register dst, intptr_t src) {
3515   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3516 }
3517 
3518 void MacroAssembler::movptr(Address dst, Register src) {
3519   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3520 }
3521 
3522 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3523   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3524     Assembler::vextractf32x4(dst, src, 0);
3525   } else {
3526     Assembler::movdqu(dst, src);
3527   }
3528 }
3529 
3530 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3531   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3532     Assembler::vinsertf32x4(dst, dst, src, 0);
3533   } else {
3534     Assembler::movdqu(dst, src);
3535   }
3536 }
3537 
3538 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3539   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3540     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3541   } else {
3542     Assembler::movdqu(dst, src);
3543   }
3544 }
3545 
3546 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3547   if (reachable(src)) {
3548     movdqu(dst, as_Address(src));
3549   } else {
3550     lea(scratchReg, src);
3551     movdqu(dst, Address(scratchReg, 0));
3552   }
3553 }
3554 
3555 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3556   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3557     vextractf64x4_low(dst, src);
3558   } else {
3559     Assembler::vmovdqu(dst, src);
3560   }
3561 }
3562 
3563 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3564   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3565     vinsertf64x4_low(dst, src);
3566   } else {
3567     Assembler::vmovdqu(dst, src);
3568   }
3569 }
3570 
3571 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3572   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3573     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3574   }
3575   else {
3576     Assembler::vmovdqu(dst, src);
3577   }
3578 }
3579 
3580 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3581   if (reachable(src)) {
3582     vmovdqu(dst, as_Address(src));
3583   }
3584   else {
3585     lea(rscratch1, src);
3586     vmovdqu(dst, Address(rscratch1, 0));
3587   }
3588 }
3589 
3590 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3591   if (reachable(src)) {
3592     Assembler::movdqa(dst, as_Address(src));
3593   } else {
3594     lea(rscratch1, src);
3595     Assembler::movdqa(dst, Address(rscratch1, 0));
3596   }
3597 }
3598 
3599 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3600   if (reachable(src)) {
3601     Assembler::movsd(dst, as_Address(src));
3602   } else {
3603     lea(rscratch1, src);
3604     Assembler::movsd(dst, Address(rscratch1, 0));
3605   }
3606 }
3607 
3608 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3609   if (reachable(src)) {
3610     Assembler::movss(dst, as_Address(src));
3611   } else {
3612     lea(rscratch1, src);
3613     Assembler::movss(dst, Address(rscratch1, 0));
3614   }
3615 }
3616 
3617 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3618   if (reachable(src)) {
3619     Assembler::mulsd(dst, as_Address(src));
3620   } else {
3621     lea(rscratch1, src);
3622     Assembler::mulsd(dst, Address(rscratch1, 0));
3623   }
3624 }
3625 
3626 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3627   if (reachable(src)) {
3628     Assembler::mulss(dst, as_Address(src));
3629   } else {
3630     lea(rscratch1, src);
3631     Assembler::mulss(dst, Address(rscratch1, 0));
3632   }
3633 }
3634 
3635 void MacroAssembler::null_check(Register reg, int offset) {
3636   if (needs_explicit_null_check(offset)) {
3637     // provoke OS NULL exception if reg = NULL by
3638     // accessing M[reg] w/o changing any (non-CC) registers
3639     // NOTE: cmpl is plenty here to provoke a segv
3640     cmpptr(rax, Address(reg, 0));
3641     // Note: should probably use testl(rax, Address(reg, 0));
3642     //       may be shorter code (however, this version of
3643     //       testl needs to be implemented first)
3644   } else {
3645     // nothing to do, (later) access of M[reg + offset]
3646     // will provoke OS NULL exception if reg = NULL
3647   }
3648 }
3649 
3650 void MacroAssembler::os_breakpoint() {
3651   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3652   // (e.g., MSVC can't call ps() otherwise)
3653   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3654 }
3655 
3656 void MacroAssembler::unimplemented(const char* what) {
3657   char* b = new char[1024];
3658   jio_snprintf(b, 1024, "unimplemented: %s", what);
3659   stop(b);
3660 }
3661 
3662 #ifdef _LP64
3663 #define XSTATE_BV 0x200
3664 #endif
3665 
3666 void MacroAssembler::pop_CPU_state() {
3667   pop_FPU_state();
3668   pop_IU_state();
3669 }
3670 
3671 void MacroAssembler::pop_FPU_state() {
3672 #ifndef _LP64
3673   frstor(Address(rsp, 0));
3674 #else
3675   fxrstor(Address(rsp, 0));
3676 #endif
3677   addptr(rsp, FPUStateSizeInWords * wordSize);
3678 }
3679 
3680 void MacroAssembler::pop_IU_state() {
3681   popa();
3682   LP64_ONLY(addq(rsp, 8));
3683   popf();
3684 }
3685 
3686 // Save Integer and Float state
3687 // Warning: Stack must be 16 byte aligned (64bit)
3688 void MacroAssembler::push_CPU_state() {
3689   push_IU_state();
3690   push_FPU_state();
3691 }
3692 
3693 void MacroAssembler::push_FPU_state() {
3694   subptr(rsp, FPUStateSizeInWords * wordSize);
3695 #ifndef _LP64
3696   fnsave(Address(rsp, 0));
3697   fwait();
3698 #else
3699   fxsave(Address(rsp, 0));
3700 #endif // LP64
3701 }
3702 
3703 void MacroAssembler::push_IU_state() {
3704   // Push flags first because pusha kills them
3705   pushf();
3706   // Make sure rsp stays 16-byte aligned
3707   LP64_ONLY(subq(rsp, 8));
3708   pusha();
3709 }
3710 
3711 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3712   if (!java_thread->is_valid()) {
3713     java_thread = rdi;
3714     get_thread(java_thread);
3715   }
3716   // we must set sp to zero to clear frame
3717   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3718   if (clear_fp) {
3719     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3720   }
3721 
3722   // Always clear the pc because it could have been set by make_walkable()
3723   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3724 
3725   vzeroupper();
3726 }
3727 
3728 void MacroAssembler::restore_rax(Register tmp) {
3729   if (tmp == noreg) pop(rax);
3730   else if (tmp != rax) mov(rax, tmp);
3731 }
3732 
3733 void MacroAssembler::round_to(Register reg, int modulus) {
3734   addptr(reg, modulus - 1);
3735   andptr(reg, -modulus);
3736 }
3737 
3738 void MacroAssembler::save_rax(Register tmp) {
3739   if (tmp == noreg) push(rax);
3740   else if (tmp != rax) mov(tmp, rax);
3741 }
3742 
3743 // Write serialization page so VM thread can do a pseudo remote membar.
3744 // We use the current thread pointer to calculate a thread specific
3745 // offset to write to within the page. This minimizes bus traffic
3746 // due to cache line collision.
3747 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3748   movl(tmp, thread);
3749   shrl(tmp, os::get_serialize_page_shift_count());
3750   andl(tmp, (os::vm_page_size() - sizeof(int)));
3751 
3752   Address index(noreg, tmp, Address::times_1);
3753   ExternalAddress page(os::get_memory_serialize_page());
3754 
3755   // Size of store must match masking code above
3756   movl(as_Address(ArrayAddress(page, index)), tmp);
3757 }
3758 
3759 // Special Shenandoah CAS implementation that handles false negatives
3760 // due to concurrent evacuation.
3761 #ifndef _LP64
3762 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3763                               bool exchange,
3764                               Register tmp1, Register tmp2) {
3765   // Shenandoah has no 32-bit version for this.
3766   Unimplemented();
3767 }
3768 #else
3769 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3770                               bool exchange,
3771                               Register tmp1, Register tmp2) {
3772   assert(UseShenandoahGC, "Should only be used with Shenandoah");
3773   assert(ShenandoahCASBarrier, "Should only be used when CAS barrier is enabled");
3774   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
3775 
3776   Label retry, done;
3777 
3778   // Remember oldval for retry logic below
3779   if (UseCompressedOops) {
3780     movl(tmp1, oldval);
3781   } else {
3782     movptr(tmp1, oldval);
3783   }
3784 
3785   // Step 1. Try to CAS with given arguments. If successful, then we are done,
3786   // and can safely return.
3787   if (os::is_MP()) lock();
3788   if (UseCompressedOops) {
3789     cmpxchgl(newval, addr);
3790   } else {
3791     cmpxchgptr(newval, addr);
3792   }
3793   jcc(Assembler::equal, done, true);
3794 
3795   // Step 2. CAS had failed. This may be a false negative.
3796   //
3797   // The trouble comes when we compare the to-space pointer with the from-space
3798   // pointer to the same object. To resolve this, it will suffice to read both
3799   // oldval and the value from memory through the read barriers -- this will give
3800   // both to-space pointers. If they mismatch, then it was a legitimate failure.
3801   //
3802   if (UseCompressedOops) {
3803     decode_heap_oop(tmp1);
3804   }
3805   oopDesc::bs()->interpreter_read_barrier(this, tmp1);
3806 
3807   if (UseCompressedOops) {
3808     movl(tmp2, oldval);
3809     decode_heap_oop(tmp2);
3810   } else {
3811     movptr(tmp2, oldval);
3812   }
3813   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3814 
3815   cmpptr(tmp1, tmp2);
3816   jcc(Assembler::notEqual, done, true);
3817 
3818   // Step 3. Try to CAS again with resolved to-space pointers.
3819   //
3820   // Corner case: it may happen that somebody stored the from-space pointer
3821   // to memory while we were preparing for retry. Therefore, we can fail again
3822   // on retry, and so need to do this in loop, always re-reading the failure
3823   // witness through the read barrier.
3824   bind(retry);
3825   if (os::is_MP()) lock();
3826   if (UseCompressedOops) {
3827     cmpxchgl(newval, addr);
3828   } else {
3829     cmpxchgptr(newval, addr);
3830   }
3831   jcc(Assembler::equal, done, true);
3832 
3833   if (UseCompressedOops) {
3834     movl(tmp2, oldval);
3835     decode_heap_oop(tmp2);
3836   } else {
3837     movptr(tmp2, oldval);
3838   }
3839   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3840 
3841   cmpptr(tmp1, tmp2);
3842   jcc(Assembler::equal, retry, true);
3843 
3844   // Step 4. If we need a boolean result out of CAS, check the flag again,
3845   // and promote the result. Note that we handle the flag from both the CAS
3846   // itself and from the retry loop.
3847   bind(done);
3848   if (!exchange) {
3849     setb(Assembler::equal, res);
3850     movzbl(res, res);
3851   }
3852 }
3853 #endif
3854 
3855 // Calls to C land
3856 //
3857 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3858 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3859 // has to be reset to 0. This is required to allow proper stack traversal.
3860 void MacroAssembler::set_last_Java_frame(Register java_thread,
3861                                          Register last_java_sp,
3862                                          Register last_java_fp,
3863                                          address  last_java_pc) {
3864   vzeroupper();
3865   // determine java_thread register
3866   if (!java_thread->is_valid()) {
3867     java_thread = rdi;
3868     get_thread(java_thread);
3869   }
3870   // determine last_java_sp register
3871   if (!last_java_sp->is_valid()) {
3872     last_java_sp = rsp;
3873   }
3874 
3875   // last_java_fp is optional
3876 
3877   if (last_java_fp->is_valid()) {
3878     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3879   }
3880 
3881   // last_java_pc is optional
3882 
3883   if (last_java_pc != NULL) {
3884     lea(Address(java_thread,
3885                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3886         InternalAddress(last_java_pc));
3887 
3888   }
3889   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3890 }
3891 
3892 void MacroAssembler::shlptr(Register dst, int imm8) {
3893   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3894 }
3895 
3896 void MacroAssembler::shrptr(Register dst, int imm8) {
3897   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3898 }
3899 
3900 void MacroAssembler::sign_extend_byte(Register reg) {
3901   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3902     movsbl(reg, reg); // movsxb
3903   } else {
3904     shll(reg, 24);
3905     sarl(reg, 24);
3906   }
3907 }
3908 
3909 void MacroAssembler::sign_extend_short(Register reg) {
3910   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3911     movswl(reg, reg); // movsxw
3912   } else {
3913     shll(reg, 16);
3914     sarl(reg, 16);
3915   }
3916 }
3917 
3918 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3919   assert(reachable(src), "Address should be reachable");
3920   testl(dst, as_Address(src));
3921 }
3922 
3923 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3924   int dst_enc = dst->encoding();
3925   int src_enc = src->encoding();
3926   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3927     Assembler::pcmpeqb(dst, src);
3928   } else if ((dst_enc < 16) && (src_enc < 16)) {
3929     Assembler::pcmpeqb(dst, src);
3930   } else if (src_enc < 16) {
3931     subptr(rsp, 64);
3932     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3933     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3934     Assembler::pcmpeqb(xmm0, src);
3935     movdqu(dst, xmm0);
3936     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3937     addptr(rsp, 64);
3938   } else if (dst_enc < 16) {
3939     subptr(rsp, 64);
3940     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3941     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3942     Assembler::pcmpeqb(dst, xmm0);
3943     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3944     addptr(rsp, 64);
3945   } else {
3946     subptr(rsp, 64);
3947     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3948     subptr(rsp, 64);
3949     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3950     movdqu(xmm0, src);
3951     movdqu(xmm1, dst);
3952     Assembler::pcmpeqb(xmm1, xmm0);
3953     movdqu(dst, xmm1);
3954     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3955     addptr(rsp, 64);
3956     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3957     addptr(rsp, 64);
3958   }
3959 }
3960 
3961 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3962   int dst_enc = dst->encoding();
3963   int src_enc = src->encoding();
3964   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3965     Assembler::pcmpeqw(dst, src);
3966   } else if ((dst_enc < 16) && (src_enc < 16)) {
3967     Assembler::pcmpeqw(dst, src);
3968   } else if (src_enc < 16) {
3969     subptr(rsp, 64);
3970     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3971     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3972     Assembler::pcmpeqw(xmm0, src);
3973     movdqu(dst, xmm0);
3974     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3975     addptr(rsp, 64);
3976   } else if (dst_enc < 16) {
3977     subptr(rsp, 64);
3978     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3979     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3980     Assembler::pcmpeqw(dst, xmm0);
3981     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3982     addptr(rsp, 64);
3983   } else {
3984     subptr(rsp, 64);
3985     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3988     movdqu(xmm0, src);
3989     movdqu(xmm1, dst);
3990     Assembler::pcmpeqw(xmm1, xmm0);
3991     movdqu(dst, xmm1);
3992     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3993     addptr(rsp, 64);
3994     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3995     addptr(rsp, 64);
3996   }
3997 }
3998 
3999 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
4000   int dst_enc = dst->encoding();
4001   if (dst_enc < 16) {
4002     Assembler::pcmpestri(dst, src, imm8);
4003   } else {
4004     subptr(rsp, 64);
4005     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4006     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4007     Assembler::pcmpestri(xmm0, src, imm8);
4008     movdqu(dst, xmm0);
4009     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4010     addptr(rsp, 64);
4011   }
4012 }
4013 
4014 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
4015   int dst_enc = dst->encoding();
4016   int src_enc = src->encoding();
4017   if ((dst_enc < 16) && (src_enc < 16)) {
4018     Assembler::pcmpestri(dst, src, imm8);
4019   } else if (src_enc < 16) {
4020     subptr(rsp, 64);
4021     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4022     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4023     Assembler::pcmpestri(xmm0, src, imm8);
4024     movdqu(dst, xmm0);
4025     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4026     addptr(rsp, 64);
4027   } else if (dst_enc < 16) {
4028     subptr(rsp, 64);
4029     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4030     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4031     Assembler::pcmpestri(dst, xmm0, imm8);
4032     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4033     addptr(rsp, 64);
4034   } else {
4035     subptr(rsp, 64);
4036     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4037     subptr(rsp, 64);
4038     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4039     movdqu(xmm0, src);
4040     movdqu(xmm1, dst);
4041     Assembler::pcmpestri(xmm1, xmm0, imm8);
4042     movdqu(dst, xmm1);
4043     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4044     addptr(rsp, 64);
4045     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4046     addptr(rsp, 64);
4047   }
4048 }
4049 
4050 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4051   int dst_enc = dst->encoding();
4052   int src_enc = src->encoding();
4053   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4054     Assembler::pmovzxbw(dst, src);
4055   } else if ((dst_enc < 16) && (src_enc < 16)) {
4056     Assembler::pmovzxbw(dst, src);
4057   } else if (src_enc < 16) {
4058     subptr(rsp, 64);
4059     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4060     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4061     Assembler::pmovzxbw(xmm0, src);
4062     movdqu(dst, xmm0);
4063     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4064     addptr(rsp, 64);
4065   } else if (dst_enc < 16) {
4066     subptr(rsp, 64);
4067     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4068     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4069     Assembler::pmovzxbw(dst, xmm0);
4070     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4071     addptr(rsp, 64);
4072   } else {
4073     subptr(rsp, 64);
4074     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4075     subptr(rsp, 64);
4076     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4077     movdqu(xmm0, src);
4078     movdqu(xmm1, dst);
4079     Assembler::pmovzxbw(xmm1, xmm0);
4080     movdqu(dst, xmm1);
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::pmovzxbw(XMMRegister dst, Address src) {
4089   int dst_enc = dst->encoding();
4090   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4091     Assembler::pmovzxbw(dst, src);
4092   } else if (dst_enc < 16) {
4093     Assembler::pmovzxbw(dst, src);
4094   } else {
4095     subptr(rsp, 64);
4096     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4097     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4098     Assembler::pmovzxbw(xmm0, src);
4099     movdqu(dst, xmm0);
4100     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4101     addptr(rsp, 64);
4102   }
4103 }
4104 
4105 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4106   int src_enc = src->encoding();
4107   if (src_enc < 16) {
4108     Assembler::pmovmskb(dst, src);
4109   } else {
4110     subptr(rsp, 64);
4111     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4112     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4113     Assembler::pmovmskb(dst, xmm0);
4114     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4115     addptr(rsp, 64);
4116   }
4117 }
4118 
4119 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4120   int dst_enc = dst->encoding();
4121   int src_enc = src->encoding();
4122   if ((dst_enc < 16) && (src_enc < 16)) {
4123     Assembler::ptest(dst, src);
4124   } else if (src_enc < 16) {
4125     subptr(rsp, 64);
4126     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4127     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4128     Assembler::ptest(xmm0, src);
4129     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4130     addptr(rsp, 64);
4131   } else if (dst_enc < 16) {
4132     subptr(rsp, 64);
4133     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4134     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4135     Assembler::ptest(dst, xmm0);
4136     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4137     addptr(rsp, 64);
4138   } else {
4139     subptr(rsp, 64);
4140     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4141     subptr(rsp, 64);
4142     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4143     movdqu(xmm0, src);
4144     movdqu(xmm1, dst);
4145     Assembler::ptest(xmm1, xmm0);
4146     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4147     addptr(rsp, 64);
4148     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4149     addptr(rsp, 64);
4150   }
4151 }
4152 
4153 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4154   if (reachable(src)) {
4155     Assembler::sqrtsd(dst, as_Address(src));
4156   } else {
4157     lea(rscratch1, src);
4158     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4159   }
4160 }
4161 
4162 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4163   if (reachable(src)) {
4164     Assembler::sqrtss(dst, as_Address(src));
4165   } else {
4166     lea(rscratch1, src);
4167     Assembler::sqrtss(dst, Address(rscratch1, 0));
4168   }
4169 }
4170 
4171 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4172   if (reachable(src)) {
4173     Assembler::subsd(dst, as_Address(src));
4174   } else {
4175     lea(rscratch1, src);
4176     Assembler::subsd(dst, Address(rscratch1, 0));
4177   }
4178 }
4179 
4180 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4181   if (reachable(src)) {
4182     Assembler::subss(dst, as_Address(src));
4183   } else {
4184     lea(rscratch1, src);
4185     Assembler::subss(dst, Address(rscratch1, 0));
4186   }
4187 }
4188 
4189 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4190   if (reachable(src)) {
4191     Assembler::ucomisd(dst, as_Address(src));
4192   } else {
4193     lea(rscratch1, src);
4194     Assembler::ucomisd(dst, Address(rscratch1, 0));
4195   }
4196 }
4197 
4198 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4199   if (reachable(src)) {
4200     Assembler::ucomiss(dst, as_Address(src));
4201   } else {
4202     lea(rscratch1, src);
4203     Assembler::ucomiss(dst, Address(rscratch1, 0));
4204   }
4205 }
4206 
4207 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4208   // Used in sign-bit flipping with aligned address.
4209   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4210   if (reachable(src)) {
4211     Assembler::xorpd(dst, as_Address(src));
4212   } else {
4213     lea(rscratch1, src);
4214     Assembler::xorpd(dst, Address(rscratch1, 0));
4215   }
4216 }
4217 
4218 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4219   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4220     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4221   }
4222   else {
4223     Assembler::xorpd(dst, src);
4224   }
4225 }
4226 
4227 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4228   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4229     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4230   } else {
4231     Assembler::xorps(dst, src);
4232   }
4233 }
4234 
4235 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4236   // Used in sign-bit flipping with aligned address.
4237   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4238   if (reachable(src)) {
4239     Assembler::xorps(dst, as_Address(src));
4240   } else {
4241     lea(rscratch1, src);
4242     Assembler::xorps(dst, Address(rscratch1, 0));
4243   }
4244 }
4245 
4246 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4247   // Used in sign-bit flipping with aligned address.
4248   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4249   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4250   if (reachable(src)) {
4251     Assembler::pshufb(dst, as_Address(src));
4252   } else {
4253     lea(rscratch1, src);
4254     Assembler::pshufb(dst, Address(rscratch1, 0));
4255   }
4256 }
4257 
4258 // AVX 3-operands instructions
4259 
4260 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4261   if (reachable(src)) {
4262     vaddsd(dst, nds, as_Address(src));
4263   } else {
4264     lea(rscratch1, src);
4265     vaddsd(dst, nds, Address(rscratch1, 0));
4266   }
4267 }
4268 
4269 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4270   if (reachable(src)) {
4271     vaddss(dst, nds, as_Address(src));
4272   } else {
4273     lea(rscratch1, src);
4274     vaddss(dst, nds, Address(rscratch1, 0));
4275   }
4276 }
4277 
4278 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4279   int dst_enc = dst->encoding();
4280   int nds_enc = nds->encoding();
4281   int src_enc = src->encoding();
4282   if ((dst_enc < 16) && (nds_enc < 16)) {
4283     vandps(dst, nds, negate_field, vector_len);
4284   } else if ((src_enc < 16) && (dst_enc < 16)) {
4285     evmovdqul(src, nds, Assembler::AVX_512bit);
4286     vandps(dst, src, negate_field, vector_len);
4287   } else if (src_enc < 16) {
4288     evmovdqul(src, nds, Assembler::AVX_512bit);
4289     vandps(src, src, negate_field, vector_len);
4290     evmovdqul(dst, src, Assembler::AVX_512bit);
4291   } else if (dst_enc < 16) {
4292     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4293     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4294     vandps(dst, xmm0, negate_field, vector_len);
4295     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4296   } else {
4297     if (src_enc != dst_enc) {
4298       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4299       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4300       vandps(xmm0, xmm0, negate_field, vector_len);
4301       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4302       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4303     } else {
4304       subptr(rsp, 64);
4305       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4306       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4307       vandps(xmm0, xmm0, negate_field, vector_len);
4308       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4309       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4310       addptr(rsp, 64);
4311     }
4312   }
4313 }
4314 
4315 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4316   int dst_enc = dst->encoding();
4317   int nds_enc = nds->encoding();
4318   int src_enc = src->encoding();
4319   if ((dst_enc < 16) && (nds_enc < 16)) {
4320     vandpd(dst, nds, negate_field, vector_len);
4321   } else if ((src_enc < 16) && (dst_enc < 16)) {
4322     evmovdqul(src, nds, Assembler::AVX_512bit);
4323     vandpd(dst, src, negate_field, vector_len);
4324   } else if (src_enc < 16) {
4325     evmovdqul(src, nds, Assembler::AVX_512bit);
4326     vandpd(src, src, negate_field, vector_len);
4327     evmovdqul(dst, src, Assembler::AVX_512bit);
4328   } else if (dst_enc < 16) {
4329     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4330     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4331     vandpd(dst, xmm0, negate_field, vector_len);
4332     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4333   } else {
4334     if (src_enc != dst_enc) {
4335       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4336       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4337       vandpd(xmm0, xmm0, negate_field, vector_len);
4338       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4339       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4340     } else {
4341       subptr(rsp, 64);
4342       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4343       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4344       vandpd(xmm0, xmm0, negate_field, vector_len);
4345       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4346       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4347       addptr(rsp, 64);
4348     }
4349   }
4350 }
4351 
4352 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4353   int dst_enc = dst->encoding();
4354   int nds_enc = nds->encoding();
4355   int src_enc = src->encoding();
4356   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4357     Assembler::vpaddb(dst, nds, src, vector_len);
4358   } else if ((dst_enc < 16) && (src_enc < 16)) {
4359     Assembler::vpaddb(dst, dst, src, vector_len);
4360   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4361     // use nds as scratch for src
4362     evmovdqul(nds, src, Assembler::AVX_512bit);
4363     Assembler::vpaddb(dst, dst, nds, vector_len);
4364   } else if ((src_enc < 16) && (nds_enc < 16)) {
4365     // use nds as scratch for dst
4366     evmovdqul(nds, dst, Assembler::AVX_512bit);
4367     Assembler::vpaddb(nds, nds, src, vector_len);
4368     evmovdqul(dst, nds, Assembler::AVX_512bit);
4369   } else if (dst_enc < 16) {
4370     // use nds as scatch for xmm0 to hold src
4371     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4372     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4373     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4374     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4375   } else {
4376     // worse case scenario, all regs are in the upper bank
4377     subptr(rsp, 64);
4378     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4379     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4380     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4381     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4382     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4383     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4384     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4385     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4386     addptr(rsp, 64);
4387   }
4388 }
4389 
4390 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4391   int dst_enc = dst->encoding();
4392   int nds_enc = nds->encoding();
4393   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4394     Assembler::vpaddb(dst, nds, src, vector_len);
4395   } else if (dst_enc < 16) {
4396     Assembler::vpaddb(dst, dst, src, vector_len);
4397   } else if (nds_enc < 16) {
4398     // implies dst_enc in upper bank with src as scratch
4399     evmovdqul(nds, dst, Assembler::AVX_512bit);
4400     Assembler::vpaddb(nds, nds, src, vector_len);
4401     evmovdqul(dst, nds, Assembler::AVX_512bit);
4402   } else {
4403     // worse case scenario, all regs in upper bank
4404     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4405     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4406     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4407     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4408   }
4409 }
4410 
4411 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4412   int dst_enc = dst->encoding();
4413   int nds_enc = nds->encoding();
4414   int src_enc = src->encoding();
4415   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4416     Assembler::vpaddw(dst, nds, src, vector_len);
4417   } else if ((dst_enc < 16) && (src_enc < 16)) {
4418     Assembler::vpaddw(dst, dst, src, vector_len);
4419   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4420     // use nds as scratch for src
4421     evmovdqul(nds, src, Assembler::AVX_512bit);
4422     Assembler::vpaddw(dst, dst, nds, vector_len);
4423   } else if ((src_enc < 16) && (nds_enc < 16)) {
4424     // use nds as scratch for dst
4425     evmovdqul(nds, dst, Assembler::AVX_512bit);
4426     Assembler::vpaddw(nds, nds, src, vector_len);
4427     evmovdqul(dst, nds, Assembler::AVX_512bit);
4428   } else if (dst_enc < 16) {
4429     // use nds as scatch for xmm0 to hold src
4430     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4431     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4432     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4433     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4434   } else {
4435     // worse case scenario, all regs are in the upper bank
4436     subptr(rsp, 64);
4437     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4438     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4439     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4440     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4441     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4442     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4443     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4444     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4445     addptr(rsp, 64);
4446   }
4447 }
4448 
4449 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4450   int dst_enc = dst->encoding();
4451   int nds_enc = nds->encoding();
4452   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4453     Assembler::vpaddw(dst, nds, src, vector_len);
4454   } else if (dst_enc < 16) {
4455     Assembler::vpaddw(dst, dst, src, vector_len);
4456   } else if (nds_enc < 16) {
4457     // implies dst_enc in upper bank with src as scratch
4458     evmovdqul(nds, dst, Assembler::AVX_512bit);
4459     Assembler::vpaddw(nds, nds, src, vector_len);
4460     evmovdqul(dst, nds, Assembler::AVX_512bit);
4461   } else {
4462     // worse case scenario, all regs in upper bank
4463     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4464     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4465     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4466     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4467   }
4468 }
4469 
4470 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4471   if (reachable(src)) {
4472     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4473   } else {
4474     lea(rscratch1, src);
4475     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4476   }
4477 }
4478 
4479 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4480   int dst_enc = dst->encoding();
4481   int src_enc = src->encoding();
4482   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4483     Assembler::vpbroadcastw(dst, src);
4484   } else if ((dst_enc < 16) && (src_enc < 16)) {
4485     Assembler::vpbroadcastw(dst, src);
4486   } else if (src_enc < 16) {
4487     subptr(rsp, 64);
4488     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4489     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4490     Assembler::vpbroadcastw(xmm0, src);
4491     movdqu(dst, xmm0);
4492     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4493     addptr(rsp, 64);
4494   } else if (dst_enc < 16) {
4495     subptr(rsp, 64);
4496     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4497     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4498     Assembler::vpbroadcastw(dst, xmm0);
4499     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4500     addptr(rsp, 64);
4501   } else {
4502     subptr(rsp, 64);
4503     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4504     subptr(rsp, 64);
4505     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4506     movdqu(xmm0, src);
4507     movdqu(xmm1, dst);
4508     Assembler::vpbroadcastw(xmm1, xmm0);
4509     movdqu(dst, xmm1);
4510     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4511     addptr(rsp, 64);
4512     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4513     addptr(rsp, 64);
4514   }
4515 }
4516 
4517 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4518   int dst_enc = dst->encoding();
4519   int nds_enc = nds->encoding();
4520   int src_enc = src->encoding();
4521   assert(dst_enc == nds_enc, "");
4522   if ((dst_enc < 16) && (src_enc < 16)) {
4523     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4524   } else if (src_enc < 16) {
4525     subptr(rsp, 64);
4526     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4527     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4528     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4529     movdqu(dst, xmm0);
4530     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4531     addptr(rsp, 64);
4532   } else if (dst_enc < 16) {
4533     subptr(rsp, 64);
4534     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4535     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4536     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4537     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4538     addptr(rsp, 64);
4539   } else {
4540     subptr(rsp, 64);
4541     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4542     subptr(rsp, 64);
4543     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4544     movdqu(xmm0, src);
4545     movdqu(xmm1, dst);
4546     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4547     movdqu(dst, xmm1);
4548     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4549     addptr(rsp, 64);
4550     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4551     addptr(rsp, 64);
4552   }
4553 }
4554 
4555 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4556   int dst_enc = dst->encoding();
4557   int nds_enc = nds->encoding();
4558   int src_enc = src->encoding();
4559   assert(dst_enc == nds_enc, "");
4560   if ((dst_enc < 16) && (src_enc < 16)) {
4561     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4562   } else if (src_enc < 16) {
4563     subptr(rsp, 64);
4564     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4565     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4566     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4567     movdqu(dst, xmm0);
4568     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4569     addptr(rsp, 64);
4570   } else if (dst_enc < 16) {
4571     subptr(rsp, 64);
4572     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4573     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4574     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4575     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4576     addptr(rsp, 64);
4577   } else {
4578     subptr(rsp, 64);
4579     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4580     subptr(rsp, 64);
4581     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4582     movdqu(xmm0, src);
4583     movdqu(xmm1, dst);
4584     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4585     movdqu(dst, xmm1);
4586     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4587     addptr(rsp, 64);
4588     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4589     addptr(rsp, 64);
4590   }
4591 }
4592 
4593 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4594   int dst_enc = dst->encoding();
4595   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4596     Assembler::vpmovzxbw(dst, src, vector_len);
4597   } else if (dst_enc < 16) {
4598     Assembler::vpmovzxbw(dst, src, vector_len);
4599   } else {
4600     subptr(rsp, 64);
4601     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4603     Assembler::vpmovzxbw(xmm0, src, vector_len);
4604     movdqu(dst, xmm0);
4605     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4606     addptr(rsp, 64);
4607   }
4608 }
4609 
4610 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4611   int src_enc = src->encoding();
4612   if (src_enc < 16) {
4613     Assembler::vpmovmskb(dst, src);
4614   } else {
4615     subptr(rsp, 64);
4616     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4617     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4618     Assembler::vpmovmskb(dst, xmm0);
4619     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4620     addptr(rsp, 64);
4621   }
4622 }
4623 
4624 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4625   int dst_enc = dst->encoding();
4626   int nds_enc = nds->encoding();
4627   int src_enc = src->encoding();
4628   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4629     Assembler::vpmullw(dst, nds, src, vector_len);
4630   } else if ((dst_enc < 16) && (src_enc < 16)) {
4631     Assembler::vpmullw(dst, dst, src, vector_len);
4632   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4633     // use nds as scratch for src
4634     evmovdqul(nds, src, Assembler::AVX_512bit);
4635     Assembler::vpmullw(dst, dst, nds, vector_len);
4636   } else if ((src_enc < 16) && (nds_enc < 16)) {
4637     // use nds as scratch for dst
4638     evmovdqul(nds, dst, Assembler::AVX_512bit);
4639     Assembler::vpmullw(nds, nds, src, vector_len);
4640     evmovdqul(dst, nds, Assembler::AVX_512bit);
4641   } else if (dst_enc < 16) {
4642     // use nds as scatch for xmm0 to hold src
4643     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4644     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4645     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4646     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4647   } else {
4648     // worse case scenario, all regs are in the upper bank
4649     subptr(rsp, 64);
4650     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4651     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4652     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4653     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4654     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4655     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4656     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4657     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4658     addptr(rsp, 64);
4659   }
4660 }
4661 
4662 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4663   int dst_enc = dst->encoding();
4664   int nds_enc = nds->encoding();
4665   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4666     Assembler::vpmullw(dst, nds, src, vector_len);
4667   } else if (dst_enc < 16) {
4668     Assembler::vpmullw(dst, dst, src, vector_len);
4669   } else if (nds_enc < 16) {
4670     // implies dst_enc in upper bank with src as scratch
4671     evmovdqul(nds, dst, Assembler::AVX_512bit);
4672     Assembler::vpmullw(nds, nds, src, vector_len);
4673     evmovdqul(dst, nds, Assembler::AVX_512bit);
4674   } else {
4675     // worse case scenario, all regs in upper bank
4676     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4677     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4678     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4679     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4680   }
4681 }
4682 
4683 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4684   int dst_enc = dst->encoding();
4685   int nds_enc = nds->encoding();
4686   int src_enc = src->encoding();
4687   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4688     Assembler::vpsubb(dst, nds, src, vector_len);
4689   } else if ((dst_enc < 16) && (src_enc < 16)) {
4690     Assembler::vpsubb(dst, dst, src, vector_len);
4691   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4692     // use nds as scratch for src
4693     evmovdqul(nds, src, Assembler::AVX_512bit);
4694     Assembler::vpsubb(dst, dst, nds, vector_len);
4695   } else if ((src_enc < 16) && (nds_enc < 16)) {
4696     // use nds as scratch for dst
4697     evmovdqul(nds, dst, Assembler::AVX_512bit);
4698     Assembler::vpsubb(nds, nds, src, vector_len);
4699     evmovdqul(dst, nds, Assembler::AVX_512bit);
4700   } else if (dst_enc < 16) {
4701     // use nds as scatch for xmm0 to hold src
4702     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4703     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4704     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4705     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4706   } else {
4707     // worse case scenario, all regs are in the upper bank
4708     subptr(rsp, 64);
4709     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4710     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4711     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4712     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4713     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4714     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4715     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4716     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4717     addptr(rsp, 64);
4718   }
4719 }
4720 
4721 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4722   int dst_enc = dst->encoding();
4723   int nds_enc = nds->encoding();
4724   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4725     Assembler::vpsubb(dst, nds, src, vector_len);
4726   } else if (dst_enc < 16) {
4727     Assembler::vpsubb(dst, dst, src, vector_len);
4728   } else if (nds_enc < 16) {
4729     // implies dst_enc in upper bank with src as scratch
4730     evmovdqul(nds, dst, Assembler::AVX_512bit);
4731     Assembler::vpsubb(nds, nds, src, vector_len);
4732     evmovdqul(dst, nds, Assembler::AVX_512bit);
4733   } else {
4734     // worse case scenario, all regs in upper bank
4735     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4736     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4737     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4738     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4739   }
4740 }
4741 
4742 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4743   int dst_enc = dst->encoding();
4744   int nds_enc = nds->encoding();
4745   int src_enc = src->encoding();
4746   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4747     Assembler::vpsubw(dst, nds, src, vector_len);
4748   } else if ((dst_enc < 16) && (src_enc < 16)) {
4749     Assembler::vpsubw(dst, dst, src, vector_len);
4750   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4751     // use nds as scratch for src
4752     evmovdqul(nds, src, Assembler::AVX_512bit);
4753     Assembler::vpsubw(dst, dst, nds, vector_len);
4754   } else if ((src_enc < 16) && (nds_enc < 16)) {
4755     // use nds as scratch for dst
4756     evmovdqul(nds, dst, Assembler::AVX_512bit);
4757     Assembler::vpsubw(nds, nds, src, vector_len);
4758     evmovdqul(dst, nds, Assembler::AVX_512bit);
4759   } else if (dst_enc < 16) {
4760     // use nds as scatch for xmm0 to hold src
4761     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4762     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4763     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4764     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4765   } else {
4766     // worse case scenario, all regs are in the upper bank
4767     subptr(rsp, 64);
4768     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4769     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4770     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4771     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4772     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4773     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4774     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4775     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4776     addptr(rsp, 64);
4777   }
4778 }
4779 
4780 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4781   int dst_enc = dst->encoding();
4782   int nds_enc = nds->encoding();
4783   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4784     Assembler::vpsubw(dst, nds, src, vector_len);
4785   } else if (dst_enc < 16) {
4786     Assembler::vpsubw(dst, dst, src, vector_len);
4787   } else if (nds_enc < 16) {
4788     // implies dst_enc in upper bank with src as scratch
4789     evmovdqul(nds, dst, Assembler::AVX_512bit);
4790     Assembler::vpsubw(nds, nds, src, vector_len);
4791     evmovdqul(dst, nds, Assembler::AVX_512bit);
4792   } else {
4793     // worse case scenario, all regs in upper bank
4794     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4795     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4796     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4797     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4798   }
4799 }
4800 
4801 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4802   int dst_enc = dst->encoding();
4803   int nds_enc = nds->encoding();
4804   int shift_enc = shift->encoding();
4805   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4806     Assembler::vpsraw(dst, nds, shift, vector_len);
4807   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4808     Assembler::vpsraw(dst, dst, shift, vector_len);
4809   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4810     // use nds_enc as scratch with shift
4811     evmovdqul(nds, shift, Assembler::AVX_512bit);
4812     Assembler::vpsraw(dst, dst, nds, vector_len);
4813   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4814     // use nds as scratch with dst
4815     evmovdqul(nds, dst, Assembler::AVX_512bit);
4816     Assembler::vpsraw(nds, nds, shift, vector_len);
4817     evmovdqul(dst, nds, Assembler::AVX_512bit);
4818   } else if (dst_enc < 16) {
4819     // use nds to save a copy of xmm0 and hold shift
4820     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4821     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4822     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4823     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4824   } else if (nds_enc < 16) {
4825     // use nds as dest as temps
4826     evmovdqul(nds, dst, Assembler::AVX_512bit);
4827     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4828     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4829     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4830     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4831     evmovdqul(dst, nds, Assembler::AVX_512bit);
4832   } else {
4833     // worse case scenario, all regs are in the upper bank
4834     subptr(rsp, 64);
4835     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4836     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4837     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4838     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4839     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4840     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4841     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4842     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4843     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4844     addptr(rsp, 64);
4845   }
4846 }
4847 
4848 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4849   int dst_enc = dst->encoding();
4850   int nds_enc = nds->encoding();
4851   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4852     Assembler::vpsraw(dst, nds, shift, vector_len);
4853   } else if (dst_enc < 16) {
4854     Assembler::vpsraw(dst, dst, shift, vector_len);
4855   } else if (nds_enc < 16) {
4856     // use nds as scratch
4857     evmovdqul(nds, dst, Assembler::AVX_512bit);
4858     Assembler::vpsraw(nds, nds, shift, vector_len);
4859     evmovdqul(dst, nds, Assembler::AVX_512bit);
4860   } else {
4861     // use nds as scratch for xmm0
4862     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4863     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4864     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4865     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4866   }
4867 }
4868 
4869 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4870   int dst_enc = dst->encoding();
4871   int nds_enc = nds->encoding();
4872   int shift_enc = shift->encoding();
4873   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4874     Assembler::vpsrlw(dst, nds, shift, vector_len);
4875   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4876     Assembler::vpsrlw(dst, dst, shift, vector_len);
4877   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4878     // use nds_enc as scratch with shift
4879     evmovdqul(nds, shift, Assembler::AVX_512bit);
4880     Assembler::vpsrlw(dst, dst, nds, vector_len);
4881   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4882     // use nds as scratch with dst
4883     evmovdqul(nds, dst, Assembler::AVX_512bit);
4884     Assembler::vpsrlw(nds, nds, shift, vector_len);
4885     evmovdqul(dst, nds, Assembler::AVX_512bit);
4886   } else if (dst_enc < 16) {
4887     // use nds to save a copy of xmm0 and hold shift
4888     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4889     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4890     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4891     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4892   } else if (nds_enc < 16) {
4893     // use nds as dest as temps
4894     evmovdqul(nds, dst, Assembler::AVX_512bit);
4895     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4896     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4897     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4898     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4899     evmovdqul(dst, nds, Assembler::AVX_512bit);
4900   } else {
4901     // worse case scenario, all regs are in the upper bank
4902     subptr(rsp, 64);
4903     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4904     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4905     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4906     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4907     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4908     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4909     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4910     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4911     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4912     addptr(rsp, 64);
4913   }
4914 }
4915 
4916 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4917   int dst_enc = dst->encoding();
4918   int nds_enc = nds->encoding();
4919   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4920     Assembler::vpsrlw(dst, nds, shift, vector_len);
4921   } else if (dst_enc < 16) {
4922     Assembler::vpsrlw(dst, dst, shift, vector_len);
4923   } else if (nds_enc < 16) {
4924     // use nds as scratch
4925     evmovdqul(nds, dst, Assembler::AVX_512bit);
4926     Assembler::vpsrlw(nds, nds, shift, vector_len);
4927     evmovdqul(dst, nds, Assembler::AVX_512bit);
4928   } else {
4929     // use nds as scratch for xmm0
4930     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4931     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4932     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4933     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4934   }
4935 }
4936 
4937 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4938   int dst_enc = dst->encoding();
4939   int nds_enc = nds->encoding();
4940   int shift_enc = shift->encoding();
4941   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4942     Assembler::vpsllw(dst, nds, shift, vector_len);
4943   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4944     Assembler::vpsllw(dst, dst, shift, vector_len);
4945   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4946     // use nds_enc as scratch with shift
4947     evmovdqul(nds, shift, Assembler::AVX_512bit);
4948     Assembler::vpsllw(dst, dst, nds, vector_len);
4949   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4950     // use nds as scratch with dst
4951     evmovdqul(nds, dst, Assembler::AVX_512bit);
4952     Assembler::vpsllw(nds, nds, shift, vector_len);
4953     evmovdqul(dst, nds, Assembler::AVX_512bit);
4954   } else if (dst_enc < 16) {
4955     // use nds to save a copy of xmm0 and hold shift
4956     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4957     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4958     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4959     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4960   } else if (nds_enc < 16) {
4961     // use nds as dest as temps
4962     evmovdqul(nds, dst, Assembler::AVX_512bit);
4963     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4964     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4965     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4966     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4967     evmovdqul(dst, nds, Assembler::AVX_512bit);
4968   } else {
4969     // worse case scenario, all regs are in the upper bank
4970     subptr(rsp, 64);
4971     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4972     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4973     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4974     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4975     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4976     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4977     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4978     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4979     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4980     addptr(rsp, 64);
4981   }
4982 }
4983 
4984 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4985   int dst_enc = dst->encoding();
4986   int nds_enc = nds->encoding();
4987   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4988     Assembler::vpsllw(dst, nds, shift, vector_len);
4989   } else if (dst_enc < 16) {
4990     Assembler::vpsllw(dst, dst, shift, vector_len);
4991   } else if (nds_enc < 16) {
4992     // use nds as scratch
4993     evmovdqul(nds, dst, Assembler::AVX_512bit);
4994     Assembler::vpsllw(nds, nds, shift, vector_len);
4995     evmovdqul(dst, nds, Assembler::AVX_512bit);
4996   } else {
4997     // use nds as scratch for xmm0
4998     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4999     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5000     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
5001     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5002   }
5003 }
5004 
5005 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
5006   int dst_enc = dst->encoding();
5007   int src_enc = src->encoding();
5008   if ((dst_enc < 16) && (src_enc < 16)) {
5009     Assembler::vptest(dst, src);
5010   } else if (src_enc < 16) {
5011     subptr(rsp, 64);
5012     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5013     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5014     Assembler::vptest(xmm0, src);
5015     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5016     addptr(rsp, 64);
5017   } else if (dst_enc < 16) {
5018     subptr(rsp, 64);
5019     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5020     evmovdqul(xmm0, src, Assembler::AVX_512bit);
5021     Assembler::vptest(dst, xmm0);
5022     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5023     addptr(rsp, 64);
5024   } else {
5025     subptr(rsp, 64);
5026     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5027     subptr(rsp, 64);
5028     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5029     movdqu(xmm0, src);
5030     movdqu(xmm1, dst);
5031     Assembler::vptest(xmm1, xmm0);
5032     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5033     addptr(rsp, 64);
5034     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5035     addptr(rsp, 64);
5036   }
5037 }
5038 
5039 // This instruction exists within macros, ergo we cannot control its input
5040 // when emitted through those patterns.
5041 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
5042   if (VM_Version::supports_avx512nobw()) {
5043     int dst_enc = dst->encoding();
5044     int src_enc = src->encoding();
5045     if (dst_enc == src_enc) {
5046       if (dst_enc < 16) {
5047         Assembler::punpcklbw(dst, src);
5048       } else {
5049         subptr(rsp, 64);
5050         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5051         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5052         Assembler::punpcklbw(xmm0, xmm0);
5053         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5054         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5055         addptr(rsp, 64);
5056       }
5057     } else {
5058       if ((src_enc < 16) && (dst_enc < 16)) {
5059         Assembler::punpcklbw(dst, src);
5060       } else if (src_enc < 16) {
5061         subptr(rsp, 64);
5062         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5063         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5064         Assembler::punpcklbw(xmm0, src);
5065         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5066         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5067         addptr(rsp, 64);
5068       } else if (dst_enc < 16) {
5069         subptr(rsp, 64);
5070         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5071         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5072         Assembler::punpcklbw(dst, xmm0);
5073         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5074         addptr(rsp, 64);
5075       } else {
5076         subptr(rsp, 64);
5077         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5078         subptr(rsp, 64);
5079         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5080         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5081         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5082         Assembler::punpcklbw(xmm0, xmm1);
5083         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5084         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5085         addptr(rsp, 64);
5086         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5087         addptr(rsp, 64);
5088       }
5089     }
5090   } else {
5091     Assembler::punpcklbw(dst, src);
5092   }
5093 }
5094 
5095 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5096   if (VM_Version::supports_avx512vl()) {
5097     Assembler::pshufd(dst, src, mode);
5098   } else {
5099     int dst_enc = dst->encoding();
5100     if (dst_enc < 16) {
5101       Assembler::pshufd(dst, src, mode);
5102     } else {
5103       subptr(rsp, 64);
5104       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5105       Assembler::pshufd(xmm0, src, mode);
5106       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5107       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5108       addptr(rsp, 64);
5109     }
5110   }
5111 }
5112 
5113 // This instruction exists within macros, ergo we cannot control its input
5114 // when emitted through those patterns.
5115 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5116   if (VM_Version::supports_avx512nobw()) {
5117     int dst_enc = dst->encoding();
5118     int src_enc = src->encoding();
5119     if (dst_enc == src_enc) {
5120       if (dst_enc < 16) {
5121         Assembler::pshuflw(dst, src, mode);
5122       } else {
5123         subptr(rsp, 64);
5124         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5125         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5126         Assembler::pshuflw(xmm0, xmm0, mode);
5127         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5128         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5129         addptr(rsp, 64);
5130       }
5131     } else {
5132       if ((src_enc < 16) && (dst_enc < 16)) {
5133         Assembler::pshuflw(dst, src, mode);
5134       } else if (src_enc < 16) {
5135         subptr(rsp, 64);
5136         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5137         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5138         Assembler::pshuflw(xmm0, src, mode);
5139         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5140         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5141         addptr(rsp, 64);
5142       } else if (dst_enc < 16) {
5143         subptr(rsp, 64);
5144         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5145         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5146         Assembler::pshuflw(dst, xmm0, mode);
5147         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5148         addptr(rsp, 64);
5149       } else {
5150         subptr(rsp, 64);
5151         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5152         subptr(rsp, 64);
5153         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5154         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5155         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5156         Assembler::pshuflw(xmm0, xmm1, mode);
5157         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5158         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5159         addptr(rsp, 64);
5160         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5161         addptr(rsp, 64);
5162       }
5163     }
5164   } else {
5165     Assembler::pshuflw(dst, src, mode);
5166   }
5167 }
5168 
5169 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5170   if (reachable(src)) {
5171     vandpd(dst, nds, as_Address(src), vector_len);
5172   } else {
5173     lea(rscratch1, src);
5174     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5175   }
5176 }
5177 
5178 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5179   if (reachable(src)) {
5180     vandps(dst, nds, as_Address(src), vector_len);
5181   } else {
5182     lea(rscratch1, src);
5183     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5184   }
5185 }
5186 
5187 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5188   if (reachable(src)) {
5189     vdivsd(dst, nds, as_Address(src));
5190   } else {
5191     lea(rscratch1, src);
5192     vdivsd(dst, nds, Address(rscratch1, 0));
5193   }
5194 }
5195 
5196 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5197   if (reachable(src)) {
5198     vdivss(dst, nds, as_Address(src));
5199   } else {
5200     lea(rscratch1, src);
5201     vdivss(dst, nds, Address(rscratch1, 0));
5202   }
5203 }
5204 
5205 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5206   if (reachable(src)) {
5207     vmulsd(dst, nds, as_Address(src));
5208   } else {
5209     lea(rscratch1, src);
5210     vmulsd(dst, nds, Address(rscratch1, 0));
5211   }
5212 }
5213 
5214 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5215   if (reachable(src)) {
5216     vmulss(dst, nds, as_Address(src));
5217   } else {
5218     lea(rscratch1, src);
5219     vmulss(dst, nds, Address(rscratch1, 0));
5220   }
5221 }
5222 
5223 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5224   if (reachable(src)) {
5225     vsubsd(dst, nds, as_Address(src));
5226   } else {
5227     lea(rscratch1, src);
5228     vsubsd(dst, nds, Address(rscratch1, 0));
5229   }
5230 }
5231 
5232 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5233   if (reachable(src)) {
5234     vsubss(dst, nds, as_Address(src));
5235   } else {
5236     lea(rscratch1, src);
5237     vsubss(dst, nds, Address(rscratch1, 0));
5238   }
5239 }
5240 
5241 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5242   int nds_enc = nds->encoding();
5243   int dst_enc = dst->encoding();
5244   bool dst_upper_bank = (dst_enc > 15);
5245   bool nds_upper_bank = (nds_enc > 15);
5246   if (VM_Version::supports_avx512novl() &&
5247       (nds_upper_bank || dst_upper_bank)) {
5248     if (dst_upper_bank) {
5249       subptr(rsp, 64);
5250       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5251       movflt(xmm0, nds);
5252       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5253       movflt(dst, xmm0);
5254       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5255       addptr(rsp, 64);
5256     } else {
5257       movflt(dst, nds);
5258       vxorps(dst, dst, src, Assembler::AVX_128bit);
5259     }
5260   } else {
5261     vxorps(dst, nds, src, Assembler::AVX_128bit);
5262   }
5263 }
5264 
5265 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5266   int nds_enc = nds->encoding();
5267   int dst_enc = dst->encoding();
5268   bool dst_upper_bank = (dst_enc > 15);
5269   bool nds_upper_bank = (nds_enc > 15);
5270   if (VM_Version::supports_avx512novl() &&
5271       (nds_upper_bank || dst_upper_bank)) {
5272     if (dst_upper_bank) {
5273       subptr(rsp, 64);
5274       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5275       movdbl(xmm0, nds);
5276       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5277       movdbl(dst, xmm0);
5278       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5279       addptr(rsp, 64);
5280     } else {
5281       movdbl(dst, nds);
5282       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5283     }
5284   } else {
5285     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5286   }
5287 }
5288 
5289 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5290   if (reachable(src)) {
5291     vxorpd(dst, nds, as_Address(src), vector_len);
5292   } else {
5293     lea(rscratch1, src);
5294     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5295   }
5296 }
5297 
5298 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5299   if (reachable(src)) {
5300     vxorps(dst, nds, as_Address(src), vector_len);
5301   } else {
5302     lea(rscratch1, src);
5303     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5304   }
5305 }
5306 
5307 
5308 void MacroAssembler::resolve_jobject(Register value,
5309                                      Register thread,
5310                                      Register tmp) {
5311   assert_different_registers(value, thread, tmp);
5312   Label done, not_weak;
5313   testptr(value, value);
5314   jcc(Assembler::zero, done);                // Use NULL as-is.
5315   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5316   jcc(Assembler::zero, not_weak);
5317   // Resolve jweak.
5318   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5319   verify_oop(value);
5320 #if INCLUDE_ALL_GCS
5321   if (UseG1GC || UseShenandoahGC) {
5322     g1_write_barrier_pre(noreg /* obj */,
5323                          value /* pre_val */,
5324                          thread /* thread */,
5325                          tmp /* tmp */,
5326                          true /* tosca_live */,
5327                          true /* expand_call */);
5328   }
5329 #endif // INCLUDE_ALL_GCS
5330   jmp(done);
5331   bind(not_weak);
5332   // Resolve (untagged) jobject.
5333   movptr(value, Address(value, 0));
5334   verify_oop(value);
5335   bind(done);
5336 }
5337 
5338 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5339   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5340   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5341   // The inverted mask is sign-extended
5342   andptr(possibly_jweak, inverted_jweak_mask);
5343 }
5344 
5345 //////////////////////////////////////////////////////////////////////////////////
5346 #if INCLUDE_ALL_GCS
5347 
5348 void MacroAssembler::g1_write_barrier_pre(Register obj,
5349                                           Register pre_val,
5350                                           Register thread,
5351                                           Register tmp,
5352                                           bool tosca_live,
5353                                           bool expand_call) {
5354 
5355   // If expand_call is true then we expand the call_VM_leaf macro
5356   // directly to skip generating the check by
5357   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5358 
5359 #ifdef _LP64
5360   assert(thread == r15_thread, "must be");
5361 #endif // _LP64
5362 
5363   Label done;
5364   Label runtime;
5365 
5366   assert(pre_val != noreg, "check this code");
5367 
5368   if (obj != noreg) {
5369     assert_different_registers(obj, pre_val, tmp);
5370     assert(pre_val != rax, "check this code");
5371   }
5372 
5373   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5374                                        SATBMarkQueue::byte_offset_of_active()));
5375   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5376                                        SATBMarkQueue::byte_offset_of_index()));
5377   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5378                                        SATBMarkQueue::byte_offset_of_buf()));
5379 
5380 
5381   // Is marking active?
5382   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5383     cmpl(in_progress, 0);
5384   } else {
5385     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5386     cmpb(in_progress, 0);
5387   }
5388   jcc(Assembler::equal, done);
5389 
5390   // Do we need to load the previous value?
5391   if (obj != noreg) {
5392     load_heap_oop(pre_val, Address(obj, 0));
5393   }
5394 
5395   // Is the previous value null?
5396   cmpptr(pre_val, (int32_t) NULL_WORD);
5397   jcc(Assembler::equal, done);
5398 
5399   // Can we store original value in the thread's buffer?
5400   // Is index == 0?
5401   // (The index field is typed as size_t.)
5402 
5403   movptr(tmp, index);                   // tmp := *index_adr
5404   cmpptr(tmp, 0);                       // tmp == 0?
5405   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5406 
5407   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5408   movptr(index, tmp);                   // *index_adr := tmp
5409   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5410 
5411   // Record the previous value
5412   movptr(Address(tmp, 0), pre_val);
5413   jmp(done);
5414 
5415   bind(runtime);
5416   // save the live input values
5417   if(tosca_live) push(rax);
5418 
5419   if (obj != noreg && obj != rax)
5420     push(obj);
5421 
5422   if (pre_val != rax)
5423     push(pre_val);
5424 
5425   // Calling the runtime using the regular call_VM_leaf mechanism generates
5426   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5427   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5428   //
5429   // If we care generating the pre-barrier without a frame (e.g. in the
5430   // intrinsified Reference.get() routine) then ebp might be pointing to
5431   // the caller frame and so this check will most likely fail at runtime.
5432   //
5433   // Expanding the call directly bypasses the generation of the check.
5434   // So when we do not have have a full interpreter frame on the stack
5435   // expand_call should be passed true.
5436 
5437   NOT_LP64( push(thread); )
5438 
5439   if (expand_call) {
5440     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5441     pass_arg1(this, thread);
5442     pass_arg0(this, pre_val);
5443     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5444   } else {
5445     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5446   }
5447 
5448   NOT_LP64( pop(thread); )
5449 
5450   // save the live input values
5451   if (pre_val != rax)
5452     pop(pre_val);
5453 
5454   if (obj != noreg && obj != rax)
5455     pop(obj);
5456 
5457   if(tosca_live) pop(rax);
5458 
5459   bind(done);
5460 }
5461 
5462 void MacroAssembler::shenandoah_write_barrier_post(Register store_addr,
5463                                                    Register new_val,
5464                                                    Register thread,
5465                                                    Register tmp,
5466                                                    Register tmp2) {
5467   assert(UseShenandoahGC, "why else should we be here?");
5468 
5469   if (! UseShenandoahMatrix) {
5470     // No need for that barrier if not using matrix.
5471     return;
5472   }
5473 
5474   Label done;
5475   testptr(new_val, new_val);
5476   jcc(Assembler::zero, done);
5477   ShenandoahConnectionMatrix* matrix = ShenandoahHeap::heap()->connection_matrix();
5478   address matrix_addr = matrix->matrix_addr();
5479   movptr(rscratch1, (intptr_t) ShenandoahHeap::heap()->base());
5480   // Compute to-region index
5481   movptr(tmp, new_val);
5482   subptr(tmp, rscratch1);
5483   shrptr(tmp, ShenandoahHeapRegion::region_size_shift_jint());
5484   // Compute from-region index
5485   movptr(tmp2, store_addr);
5486   subptr(tmp2, rscratch1);
5487   shrptr(tmp2, ShenandoahHeapRegion::region_size_shift_jint());
5488   // Compute matrix index
5489   imulptr(tmp, tmp, matrix->stride_jint());
5490   addptr(tmp, tmp2);
5491   // Address is _matrix[from * stride + to]
5492   movptr(rscratch1, (intptr_t) matrix_addr);
5493   // Test if the element is already set.
5494   testb(Address(rscratch1, tmp, Address::times_1), 0);
5495   jcc(Assembler::notZero, done);
5496   // Store true, if not yet set.
5497   movb(Address(rscratch1, tmp, Address::times_1), 1);
5498   bind(done);
5499 }
5500 
5501 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5502                                            Register new_val,
5503                                            Register thread,
5504                                            Register tmp,
5505                                            Register tmp2) {
5506 #ifdef _LP64
5507   assert(thread == r15_thread, "must be");
5508 #endif // _LP64
5509 
5510   assert(UseG1GC, "expect G1 GC");
5511 
5512   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5513                                        DirtyCardQueue::byte_offset_of_index()));
5514   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5515                                        DirtyCardQueue::byte_offset_of_buf()));
5516 
5517   CardTableModRefBS* ct =
5518     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5519   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5520 
5521   Label done;
5522   Label runtime;
5523 
5524   // Does store cross heap regions?
5525 
5526   movptr(tmp, store_addr);
5527   xorptr(tmp, new_val);
5528   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5529   jcc(Assembler::equal, done);
5530 
5531   // crosses regions, storing NULL?
5532 
5533   cmpptr(new_val, (int32_t) NULL_WORD);
5534   jcc(Assembler::equal, done);
5535 
5536   // storing region crossing non-NULL, is card already dirty?
5537 
5538   const Register card_addr = tmp;
5539   const Register cardtable = tmp2;
5540 
5541   movptr(card_addr, store_addr);
5542   shrptr(card_addr, CardTableModRefBS::card_shift);
5543   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5544   // a valid address and therefore is not properly handled by the relocation code.
5545   movptr(cardtable, (intptr_t)ct->byte_map_base);
5546   addptr(card_addr, cardtable);
5547 
5548   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5549   jcc(Assembler::equal, done);
5550 
5551   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5552   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5553   jcc(Assembler::equal, done);
5554 
5555 
5556   // storing a region crossing, non-NULL oop, card is clean.
5557   // dirty card and log.
5558 
5559   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5560 
5561   cmpl(queue_index, 0);
5562   jcc(Assembler::equal, runtime);
5563   subl(queue_index, wordSize);
5564   movptr(tmp2, buffer);
5565 #ifdef _LP64
5566   movslq(rscratch1, queue_index);
5567   addq(tmp2, rscratch1);
5568   movq(Address(tmp2, 0), card_addr);
5569 #else
5570   addl(tmp2, queue_index);
5571   movl(Address(tmp2, 0), card_addr);
5572 #endif
5573   jmp(done);
5574 
5575   bind(runtime);
5576   // save the live input values
5577   push(store_addr);
5578   push(new_val);
5579 #ifdef _LP64
5580   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5581 #else
5582   push(thread);
5583   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5584   pop(thread);
5585 #endif
5586   pop(new_val);
5587   pop(store_addr);
5588 
5589   bind(done);
5590 }
5591 
5592 #ifndef _LP64
5593 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5594   Unimplemented();
5595 }
5596 #else
5597 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5598   assert(UseShenandoahGC, "must only be called with Shenandoah GC active");
5599   assert(ShenandoahWriteBarrier, "must only be called when write barriers are enabled");
5600 
5601   Label done;
5602 
5603   // Check for evacuation-in-progress
5604   Address evacuation_in_progress = Address(r15_thread, in_bytes(JavaThread::evacuation_in_progress_offset()));
5605   cmpb(evacuation_in_progress, 0);
5606 
5607   // The read-barrier.
5608   movptr(dst, Address(dst, BrooksPointer::byte_offset()));
5609 
5610   jccb(Assembler::equal, done);
5611 
5612   if (dst != rax) {
5613     xchgptr(dst, rax); // Move obj into rax and save rax into obj.
5614   }
5615 
5616   assert(StubRoutines::x86::shenandoah_wb() != NULL, "need write barrier stub");
5617   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::shenandoah_wb())));
5618 
5619   if (dst != rax) {
5620     xchgptr(rax, dst); // Swap back obj with rax.
5621   }
5622 
5623   bind(done);
5624 }
5625 #endif // _LP64
5626 
5627 #endif // INCLUDE_ALL_GCS
5628 //////////////////////////////////////////////////////////////////////////////////
5629 
5630 
5631 void MacroAssembler::store_check(Register obj, Address dst) {
5632   store_check(obj);
5633 }
5634 
5635 void MacroAssembler::store_check(Register obj) {
5636   // Does a store check for the oop in register obj. The content of
5637   // register obj is destroyed afterwards.
5638   BarrierSet* bs = Universe::heap()->barrier_set();
5639   assert(bs->kind() == BarrierSet::CardTableForRS ||
5640          bs->kind() == BarrierSet::CardTableExtension,
5641          "Wrong barrier set kind");
5642 
5643   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5644   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5645 
5646   shrptr(obj, CardTableModRefBS::card_shift);
5647 
5648   Address card_addr;
5649 
5650   // The calculation for byte_map_base is as follows:
5651   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5652   // So this essentially converts an address to a displacement and it will
5653   // never need to be relocated. On 64bit however the value may be too
5654   // large for a 32bit displacement.
5655   intptr_t disp = (intptr_t) ct->byte_map_base;
5656   if (is_simm32(disp)) {
5657     card_addr = Address(noreg, obj, Address::times_1, disp);
5658   } else {
5659     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5660     // displacement and done in a single instruction given favorable mapping and a
5661     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5662     // entry and that entry is not properly handled by the relocation code.
5663     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5664     Address index(noreg, obj, Address::times_1);
5665     card_addr = as_Address(ArrayAddress(cardtable, index));
5666   }
5667 
5668   int dirty = CardTableModRefBS::dirty_card_val();
5669   if (UseCondCardMark) {
5670     Label L_already_dirty;
5671     if (UseConcMarkSweepGC) {
5672       membar(Assembler::StoreLoad);
5673     }
5674     cmpb(card_addr, dirty);
5675     jcc(Assembler::equal, L_already_dirty);
5676     movb(card_addr, dirty);
5677     bind(L_already_dirty);
5678   } else {
5679     movb(card_addr, dirty);
5680   }
5681 }
5682 
5683 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5684   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5685 }
5686 
5687 // Force generation of a 4 byte immediate value even if it fits into 8bit
5688 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5689   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5690 }
5691 
5692 void MacroAssembler::subptr(Register dst, Register src) {
5693   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5694 }
5695 
5696 // C++ bool manipulation
5697 void MacroAssembler::testbool(Register dst) {
5698   if(sizeof(bool) == 1)
5699     testb(dst, 0xff);
5700   else if(sizeof(bool) == 2) {
5701     // testw implementation needed for two byte bools
5702     ShouldNotReachHere();
5703   } else if(sizeof(bool) == 4)
5704     testl(dst, dst);
5705   else
5706     // unsupported
5707     ShouldNotReachHere();
5708 }
5709 
5710 void MacroAssembler::testptr(Register dst, Register src) {
5711   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5712 }
5713 
5714 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5715 void MacroAssembler::tlab_allocate(Register obj,
5716                                    Register var_size_in_bytes,
5717                                    int con_size_in_bytes,
5718                                    Register t1,
5719                                    Register t2,
5720                                    Label& slow_case) {
5721   assert_different_registers(obj, t1, t2);
5722   assert_different_registers(obj, var_size_in_bytes, t1);
5723   Register end = t2;
5724   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5725 
5726   verify_tlab();
5727 
5728   NOT_LP64(get_thread(thread));
5729 
5730   uint oop_extra_words = Universe::heap()->oop_extra_words();
5731 
5732   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5733   if (var_size_in_bytes == noreg) {
5734     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5735   } else {
5736     if (oop_extra_words > 0) {
5737       addptr(var_size_in_bytes, oop_extra_words * HeapWordSize);
5738     }
5739     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5740   }
5741   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5742   jcc(Assembler::above, slow_case);
5743 
5744   // update the tlab top pointer
5745   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5746 
5747   Universe::heap()->compile_prepare_oop(this, obj);
5748 
5749   // recover var_size_in_bytes if necessary
5750   if (var_size_in_bytes == end) {
5751     subptr(var_size_in_bytes, obj);
5752   }
5753   verify_tlab();
5754 }
5755 
5756 // Preserves rbx, and rdx.
5757 Register MacroAssembler::tlab_refill(Label& retry,
5758                                      Label& try_eden,
5759                                      Label& slow_case) {
5760   Register top = rax;
5761   Register t1  = rcx; // object size
5762   Register t2  = rsi;
5763   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5764   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5765   Label do_refill, discard_tlab;
5766 
5767   if (!Universe::heap()->supports_inline_contig_alloc()) {
5768     // No allocation in the shared eden.
5769     jmp(slow_case);
5770   }
5771 
5772   NOT_LP64(get_thread(thread_reg));
5773 
5774   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5775   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5776 
5777   // calculate amount of free space
5778   subptr(t1, top);
5779   shrptr(t1, LogHeapWordSize);
5780 
5781   // Retain tlab and allocate object in shared space if
5782   // the amount free in the tlab is too large to discard.
5783   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5784   jcc(Assembler::lessEqual, discard_tlab);
5785 
5786   // Retain
5787   // %%% yuck as movptr...
5788   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5789   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5790   if (TLABStats) {
5791     // increment number of slow_allocations
5792     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5793   }
5794   jmp(try_eden);
5795 
5796   bind(discard_tlab);
5797   if (TLABStats) {
5798     // increment number of refills
5799     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5800     // accumulate wastage -- t1 is amount free in tlab
5801     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5802   }
5803 
5804   // if tlab is currently allocated (top or end != null) then
5805   // fill [top, end + alignment_reserve) with array object
5806   testptr(top, top);
5807   jcc(Assembler::zero, do_refill);
5808 
5809   // set up the mark word
5810   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5811   // set the length to the remaining space
5812   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5813   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5814   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5815   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5816   // set klass to intArrayKlass
5817   // dubious reloc why not an oop reloc?
5818   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5819   // store klass last.  concurrent gcs assumes klass length is valid if
5820   // klass field is not null.
5821   store_klass(top, t1);
5822 
5823   movptr(t1, top);
5824   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5825   incr_allocated_bytes(thread_reg, t1, 0);
5826 
5827   // refill the tlab with an eden allocation
5828   bind(do_refill);
5829   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5830   shlptr(t1, LogHeapWordSize);
5831   // allocate new tlab, address returned in top
5832   eden_allocate(top, t1, 0, t2, slow_case);
5833 
5834   // Check that t1 was preserved in eden_allocate.
5835 #ifdef ASSERT
5836   if (UseTLAB) {
5837     Label ok;
5838     Register tsize = rsi;
5839     assert_different_registers(tsize, thread_reg, t1);
5840     push(tsize);
5841     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5842     shlptr(tsize, LogHeapWordSize);
5843     cmpptr(t1, tsize);
5844     jcc(Assembler::equal, ok);
5845     STOP("assert(t1 != tlab size)");
5846     should_not_reach_here();
5847 
5848     bind(ok);
5849     pop(tsize);
5850   }
5851 #endif
5852   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5853   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5854   addptr(top, t1);
5855   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5856   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5857 
5858   if (ZeroTLAB) {
5859     // This is a fast TLAB refill, therefore the GC is not notified of it.
5860     // So compiled code must fill the new TLAB with zeroes.
5861     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5862     zero_memory(top, t1, 0, t2);
5863   }
5864 
5865   verify_tlab();
5866   jmp(retry);
5867 
5868   return thread_reg; // for use by caller
5869 }
5870 
5871 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5872 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5873   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5874   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5875   Label done;
5876 
5877   testptr(length_in_bytes, length_in_bytes);
5878   jcc(Assembler::zero, done);
5879 
5880   // initialize topmost word, divide index by 2, check if odd and test if zero
5881   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5882 #ifdef ASSERT
5883   {
5884     Label L;
5885     testptr(length_in_bytes, BytesPerWord - 1);
5886     jcc(Assembler::zero, L);
5887     stop("length must be a multiple of BytesPerWord");
5888     bind(L);
5889   }
5890 #endif
5891   Register index = length_in_bytes;
5892   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5893   if (UseIncDec) {
5894     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5895   } else {
5896     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5897     shrptr(index, 1);
5898   }
5899 #ifndef _LP64
5900   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5901   {
5902     Label even;
5903     // note: if index was a multiple of 8, then it cannot
5904     //       be 0 now otherwise it must have been 0 before
5905     //       => if it is even, we don't need to check for 0 again
5906     jcc(Assembler::carryClear, even);
5907     // clear topmost word (no jump would be needed if conditional assignment worked here)
5908     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5909     // index could be 0 now, must check again
5910     jcc(Assembler::zero, done);
5911     bind(even);
5912   }
5913 #endif // !_LP64
5914   // initialize remaining object fields: index is a multiple of 2 now
5915   {
5916     Label loop;
5917     bind(loop);
5918     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5919     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5920     decrement(index);
5921     jcc(Assembler::notZero, loop);
5922   }
5923 
5924   bind(done);
5925 }
5926 
5927 void MacroAssembler::incr_allocated_bytes(Register thread,
5928                                           Register var_size_in_bytes,
5929                                           int con_size_in_bytes,
5930                                           Register t1) {
5931   if (!thread->is_valid()) {
5932 #ifdef _LP64
5933     thread = r15_thread;
5934 #else
5935     assert(t1->is_valid(), "need temp reg");
5936     thread = t1;
5937     get_thread(thread);
5938 #endif
5939   }
5940 
5941 #ifdef _LP64
5942   if (var_size_in_bytes->is_valid()) {
5943     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5944   } else {
5945     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5946   }
5947 #else
5948   if (var_size_in_bytes->is_valid()) {
5949     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5950   } else {
5951     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5952   }
5953   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5954 #endif
5955 }
5956 
5957 // Look up the method for a megamorphic invokeinterface call.
5958 // The target method is determined by <intf_klass, itable_index>.
5959 // The receiver klass is in recv_klass.
5960 // On success, the result will be in method_result, and execution falls through.
5961 // On failure, execution transfers to the given label.
5962 void MacroAssembler::lookup_interface_method(Register recv_klass,
5963                                              Register intf_klass,
5964                                              RegisterOrConstant itable_index,
5965                                              Register method_result,
5966                                              Register scan_temp,
5967                                              Label& L_no_such_interface) {
5968   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5969   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5970          "caller must use same register for non-constant itable index as for method");
5971 
5972   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5973   int vtable_base = in_bytes(Klass::vtable_start_offset());
5974   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5975   int scan_step   = itableOffsetEntry::size() * wordSize;
5976   int vte_size    = vtableEntry::size_in_bytes();
5977   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5978   assert(vte_size == wordSize, "else adjust times_vte_scale");
5979 
5980   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5981 
5982   // %%% Could store the aligned, prescaled offset in the klassoop.
5983   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5984 
5985   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5986   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5987   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5988 
5989   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5990   //   if (scan->interface() == intf) {
5991   //     result = (klass + scan->offset() + itable_index);
5992   //   }
5993   // }
5994   Label search, found_method;
5995 
5996   for (int peel = 1; peel >= 0; peel--) {
5997     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5998     cmpptr(intf_klass, method_result);
5999 
6000     if (peel) {
6001       jccb(Assembler::equal, found_method);
6002     } else {
6003       jccb(Assembler::notEqual, search);
6004       // (invert the test to fall through to found_method...)
6005     }
6006 
6007     if (!peel)  break;
6008 
6009     bind(search);
6010 
6011     // Check that the previous entry is non-null.  A null entry means that
6012     // the receiver class doesn't implement the interface, and wasn't the
6013     // same as when the caller was compiled.
6014     testptr(method_result, method_result);
6015     jcc(Assembler::zero, L_no_such_interface);
6016     addptr(scan_temp, scan_step);
6017   }
6018 
6019   bind(found_method);
6020 
6021   // Got a hit.
6022   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
6023   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
6024 }
6025 
6026 
6027 // virtual method calling
6028 void MacroAssembler::lookup_virtual_method(Register recv_klass,
6029                                            RegisterOrConstant vtable_index,
6030                                            Register method_result) {
6031   const int base = in_bytes(Klass::vtable_start_offset());
6032   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
6033   Address vtable_entry_addr(recv_klass,
6034                             vtable_index, Address::times_ptr,
6035                             base + vtableEntry::method_offset_in_bytes());
6036   movptr(method_result, vtable_entry_addr);
6037 }
6038 
6039 
6040 void MacroAssembler::check_klass_subtype(Register sub_klass,
6041                            Register super_klass,
6042                            Register temp_reg,
6043                            Label& L_success) {
6044   Label L_failure;
6045   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
6046   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
6047   bind(L_failure);
6048 }
6049 
6050 
6051 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
6052                                                    Register super_klass,
6053                                                    Register temp_reg,
6054                                                    Label* L_success,
6055                                                    Label* L_failure,
6056                                                    Label* L_slow_path,
6057                                         RegisterOrConstant super_check_offset) {
6058   assert_different_registers(sub_klass, super_klass, temp_reg);
6059   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
6060   if (super_check_offset.is_register()) {
6061     assert_different_registers(sub_klass, super_klass,
6062                                super_check_offset.as_register());
6063   } else if (must_load_sco) {
6064     assert(temp_reg != noreg, "supply either a temp or a register offset");
6065   }
6066 
6067   Label L_fallthrough;
6068   int label_nulls = 0;
6069   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6070   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6071   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6072   assert(label_nulls <= 1, "at most one NULL in the batch");
6073 
6074   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6075   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6076   Address super_check_offset_addr(super_klass, sco_offset);
6077 
6078   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6079   // range of a jccb.  If this routine grows larger, reconsider at
6080   // least some of these.
6081 #define local_jcc(assembler_cond, label)                                \
6082   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6083   else                             jcc( assembler_cond, label) /*omit semi*/
6084 
6085   // Hacked jmp, which may only be used just before L_fallthrough.
6086 #define final_jmp(label)                                                \
6087   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6088   else                            jmp(label)                /*omit semi*/
6089 
6090   // If the pointers are equal, we are done (e.g., String[] elements).
6091   // This self-check enables sharing of secondary supertype arrays among
6092   // non-primary types such as array-of-interface.  Otherwise, each such
6093   // type would need its own customized SSA.
6094   // We move this check to the front of the fast path because many
6095   // type checks are in fact trivially successful in this manner,
6096   // so we get a nicely predicted branch right at the start of the check.
6097   cmpptr(sub_klass, super_klass);
6098   local_jcc(Assembler::equal, *L_success);
6099 
6100   // Check the supertype display:
6101   if (must_load_sco) {
6102     // Positive movl does right thing on LP64.
6103     movl(temp_reg, super_check_offset_addr);
6104     super_check_offset = RegisterOrConstant(temp_reg);
6105   }
6106   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6107   cmpptr(super_klass, super_check_addr); // load displayed supertype
6108 
6109   // This check has worked decisively for primary supers.
6110   // Secondary supers are sought in the super_cache ('super_cache_addr').
6111   // (Secondary supers are interfaces and very deeply nested subtypes.)
6112   // This works in the same check above because of a tricky aliasing
6113   // between the super_cache and the primary super display elements.
6114   // (The 'super_check_addr' can address either, as the case requires.)
6115   // Note that the cache is updated below if it does not help us find
6116   // what we need immediately.
6117   // So if it was a primary super, we can just fail immediately.
6118   // Otherwise, it's the slow path for us (no success at this point).
6119 
6120   if (super_check_offset.is_register()) {
6121     local_jcc(Assembler::equal, *L_success);
6122     cmpl(super_check_offset.as_register(), sc_offset);
6123     if (L_failure == &L_fallthrough) {
6124       local_jcc(Assembler::equal, *L_slow_path);
6125     } else {
6126       local_jcc(Assembler::notEqual, *L_failure);
6127       final_jmp(*L_slow_path);
6128     }
6129   } else if (super_check_offset.as_constant() == sc_offset) {
6130     // Need a slow path; fast failure is impossible.
6131     if (L_slow_path == &L_fallthrough) {
6132       local_jcc(Assembler::equal, *L_success);
6133     } else {
6134       local_jcc(Assembler::notEqual, *L_slow_path);
6135       final_jmp(*L_success);
6136     }
6137   } else {
6138     // No slow path; it's a fast decision.
6139     if (L_failure == &L_fallthrough) {
6140       local_jcc(Assembler::equal, *L_success);
6141     } else {
6142       local_jcc(Assembler::notEqual, *L_failure);
6143       final_jmp(*L_success);
6144     }
6145   }
6146 
6147   bind(L_fallthrough);
6148 
6149 #undef local_jcc
6150 #undef final_jmp
6151 }
6152 
6153 
6154 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6155                                                    Register super_klass,
6156                                                    Register temp_reg,
6157                                                    Register temp2_reg,
6158                                                    Label* L_success,
6159                                                    Label* L_failure,
6160                                                    bool set_cond_codes) {
6161   assert_different_registers(sub_klass, super_klass, temp_reg);
6162   if (temp2_reg != noreg)
6163     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6164 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6165 
6166   Label L_fallthrough;
6167   int label_nulls = 0;
6168   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6169   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6170   assert(label_nulls <= 1, "at most one NULL in the batch");
6171 
6172   // a couple of useful fields in sub_klass:
6173   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6174   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6175   Address secondary_supers_addr(sub_klass, ss_offset);
6176   Address super_cache_addr(     sub_klass, sc_offset);
6177 
6178   // Do a linear scan of the secondary super-klass chain.
6179   // This code is rarely used, so simplicity is a virtue here.
6180   // The repne_scan instruction uses fixed registers, which we must spill.
6181   // Don't worry too much about pre-existing connections with the input regs.
6182 
6183   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6184   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6185 
6186   // Get super_klass value into rax (even if it was in rdi or rcx).
6187   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6188   if (super_klass != rax || UseCompressedOops) {
6189     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6190     mov(rax, super_klass);
6191   }
6192   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6193   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6194 
6195 #ifndef PRODUCT
6196   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6197   ExternalAddress pst_counter_addr((address) pst_counter);
6198   NOT_LP64(  incrementl(pst_counter_addr) );
6199   LP64_ONLY( lea(rcx, pst_counter_addr) );
6200   LP64_ONLY( incrementl(Address(rcx, 0)) );
6201 #endif //PRODUCT
6202 
6203   // We will consult the secondary-super array.
6204   movptr(rdi, secondary_supers_addr);
6205   // Load the array length.  (Positive movl does right thing on LP64.)
6206   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6207   // Skip to start of data.
6208   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6209 
6210   // Scan RCX words at [RDI] for an occurrence of RAX.
6211   // Set NZ/Z based on last compare.
6212   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6213   // not change flags (only scas instruction which is repeated sets flags).
6214   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6215 
6216     testptr(rax,rax); // Set Z = 0
6217     repne_scan();
6218 
6219   // Unspill the temp. registers:
6220   if (pushed_rdi)  pop(rdi);
6221   if (pushed_rcx)  pop(rcx);
6222   if (pushed_rax)  pop(rax);
6223 
6224   if (set_cond_codes) {
6225     // Special hack for the AD files:  rdi is guaranteed non-zero.
6226     assert(!pushed_rdi, "rdi must be left non-NULL");
6227     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6228   }
6229 
6230   if (L_failure == &L_fallthrough)
6231         jccb(Assembler::notEqual, *L_failure);
6232   else  jcc(Assembler::notEqual, *L_failure);
6233 
6234   // Success.  Cache the super we found and proceed in triumph.
6235   movptr(super_cache_addr, super_klass);
6236 
6237   if (L_success != &L_fallthrough) {
6238     jmp(*L_success);
6239   }
6240 
6241 #undef IS_A_TEMP
6242 
6243   bind(L_fallthrough);
6244 }
6245 
6246 
6247 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6248   if (VM_Version::supports_cmov()) {
6249     cmovl(cc, dst, src);
6250   } else {
6251     Label L;
6252     jccb(negate_condition(cc), L);
6253     movl(dst, src);
6254     bind(L);
6255   }
6256 }
6257 
6258 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6259   if (VM_Version::supports_cmov()) {
6260     cmovl(cc, dst, src);
6261   } else {
6262     Label L;
6263     jccb(negate_condition(cc), L);
6264     movl(dst, src);
6265     bind(L);
6266   }
6267 }
6268 
6269 void MacroAssembler::verify_oop(Register reg, const char* s) {
6270   if (!VerifyOops) return;
6271 
6272   // Pass register number to verify_oop_subroutine
6273   const char* b = NULL;
6274   {
6275     ResourceMark rm;
6276     stringStream ss;
6277     ss.print("verify_oop: %s: %s", reg->name(), s);
6278     b = code_string(ss.as_string());
6279   }
6280   BLOCK_COMMENT("verify_oop {");
6281 #ifdef _LP64
6282   push(rscratch1);                    // save r10, trashed by movptr()
6283 #endif
6284   push(rax);                          // save rax,
6285   push(reg);                          // pass register argument
6286   ExternalAddress buffer((address) b);
6287   // avoid using pushptr, as it modifies scratch registers
6288   // and our contract is not to modify anything
6289   movptr(rax, buffer.addr());
6290   push(rax);
6291   // call indirectly to solve generation ordering problem
6292   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6293   call(rax);
6294   // Caller pops the arguments (oop, message) and restores rax, r10
6295   BLOCK_COMMENT("} verify_oop");
6296 }
6297 
6298 
6299 void MacroAssembler::shenandoah_in_heap_check(Register dst, Register tmp, Label& done) {
6300   // Converts dst to biased region index
6301 
6302   // Test that oop is not in to-space.
6303   shrptr(dst, ShenandoahHeapRegion::region_size_shift_jint());
6304 
6305   // Check if in bounds for cset check. This implicitly checks if target is in heap.
6306   // Since heap might not start at zero, we want to bias the low/high boundaries.
6307   uintx bias = (uintx) ShenandoahHeap::heap()->base() >> ShenandoahHeapRegion::region_size_shift();
6308   int32_t low = (int32_t) (0 + bias);
6309   int32_t high = (int32_t) (ShenandoahHeap::heap()->max_regions() + bias);
6310 
6311   cmpptr(dst, low);
6312   jccb(Assembler::below, done);
6313   cmpptr(dst, high);
6314   jccb(Assembler::aboveEqual, done);
6315 }
6316 
6317 void MacroAssembler::shenandoah_cset_check(Register dst, Register tmp, Label& done) {
6318   // Destroys dst
6319 
6320   shenandoah_in_heap_check(dst, tmp, done);
6321 
6322   movptr(tmp, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
6323   movbool(tmp, Address(tmp, dst, Address::times_1));
6324   testbool(tmp);
6325   jccb(Assembler::zero, done);
6326 
6327   // Check for cancelled GC.
6328   movptr(tmp, (intptr_t) ShenandoahHeap::cancelled_concgc_addr());
6329   movbool(tmp, Address(tmp, 0));
6330   testbool(tmp);
6331   jccb(Assembler::notZero, done);
6332 }
6333 
6334 #ifndef _LP64
6335 void MacroAssembler::shenandoah_store_addr_check(Address addr) {
6336   // Not implemented on 32-bit, pass.
6337 }
6338 void MacroAssembler::shenandoah_store_addr_check(Register dst) {
6339   // Not implemented on 32-bit, pass.
6340 }
6341 void MacroAssembler::shenandoah_store_val_check(Register dst, Register value) {
6342   // Not implemented on 32-bit, pass.
6343 }
6344 void MacroAssembler::shenandoah_store_val_check(Address dst, Register value) {
6345   // Not implemented on 32-bit, pass.
6346 }
6347 void MacroAssembler::shenandoah_lock_check(Register dst) {
6348   // Not implemented on 32-bit, pass.
6349 }
6350 #else
6351 void MacroAssembler::shenandoah_store_addr_check(Address addr) {
6352   shenandoah_store_addr_check(addr.base());
6353 }
6354 
6355 void MacroAssembler::shenandoah_store_addr_check(Register dst) {
6356   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6357   if (dst == rsp) return; // Stack-based target
6358 
6359   // This method temporarily destroys dst, but always pushes
6360   // the original values on stack, and restores them on exit.
6361 
6362   Register tmp = NULL;
6363   if (dst != rscratch1) {
6364     tmp = rscratch1;
6365   } else if (dst != rscratch2) {
6366     tmp = rscratch2;
6367   } else {
6368     guarantee(false, "able to select the temp register");
6369   }
6370 
6371   Label done;
6372 
6373   pushf();
6374   push(dst);
6375   push(tmp);
6376 
6377   // Check null.
6378   testptr(dst, dst);
6379   jcc(Assembler::zero, done);
6380 
6381   shenandoah_cset_check(dst, tmp, done);
6382 
6383   // Fail.
6384   pop(tmp);
6385   pop(dst);
6386   popf();
6387 
6388   // Stop, provoke SEGV.
6389   // Shortest way to fail VM with RIP pointing to this check.
6390   // Store dst register to clearly see what had failed.
6391   lea(tmp, ExternalAddress(badAddress));
6392   movptr(Address(tmp, 0), dst);
6393   hlt();
6394 
6395   bind(done);
6396 
6397   pop(tmp);
6398   pop(dst);
6399   popf();
6400 }
6401 
6402 void MacroAssembler::shenandoah_store_val_check(Register dst, Register value) {
6403   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6404   if (dst == rsp)   return; // Stack-based target
6405   if (value == rsp) return; // Stack-based value // TODO: Handle this.
6406 
6407   // This method temporarily destroys dst and value, but always pushes
6408   // the original values on stack, and restores them on exit.
6409 
6410   Register tmp = NULL;
6411   if (value != rscratch1 && dst != rscratch1) {
6412     tmp = rscratch1;
6413   } else if (value != rscratch2 && dst != rscratch2) {
6414     tmp = rscratch2;
6415   } else if (value != r9 && dst != r9) {
6416     tmp = r9;
6417   } else {
6418     guarantee(false, "able to select the temp register");
6419   }
6420 
6421   // Push tmp regs and flags.
6422   pushf();
6423   push(dst);
6424   push(value);
6425   push(tmp);
6426 
6427   Label done;
6428 
6429   if (ShenandoahUpdateRefsEarly) {
6430     // Do value-check only when update refs is in progress.
6431     movptr(tmp, (intptr_t) ShenandoahHeap::update_refs_in_progress_addr());
6432   } else {
6433     // Do value-check only when concurrent mark is in progress.
6434     movptr(tmp, (intptr_t) ShenandoahHeap::concurrent_mark_in_progress_addr());
6435   }
6436   movbool(tmp, Address(tmp, 0));
6437   testbool(tmp);
6438   jcc(Assembler::zero, done);
6439 
6440   // Null-check dst.
6441   testptr(dst, dst);
6442   jcc(Assembler::zero, done);
6443 
6444   // Check that dst is in heap.
6445   // Rationale: we accept offheap writes to roots, because we will fix them up
6446   // as needed later. Non-root offheap writes are unsafe anyway, allow them.
6447   shenandoah_in_heap_check(dst, tmp, done);
6448 
6449   // Null-check value.
6450   testptr(value, value);
6451   jcc(Assembler::zero, done);
6452 
6453   // Test that value oop is not in to-space.
6454   shenandoah_cset_check(value, tmp, done);
6455 
6456   // Fail.
6457   pop(tmp);
6458   pop(value);
6459   pop(dst);
6460   popf();
6461 
6462   // Stop, provoke SEGV.
6463   // Shortest way to fail VM with RIP pointing to this check.
6464   // Store value register to clearly see what had failed.
6465   lea(tmp, ExternalAddress(badAddress));
6466   movptr(Address(tmp, 0), value);
6467   hlt();
6468 
6469   bind(done);
6470 
6471   // Pop tmp regs and flags.
6472   pop(tmp);
6473   pop(value);
6474   pop(dst);
6475   popf();
6476 }
6477 
6478 void MacroAssembler::shenandoah_store_val_check(Address addr, Register value) {
6479   shenandoah_store_val_check(addr.base(), value);
6480 }
6481 
6482 void MacroAssembler::shenandoah_lock_check(Register dst) {
6483 #ifdef ASSERT
6484   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6485 
6486   push(r8);
6487   movptr(r8, Address(dst, BasicObjectLock::obj_offset_in_bytes()));
6488   shenandoah_store_addr_check(r8);
6489   pop(r8);
6490 #endif
6491 }
6492 #endif // _LP64
6493 
6494 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6495                                                       Register tmp,
6496                                                       int offset) {
6497   intptr_t value = *delayed_value_addr;
6498   if (value != 0)
6499     return RegisterOrConstant(value + offset);
6500 
6501   // load indirectly to solve generation ordering problem
6502   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6503 
6504 #ifdef ASSERT
6505   { Label L;
6506     testptr(tmp, tmp);
6507     if (WizardMode) {
6508       const char* buf = NULL;
6509       {
6510         ResourceMark rm;
6511         stringStream ss;
6512         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6513         buf = code_string(ss.as_string());
6514       }
6515       jcc(Assembler::notZero, L);
6516       STOP(buf);
6517     } else {
6518       jccb(Assembler::notZero, L);
6519       hlt();
6520     }
6521     bind(L);
6522   }
6523 #endif
6524 
6525   if (offset != 0)
6526     addptr(tmp, offset);
6527 
6528   return RegisterOrConstant(tmp);
6529 }
6530 
6531 
6532 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6533                                          int extra_slot_offset) {
6534   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6535   int stackElementSize = Interpreter::stackElementSize;
6536   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6537 #ifdef ASSERT
6538   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6539   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6540 #endif
6541   Register             scale_reg    = noreg;
6542   Address::ScaleFactor scale_factor = Address::no_scale;
6543   if (arg_slot.is_constant()) {
6544     offset += arg_slot.as_constant() * stackElementSize;
6545   } else {
6546     scale_reg    = arg_slot.as_register();
6547     scale_factor = Address::times(stackElementSize);
6548   }
6549   offset += wordSize;           // return PC is on stack
6550   return Address(rsp, scale_reg, scale_factor, offset);
6551 }
6552 
6553 
6554 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6555   if (!VerifyOops) return;
6556 
6557   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6558   // Pass register number to verify_oop_subroutine
6559   const char* b = NULL;
6560   {
6561     ResourceMark rm;
6562     stringStream ss;
6563     ss.print("verify_oop_addr: %s", s);
6564     b = code_string(ss.as_string());
6565   }
6566 #ifdef _LP64
6567   push(rscratch1);                    // save r10, trashed by movptr()
6568 #endif
6569   push(rax);                          // save rax,
6570   // addr may contain rsp so we will have to adjust it based on the push
6571   // we just did (and on 64 bit we do two pushes)
6572   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6573   // stores rax into addr which is backwards of what was intended.
6574   if (addr.uses(rsp)) {
6575     lea(rax, addr);
6576     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6577   } else {
6578     pushptr(addr);
6579   }
6580 
6581   ExternalAddress buffer((address) b);
6582   // pass msg argument
6583   // avoid using pushptr, as it modifies scratch registers
6584   // and our contract is not to modify anything
6585   movptr(rax, buffer.addr());
6586   push(rax);
6587 
6588   // call indirectly to solve generation ordering problem
6589   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6590   call(rax);
6591   // Caller pops the arguments (addr, message) and restores rax, r10.
6592 }
6593 
6594 void MacroAssembler::verify_tlab() {
6595 #ifdef ASSERT
6596   if (UseTLAB && VerifyOops) {
6597     Label next, ok;
6598     Register t1 = rsi;
6599     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6600 
6601     push(t1);
6602     NOT_LP64(push(thread_reg));
6603     NOT_LP64(get_thread(thread_reg));
6604 
6605     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6606     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6607     jcc(Assembler::aboveEqual, next);
6608     STOP("assert(top >= start)");
6609     should_not_reach_here();
6610 
6611     bind(next);
6612     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6613     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6614     jcc(Assembler::aboveEqual, ok);
6615     STOP("assert(top <= end)");
6616     should_not_reach_here();
6617 
6618     bind(ok);
6619     NOT_LP64(pop(thread_reg));
6620     pop(t1);
6621   }
6622 #endif
6623 }
6624 
6625 class ControlWord {
6626  public:
6627   int32_t _value;
6628 
6629   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6630   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6631   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6632   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6633   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6634   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6635   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6636   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6637 
6638   void print() const {
6639     // rounding control
6640     const char* rc;
6641     switch (rounding_control()) {
6642       case 0: rc = "round near"; break;
6643       case 1: rc = "round down"; break;
6644       case 2: rc = "round up  "; break;
6645       case 3: rc = "chop      "; break;
6646     };
6647     // precision control
6648     const char* pc;
6649     switch (precision_control()) {
6650       case 0: pc = "24 bits "; break;
6651       case 1: pc = "reserved"; break;
6652       case 2: pc = "53 bits "; break;
6653       case 3: pc = "64 bits "; break;
6654     };
6655     // flags
6656     char f[9];
6657     f[0] = ' ';
6658     f[1] = ' ';
6659     f[2] = (precision   ()) ? 'P' : 'p';
6660     f[3] = (underflow   ()) ? 'U' : 'u';
6661     f[4] = (overflow    ()) ? 'O' : 'o';
6662     f[5] = (zero_divide ()) ? 'Z' : 'z';
6663     f[6] = (denormalized()) ? 'D' : 'd';
6664     f[7] = (invalid     ()) ? 'I' : 'i';
6665     f[8] = '\x0';
6666     // output
6667     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6668   }
6669 
6670 };
6671 
6672 class StatusWord {
6673  public:
6674   int32_t _value;
6675 
6676   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6677   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6678   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6679   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6680   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6681   int  top() const                     { return  (_value >> 11) & 7      ; }
6682   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6683   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6684   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6685   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6686   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6687   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6688   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6689   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6690 
6691   void print() const {
6692     // condition codes
6693     char c[5];
6694     c[0] = (C3()) ? '3' : '-';
6695     c[1] = (C2()) ? '2' : '-';
6696     c[2] = (C1()) ? '1' : '-';
6697     c[3] = (C0()) ? '0' : '-';
6698     c[4] = '\x0';
6699     // flags
6700     char f[9];
6701     f[0] = (error_status()) ? 'E' : '-';
6702     f[1] = (stack_fault ()) ? 'S' : '-';
6703     f[2] = (precision   ()) ? 'P' : '-';
6704     f[3] = (underflow   ()) ? 'U' : '-';
6705     f[4] = (overflow    ()) ? 'O' : '-';
6706     f[5] = (zero_divide ()) ? 'Z' : '-';
6707     f[6] = (denormalized()) ? 'D' : '-';
6708     f[7] = (invalid     ()) ? 'I' : '-';
6709     f[8] = '\x0';
6710     // output
6711     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6712   }
6713 
6714 };
6715 
6716 class TagWord {
6717  public:
6718   int32_t _value;
6719 
6720   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6721 
6722   void print() const {
6723     printf("%04x", _value & 0xFFFF);
6724   }
6725 
6726 };
6727 
6728 class FPU_Register {
6729  public:
6730   int32_t _m0;
6731   int32_t _m1;
6732   int16_t _ex;
6733 
6734   bool is_indefinite() const           {
6735     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6736   }
6737 
6738   void print() const {
6739     char  sign = (_ex < 0) ? '-' : '+';
6740     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6741     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6742   };
6743 
6744 };
6745 
6746 class FPU_State {
6747  public:
6748   enum {
6749     register_size       = 10,
6750     number_of_registers =  8,
6751     register_mask       =  7
6752   };
6753 
6754   ControlWord  _control_word;
6755   StatusWord   _status_word;
6756   TagWord      _tag_word;
6757   int32_t      _error_offset;
6758   int32_t      _error_selector;
6759   int32_t      _data_offset;
6760   int32_t      _data_selector;
6761   int8_t       _register[register_size * number_of_registers];
6762 
6763   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6764   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6765 
6766   const char* tag_as_string(int tag) const {
6767     switch (tag) {
6768       case 0: return "valid";
6769       case 1: return "zero";
6770       case 2: return "special";
6771       case 3: return "empty";
6772     }
6773     ShouldNotReachHere();
6774     return NULL;
6775   }
6776 
6777   void print() const {
6778     // print computation registers
6779     { int t = _status_word.top();
6780       for (int i = 0; i < number_of_registers; i++) {
6781         int j = (i - t) & register_mask;
6782         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6783         st(j)->print();
6784         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6785       }
6786     }
6787     printf("\n");
6788     // print control registers
6789     printf("ctrl = "); _control_word.print(); printf("\n");
6790     printf("stat = "); _status_word .print(); printf("\n");
6791     printf("tags = "); _tag_word    .print(); printf("\n");
6792   }
6793 
6794 };
6795 
6796 class Flag_Register {
6797  public:
6798   int32_t _value;
6799 
6800   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6801   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6802   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6803   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6804   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6805   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6806   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6807 
6808   void print() const {
6809     // flags
6810     char f[8];
6811     f[0] = (overflow       ()) ? 'O' : '-';
6812     f[1] = (direction      ()) ? 'D' : '-';
6813     f[2] = (sign           ()) ? 'S' : '-';
6814     f[3] = (zero           ()) ? 'Z' : '-';
6815     f[4] = (auxiliary_carry()) ? 'A' : '-';
6816     f[5] = (parity         ()) ? 'P' : '-';
6817     f[6] = (carry          ()) ? 'C' : '-';
6818     f[7] = '\x0';
6819     // output
6820     printf("%08x  flags = %s", _value, f);
6821   }
6822 
6823 };
6824 
6825 class IU_Register {
6826  public:
6827   int32_t _value;
6828 
6829   void print() const {
6830     printf("%08x  %11d", _value, _value);
6831   }
6832 
6833 };
6834 
6835 class IU_State {
6836  public:
6837   Flag_Register _eflags;
6838   IU_Register   _rdi;
6839   IU_Register   _rsi;
6840   IU_Register   _rbp;
6841   IU_Register   _rsp;
6842   IU_Register   _rbx;
6843   IU_Register   _rdx;
6844   IU_Register   _rcx;
6845   IU_Register   _rax;
6846 
6847   void print() const {
6848     // computation registers
6849     printf("rax,  = "); _rax.print(); printf("\n");
6850     printf("rbx,  = "); _rbx.print(); printf("\n");
6851     printf("rcx  = "); _rcx.print(); printf("\n");
6852     printf("rdx  = "); _rdx.print(); printf("\n");
6853     printf("rdi  = "); _rdi.print(); printf("\n");
6854     printf("rsi  = "); _rsi.print(); printf("\n");
6855     printf("rbp,  = "); _rbp.print(); printf("\n");
6856     printf("rsp  = "); _rsp.print(); printf("\n");
6857     printf("\n");
6858     // control registers
6859     printf("flgs = "); _eflags.print(); printf("\n");
6860   }
6861 };
6862 
6863 
6864 class CPU_State {
6865  public:
6866   FPU_State _fpu_state;
6867   IU_State  _iu_state;
6868 
6869   void print() const {
6870     printf("--------------------------------------------------\n");
6871     _iu_state .print();
6872     printf("\n");
6873     _fpu_state.print();
6874     printf("--------------------------------------------------\n");
6875   }
6876 
6877 };
6878 
6879 
6880 static void _print_CPU_state(CPU_State* state) {
6881   state->print();
6882 };
6883 
6884 
6885 void MacroAssembler::print_CPU_state() {
6886   push_CPU_state();
6887   push(rsp);                // pass CPU state
6888   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6889   addptr(rsp, wordSize);       // discard argument
6890   pop_CPU_state();
6891 }
6892 
6893 
6894 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6895   static int counter = 0;
6896   FPU_State* fs = &state->_fpu_state;
6897   counter++;
6898   // For leaf calls, only verify that the top few elements remain empty.
6899   // We only need 1 empty at the top for C2 code.
6900   if( stack_depth < 0 ) {
6901     if( fs->tag_for_st(7) != 3 ) {
6902       printf("FPR7 not empty\n");
6903       state->print();
6904       assert(false, "error");
6905       return false;
6906     }
6907     return true;                // All other stack states do not matter
6908   }
6909 
6910   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6911          "bad FPU control word");
6912 
6913   // compute stack depth
6914   int i = 0;
6915   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6916   int d = i;
6917   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6918   // verify findings
6919   if (i != FPU_State::number_of_registers) {
6920     // stack not contiguous
6921     printf("%s: stack not contiguous at ST%d\n", s, i);
6922     state->print();
6923     assert(false, "error");
6924     return false;
6925   }
6926   // check if computed stack depth corresponds to expected stack depth
6927   if (stack_depth < 0) {
6928     // expected stack depth is -stack_depth or less
6929     if (d > -stack_depth) {
6930       // too many elements on the stack
6931       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6932       state->print();
6933       assert(false, "error");
6934       return false;
6935     }
6936   } else {
6937     // expected stack depth is stack_depth
6938     if (d != stack_depth) {
6939       // wrong stack depth
6940       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6941       state->print();
6942       assert(false, "error");
6943       return false;
6944     }
6945   }
6946   // everything is cool
6947   return true;
6948 }
6949 
6950 
6951 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6952   if (!VerifyFPU) return;
6953   push_CPU_state();
6954   push(rsp);                // pass CPU state
6955   ExternalAddress msg((address) s);
6956   // pass message string s
6957   pushptr(msg.addr());
6958   push(stack_depth);        // pass stack depth
6959   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6960   addptr(rsp, 3 * wordSize);   // discard arguments
6961   // check for error
6962   { Label L;
6963     testl(rax, rax);
6964     jcc(Assembler::notZero, L);
6965     int3();                  // break if error condition
6966     bind(L);
6967   }
6968   pop_CPU_state();
6969 }
6970 
6971 void MacroAssembler::restore_cpu_control_state_after_jni() {
6972   // Either restore the MXCSR register after returning from the JNI Call
6973   // or verify that it wasn't changed (with -Xcheck:jni flag).
6974   if (VM_Version::supports_sse()) {
6975     if (RestoreMXCSROnJNICalls) {
6976       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6977     } else if (CheckJNICalls) {
6978       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6979     }
6980   }
6981   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6982   vzeroupper();
6983 
6984 #ifndef _LP64
6985   // Either restore the x87 floating pointer control word after returning
6986   // from the JNI call or verify that it wasn't changed.
6987   if (CheckJNICalls) {
6988     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6989   }
6990 #endif // _LP64
6991 }
6992 
6993 void MacroAssembler::load_mirror(Register mirror, Register method) {
6994   // get mirror
6995   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6996   movptr(mirror, Address(method, Method::const_offset()));
6997   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6998   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6999   movptr(mirror, Address(mirror, mirror_offset));
7000 }
7001 
7002 void MacroAssembler::load_klass(Register dst, Register src) {
7003 #ifdef _LP64
7004   if (UseCompressedClassPointers) {
7005     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
7006     decode_klass_not_null(dst);
7007   } else
7008 #endif
7009     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
7010 }
7011 
7012 void MacroAssembler::load_prototype_header(Register dst, Register src) {
7013   load_klass(dst, src);
7014   movptr(dst, Address(dst, Klass::prototype_header_offset()));
7015 }
7016 
7017 void MacroAssembler::store_klass(Register dst, Register src) {
7018 #ifdef _LP64
7019   if (UseCompressedClassPointers) {
7020     encode_klass_not_null(src);
7021     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
7022   } else
7023 #endif
7024     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
7025 }
7026 
7027 void MacroAssembler::load_heap_oop(Register dst, Address src) {
7028 #ifdef _LP64
7029   // FIXME: Must change all places where we try to load the klass.
7030   if (UseCompressedOops) {
7031     movl(dst, src);
7032     decode_heap_oop(dst);
7033   } else
7034 #endif
7035     movptr(dst, src);
7036 }
7037 
7038 // Doesn't do verfication, generates fixed size code
7039 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
7040 #ifdef _LP64
7041   if (UseCompressedOops) {
7042     movl(dst, src);
7043     decode_heap_oop_not_null(dst);
7044   } else
7045 #endif
7046     movptr(dst, src);
7047 }
7048 
7049 void MacroAssembler::store_heap_oop(Address dst, Register src) {
7050 #ifdef _LP64
7051   if (UseCompressedOops) {
7052     assert(!dst.uses(src), "not enough registers");
7053     encode_heap_oop(src);
7054     movl(dst, src);
7055   } else
7056 #endif
7057     movptr(dst, src);
7058 }
7059 
7060 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
7061   assert_different_registers(src1, tmp);
7062 #ifdef _LP64
7063   if (UseCompressedOops) {
7064     bool did_push = false;
7065     if (tmp == noreg) {
7066       tmp = rax;
7067       push(tmp);
7068       did_push = true;
7069       assert(!src2.uses(rsp), "can't push");
7070     }
7071     load_heap_oop(tmp, src2);
7072     cmpptr(src1, tmp);
7073     if (did_push)  pop(tmp);
7074   } else
7075 #endif
7076     cmpptr(src1, src2);
7077 }
7078 
7079 // Used for storing NULLs.
7080 void MacroAssembler::store_heap_oop_null(Address dst) {
7081 #ifdef _LP64
7082   if (UseCompressedOops) {
7083     movl(dst, (int32_t)NULL_WORD);
7084   } else {
7085     movslq(dst, (int32_t)NULL_WORD);
7086   }
7087 #else
7088   movl(dst, (int32_t)NULL_WORD);
7089 #endif
7090 }
7091 
7092 #ifdef _LP64
7093 void MacroAssembler::store_klass_gap(Register dst, Register src) {
7094   if (UseCompressedClassPointers) {
7095     // Store to klass gap in destination
7096     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
7097   }
7098 }
7099 
7100 #ifdef ASSERT
7101 void MacroAssembler::verify_heapbase(const char* msg) {
7102   assert (UseCompressedOops, "should be compressed");
7103   assert (Universe::heap() != NULL, "java heap should be initialized");
7104   if (CheckCompressedOops) {
7105     Label ok;
7106     push(rscratch1); // cmpptr trashes rscratch1
7107     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7108     jcc(Assembler::equal, ok);
7109     STOP(msg);
7110     bind(ok);
7111     pop(rscratch1);
7112   }
7113 }
7114 #endif
7115 
7116 // Algorithm must match oop.inline.hpp encode_heap_oop.
7117 void MacroAssembler::encode_heap_oop(Register r) {
7118 #ifdef ASSERT
7119   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
7120 #endif
7121   verify_oop(r, "broken oop in encode_heap_oop");
7122   if (Universe::narrow_oop_base() == NULL) {
7123     if (Universe::narrow_oop_shift() != 0) {
7124       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7125       shrq(r, LogMinObjAlignmentInBytes);
7126     }
7127     return;
7128   }
7129   testq(r, r);
7130   cmovq(Assembler::equal, r, r12_heapbase);
7131   subq(r, r12_heapbase);
7132   shrq(r, LogMinObjAlignmentInBytes);
7133 }
7134 
7135 void MacroAssembler::encode_heap_oop_not_null(Register r) {
7136 #ifdef ASSERT
7137   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
7138   if (CheckCompressedOops) {
7139     Label ok;
7140     testq(r, r);
7141     jcc(Assembler::notEqual, ok);
7142     STOP("null oop passed to encode_heap_oop_not_null");
7143     bind(ok);
7144   }
7145 #endif
7146   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7147   if (Universe::narrow_oop_base() != NULL) {
7148     subq(r, r12_heapbase);
7149   }
7150   if (Universe::narrow_oop_shift() != 0) {
7151     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7152     shrq(r, LogMinObjAlignmentInBytes);
7153   }
7154 }
7155 
7156 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7157 #ifdef ASSERT
7158   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7159   if (CheckCompressedOops) {
7160     Label ok;
7161     testq(src, src);
7162     jcc(Assembler::notEqual, ok);
7163     STOP("null oop passed to encode_heap_oop_not_null2");
7164     bind(ok);
7165   }
7166 #endif
7167   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7168   if (dst != src) {
7169     movq(dst, src);
7170   }
7171   if (Universe::narrow_oop_base() != NULL) {
7172     subq(dst, r12_heapbase);
7173   }
7174   if (Universe::narrow_oop_shift() != 0) {
7175     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7176     shrq(dst, LogMinObjAlignmentInBytes);
7177   }
7178 }
7179 
7180 void  MacroAssembler::decode_heap_oop(Register r) {
7181 #ifdef ASSERT
7182   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7183 #endif
7184   if (Universe::narrow_oop_base() == NULL) {
7185     if (Universe::narrow_oop_shift() != 0) {
7186       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7187       shlq(r, LogMinObjAlignmentInBytes);
7188     }
7189   } else {
7190     Label done;
7191     shlq(r, LogMinObjAlignmentInBytes);
7192     jccb(Assembler::equal, done);
7193     addq(r, r12_heapbase);
7194     bind(done);
7195   }
7196   verify_oop(r, "broken oop in decode_heap_oop");
7197 }
7198 
7199 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7200   // Note: it will change flags
7201   assert (UseCompressedOops, "should only be used for compressed headers");
7202   assert (Universe::heap() != NULL, "java heap should be initialized");
7203   // Cannot assert, unverified entry point counts instructions (see .ad file)
7204   // vtableStubs also counts instructions in pd_code_size_limit.
7205   // Also do not verify_oop as this is called by verify_oop.
7206   if (Universe::narrow_oop_shift() != 0) {
7207     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7208     shlq(r, LogMinObjAlignmentInBytes);
7209     if (Universe::narrow_oop_base() != NULL) {
7210       addq(r, r12_heapbase);
7211     }
7212   } else {
7213     assert (Universe::narrow_oop_base() == NULL, "sanity");
7214   }
7215 }
7216 
7217 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7218   // Note: it will change flags
7219   assert (UseCompressedOops, "should only be used for compressed headers");
7220   assert (Universe::heap() != NULL, "java heap should be initialized");
7221   // Cannot assert, unverified entry point counts instructions (see .ad file)
7222   // vtableStubs also counts instructions in pd_code_size_limit.
7223   // Also do not verify_oop as this is called by verify_oop.
7224   if (Universe::narrow_oop_shift() != 0) {
7225     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7226     if (LogMinObjAlignmentInBytes == Address::times_8) {
7227       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7228     } else {
7229       if (dst != src) {
7230         movq(dst, src);
7231       }
7232       shlq(dst, LogMinObjAlignmentInBytes);
7233       if (Universe::narrow_oop_base() != NULL) {
7234         addq(dst, r12_heapbase);
7235       }
7236     }
7237   } else {
7238     assert (Universe::narrow_oop_base() == NULL, "sanity");
7239     if (dst != src) {
7240       movq(dst, src);
7241     }
7242   }
7243 }
7244 
7245 void MacroAssembler::encode_klass_not_null(Register r) {
7246   if (Universe::narrow_klass_base() != NULL) {
7247     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7248     assert(r != r12_heapbase, "Encoding a klass in r12");
7249     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7250     subq(r, r12_heapbase);
7251   }
7252   if (Universe::narrow_klass_shift() != 0) {
7253     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7254     shrq(r, LogKlassAlignmentInBytes);
7255   }
7256   if (Universe::narrow_klass_base() != NULL) {
7257     reinit_heapbase();
7258   }
7259 }
7260 
7261 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7262   if (dst == src) {
7263     encode_klass_not_null(src);
7264   } else {
7265     if (Universe::narrow_klass_base() != NULL) {
7266       mov64(dst, (int64_t)Universe::narrow_klass_base());
7267       negq(dst);
7268       addq(dst, src);
7269     } else {
7270       movptr(dst, src);
7271     }
7272     if (Universe::narrow_klass_shift() != 0) {
7273       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7274       shrq(dst, LogKlassAlignmentInBytes);
7275     }
7276   }
7277 }
7278 
7279 // Function instr_size_for_decode_klass_not_null() counts the instructions
7280 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7281 // when (Universe::heap() != NULL).  Hence, if the instructions they
7282 // generate change, then this method needs to be updated.
7283 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7284   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7285   if (Universe::narrow_klass_base() != NULL) {
7286     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7287     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7288   } else {
7289     // longest load decode klass function, mov64, leaq
7290     return 16;
7291   }
7292 }
7293 
7294 // !!! If the instructions that get generated here change then function
7295 // instr_size_for_decode_klass_not_null() needs to get updated.
7296 void  MacroAssembler::decode_klass_not_null(Register r) {
7297   // Note: it will change flags
7298   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7299   assert(r != r12_heapbase, "Decoding a klass in r12");
7300   // Cannot assert, unverified entry point counts instructions (see .ad file)
7301   // vtableStubs also counts instructions in pd_code_size_limit.
7302   // Also do not verify_oop as this is called by verify_oop.
7303   if (Universe::narrow_klass_shift() != 0) {
7304     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7305     shlq(r, LogKlassAlignmentInBytes);
7306   }
7307   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7308   if (Universe::narrow_klass_base() != NULL) {
7309     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7310     addq(r, r12_heapbase);
7311     reinit_heapbase();
7312   }
7313 }
7314 
7315 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7316   // Note: it will change flags
7317   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7318   if (dst == src) {
7319     decode_klass_not_null(dst);
7320   } else {
7321     // Cannot assert, unverified entry point counts instructions (see .ad file)
7322     // vtableStubs also counts instructions in pd_code_size_limit.
7323     // Also do not verify_oop as this is called by verify_oop.
7324     mov64(dst, (int64_t)Universe::narrow_klass_base());
7325     if (Universe::narrow_klass_shift() != 0) {
7326       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7327       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7328       leaq(dst, Address(dst, src, Address::times_8, 0));
7329     } else {
7330       addq(dst, src);
7331     }
7332   }
7333 }
7334 
7335 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7336   assert (UseCompressedOops, "should only be used for compressed headers");
7337   assert (Universe::heap() != NULL, "java heap should be initialized");
7338   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7339   int oop_index = oop_recorder()->find_index(obj);
7340   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7341   mov_narrow_oop(dst, oop_index, rspec);
7342 }
7343 
7344 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7345   assert (UseCompressedOops, "should only be used for compressed headers");
7346   assert (Universe::heap() != NULL, "java heap should be initialized");
7347   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7348   int oop_index = oop_recorder()->find_index(obj);
7349   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7350   mov_narrow_oop(dst, oop_index, rspec);
7351 }
7352 
7353 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7354   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7355   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7356   int klass_index = oop_recorder()->find_index(k);
7357   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7358   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7359 }
7360 
7361 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7362   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7363   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7364   int klass_index = oop_recorder()->find_index(k);
7365   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7366   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7367 }
7368 
7369 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7370   assert (UseCompressedOops, "should only be used for compressed headers");
7371   assert (Universe::heap() != NULL, "java heap should be initialized");
7372   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7373   int oop_index = oop_recorder()->find_index(obj);
7374   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7375   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7376 }
7377 
7378 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7379   assert (UseCompressedOops, "should only be used for compressed headers");
7380   assert (Universe::heap() != NULL, "java heap should be initialized");
7381   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7382   int oop_index = oop_recorder()->find_index(obj);
7383   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7384   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7385 }
7386 
7387 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7388   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7389   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7390   int klass_index = oop_recorder()->find_index(k);
7391   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7392   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7393 }
7394 
7395 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7396   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7397   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7398   int klass_index = oop_recorder()->find_index(k);
7399   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7400   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7401 }
7402 
7403 void MacroAssembler::reinit_heapbase() {
7404   if (UseCompressedOops || UseCompressedClassPointers) {
7405     if (Universe::heap() != NULL) {
7406       if (Universe::narrow_oop_base() == NULL) {
7407         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7408       } else {
7409         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7410       }
7411     } else {
7412       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7413     }
7414   }
7415 }
7416 
7417 #endif // _LP64
7418 
7419 
7420 // C2 compiled method's prolog code.
7421 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7422 
7423   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7424   // NativeJump::patch_verified_entry will be able to patch out the entry
7425   // code safely. The push to verify stack depth is ok at 5 bytes,
7426   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7427   // stack bang then we must use the 6 byte frame allocation even if
7428   // we have no frame. :-(
7429   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7430 
7431   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7432   // Remove word for return addr
7433   framesize -= wordSize;
7434   stack_bang_size -= wordSize;
7435 
7436   // Calls to C2R adapters often do not accept exceptional returns.
7437   // We require that their callers must bang for them.  But be careful, because
7438   // some VM calls (such as call site linkage) can use several kilobytes of
7439   // stack.  But the stack safety zone should account for that.
7440   // See bugs 4446381, 4468289, 4497237.
7441   if (stack_bang_size > 0) {
7442     generate_stack_overflow_check(stack_bang_size);
7443 
7444     // We always push rbp, so that on return to interpreter rbp, will be
7445     // restored correctly and we can correct the stack.
7446     push(rbp);
7447     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7448     if (PreserveFramePointer) {
7449       mov(rbp, rsp);
7450     }
7451     // Remove word for ebp
7452     framesize -= wordSize;
7453 
7454     // Create frame
7455     if (framesize) {
7456       subptr(rsp, framesize);
7457     }
7458   } else {
7459     // Create frame (force generation of a 4 byte immediate value)
7460     subptr_imm32(rsp, framesize);
7461 
7462     // Save RBP register now.
7463     framesize -= wordSize;
7464     movptr(Address(rsp, framesize), rbp);
7465     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7466     if (PreserveFramePointer) {
7467       movptr(rbp, rsp);
7468       if (framesize > 0) {
7469         addptr(rbp, framesize);
7470       }
7471     }
7472   }
7473 
7474   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7475     framesize -= wordSize;
7476     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7477   }
7478 
7479 #ifndef _LP64
7480   // If method sets FPU control word do it now
7481   if (fp_mode_24b) {
7482     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7483   }
7484   if (UseSSE >= 2 && VerifyFPU) {
7485     verify_FPU(0, "FPU stack must be clean on entry");
7486   }
7487 #endif
7488 
7489 #ifdef ASSERT
7490   if (VerifyStackAtCalls) {
7491     Label L;
7492     push(rax);
7493     mov(rax, rsp);
7494     andptr(rax, StackAlignmentInBytes-1);
7495     cmpptr(rax, StackAlignmentInBytes-wordSize);
7496     pop(rax);
7497     jcc(Assembler::equal, L);
7498     STOP("Stack is not properly aligned!");
7499     bind(L);
7500   }
7501 #endif
7502 
7503 }
7504 
7505 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7506   // cnt - number of qwords (8-byte words).
7507   // base - start address, qword aligned.
7508   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7509   assert(base==rdi, "base register must be edi for rep stos");
7510   assert(tmp==rax,   "tmp register must be eax for rep stos");
7511   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7512   assert(InitArrayShortSize % BytesPerLong == 0,
7513     "InitArrayShortSize should be the multiple of BytesPerLong");
7514 
7515   Label DONE;
7516 
7517   xorptr(tmp, tmp);
7518 
7519   if (!is_large) {
7520     Label LOOP, LONG;
7521     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7522     jccb(Assembler::greater, LONG);
7523 
7524     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7525 
7526     decrement(cnt);
7527     jccb(Assembler::negative, DONE); // Zero length
7528 
7529     // Use individual pointer-sized stores for small counts:
7530     BIND(LOOP);
7531     movptr(Address(base, cnt, Address::times_ptr), tmp);
7532     decrement(cnt);
7533     jccb(Assembler::greaterEqual, LOOP);
7534     jmpb(DONE);
7535 
7536     BIND(LONG);
7537   }
7538 
7539   // Use longer rep-prefixed ops for non-small counts:
7540   if (UseFastStosb) {
7541     shlptr(cnt, 3); // convert to number of bytes
7542     rep_stosb();
7543   } else {
7544     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7545     rep_stos();
7546   }
7547 
7548   BIND(DONE);
7549 }
7550 
7551 #ifdef COMPILER2
7552 
7553 // IndexOf for constant substrings with size >= 8 chars
7554 // which don't need to be loaded through stack.
7555 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7556                                       Register cnt1, Register cnt2,
7557                                       int int_cnt2,  Register result,
7558                                       XMMRegister vec, Register tmp,
7559                                       int ae) {
7560   ShortBranchVerifier sbv(this);
7561   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7562   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7563 
7564   // This method uses the pcmpestri instruction with bound registers
7565   //   inputs:
7566   //     xmm - substring
7567   //     rax - substring length (elements count)
7568   //     mem - scanned string
7569   //     rdx - string length (elements count)
7570   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7571   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7572   //   outputs:
7573   //     rcx - matched index in string
7574   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7575   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7576   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7577   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7578   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7579 
7580   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7581         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7582         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7583 
7584   // Note, inline_string_indexOf() generates checks:
7585   // if (substr.count > string.count) return -1;
7586   // if (substr.count == 0) return 0;
7587   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7588 
7589   // Load substring.
7590   if (ae == StrIntrinsicNode::UL) {
7591     pmovzxbw(vec, Address(str2, 0));
7592   } else {
7593     movdqu(vec, Address(str2, 0));
7594   }
7595   movl(cnt2, int_cnt2);
7596   movptr(result, str1); // string addr
7597 
7598   if (int_cnt2 > stride) {
7599     jmpb(SCAN_TO_SUBSTR);
7600 
7601     // Reload substr for rescan, this code
7602     // is executed only for large substrings (> 8 chars)
7603     bind(RELOAD_SUBSTR);
7604     if (ae == StrIntrinsicNode::UL) {
7605       pmovzxbw(vec, Address(str2, 0));
7606     } else {
7607       movdqu(vec, Address(str2, 0));
7608     }
7609     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7610 
7611     bind(RELOAD_STR);
7612     // We came here after the beginning of the substring was
7613     // matched but the rest of it was not so we need to search
7614     // again. Start from the next element after the previous match.
7615 
7616     // cnt2 is number of substring reminding elements and
7617     // cnt1 is number of string reminding elements when cmp failed.
7618     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7619     subl(cnt1, cnt2);
7620     addl(cnt1, int_cnt2);
7621     movl(cnt2, int_cnt2); // Now restore cnt2
7622 
7623     decrementl(cnt1);     // Shift to next element
7624     cmpl(cnt1, cnt2);
7625     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7626 
7627     addptr(result, (1<<scale1));
7628 
7629   } // (int_cnt2 > 8)
7630 
7631   // Scan string for start of substr in 16-byte vectors
7632   bind(SCAN_TO_SUBSTR);
7633   pcmpestri(vec, Address(result, 0), mode);
7634   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7635   subl(cnt1, stride);
7636   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7637   cmpl(cnt1, cnt2);
7638   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7639   addptr(result, 16);
7640   jmpb(SCAN_TO_SUBSTR);
7641 
7642   // Found a potential substr
7643   bind(FOUND_CANDIDATE);
7644   // Matched whole vector if first element matched (tmp(rcx) == 0).
7645   if (int_cnt2 == stride) {
7646     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7647   } else { // int_cnt2 > 8
7648     jccb(Assembler::overflow, FOUND_SUBSTR);
7649   }
7650   // After pcmpestri tmp(rcx) contains matched element index
7651   // Compute start addr of substr
7652   lea(result, Address(result, tmp, scale1));
7653 
7654   // Make sure string is still long enough
7655   subl(cnt1, tmp);
7656   cmpl(cnt1, cnt2);
7657   if (int_cnt2 == stride) {
7658     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7659   } else { // int_cnt2 > 8
7660     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7661   }
7662   // Left less then substring.
7663 
7664   bind(RET_NOT_FOUND);
7665   movl(result, -1);
7666   jmp(EXIT);
7667 
7668   if (int_cnt2 > stride) {
7669     // This code is optimized for the case when whole substring
7670     // is matched if its head is matched.
7671     bind(MATCH_SUBSTR_HEAD);
7672     pcmpestri(vec, Address(result, 0), mode);
7673     // Reload only string if does not match
7674     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7675 
7676     Label CONT_SCAN_SUBSTR;
7677     // Compare the rest of substring (> 8 chars).
7678     bind(FOUND_SUBSTR);
7679     // First 8 chars are already matched.
7680     negptr(cnt2);
7681     addptr(cnt2, stride);
7682 
7683     bind(SCAN_SUBSTR);
7684     subl(cnt1, stride);
7685     cmpl(cnt2, -stride); // Do not read beyond substring
7686     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7687     // Back-up strings to avoid reading beyond substring:
7688     // cnt1 = cnt1 - cnt2 + 8
7689     addl(cnt1, cnt2); // cnt2 is negative
7690     addl(cnt1, stride);
7691     movl(cnt2, stride); negptr(cnt2);
7692     bind(CONT_SCAN_SUBSTR);
7693     if (int_cnt2 < (int)G) {
7694       int tail_off1 = int_cnt2<<scale1;
7695       int tail_off2 = int_cnt2<<scale2;
7696       if (ae == StrIntrinsicNode::UL) {
7697         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7698       } else {
7699         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7700       }
7701       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7702     } else {
7703       // calculate index in register to avoid integer overflow (int_cnt2*2)
7704       movl(tmp, int_cnt2);
7705       addptr(tmp, cnt2);
7706       if (ae == StrIntrinsicNode::UL) {
7707         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7708       } else {
7709         movdqu(vec, Address(str2, tmp, scale2, 0));
7710       }
7711       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7712     }
7713     // Need to reload strings pointers if not matched whole vector
7714     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7715     addptr(cnt2, stride);
7716     jcc(Assembler::negative, SCAN_SUBSTR);
7717     // Fall through if found full substring
7718 
7719   } // (int_cnt2 > 8)
7720 
7721   bind(RET_FOUND);
7722   // Found result if we matched full small substring.
7723   // Compute substr offset
7724   subptr(result, str1);
7725   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7726     shrl(result, 1); // index
7727   }
7728   bind(EXIT);
7729 
7730 } // string_indexofC8
7731 
7732 // Small strings are loaded through stack if they cross page boundary.
7733 void MacroAssembler::string_indexof(Register str1, Register str2,
7734                                     Register cnt1, Register cnt2,
7735                                     int int_cnt2,  Register result,
7736                                     XMMRegister vec, Register tmp,
7737                                     int ae) {
7738   ShortBranchVerifier sbv(this);
7739   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7740   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7741 
7742   //
7743   // int_cnt2 is length of small (< 8 chars) constant substring
7744   // or (-1) for non constant substring in which case its length
7745   // is in cnt2 register.
7746   //
7747   // Note, inline_string_indexOf() generates checks:
7748   // if (substr.count > string.count) return -1;
7749   // if (substr.count == 0) return 0;
7750   //
7751   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7752   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7753   // This method uses the pcmpestri instruction with bound registers
7754   //   inputs:
7755   //     xmm - substring
7756   //     rax - substring length (elements count)
7757   //     mem - scanned string
7758   //     rdx - string length (elements count)
7759   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7760   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7761   //   outputs:
7762   //     rcx - matched index in string
7763   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7764   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7765   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7766   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7767 
7768   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7769         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7770         FOUND_CANDIDATE;
7771 
7772   { //========================================================
7773     // We don't know where these strings are located
7774     // and we can't read beyond them. Load them through stack.
7775     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7776 
7777     movptr(tmp, rsp); // save old SP
7778 
7779     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7780       if (int_cnt2 == (1>>scale2)) { // One byte
7781         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7782         load_unsigned_byte(result, Address(str2, 0));
7783         movdl(vec, result); // move 32 bits
7784       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7785         // Not enough header space in 32-bit VM: 12+3 = 15.
7786         movl(result, Address(str2, -1));
7787         shrl(result, 8);
7788         movdl(vec, result); // move 32 bits
7789       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7790         load_unsigned_short(result, Address(str2, 0));
7791         movdl(vec, result); // move 32 bits
7792       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7793         movdl(vec, Address(str2, 0)); // move 32 bits
7794       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7795         movq(vec, Address(str2, 0));  // move 64 bits
7796       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7797         // Array header size is 12 bytes in 32-bit VM
7798         // + 6 bytes for 3 chars == 18 bytes,
7799         // enough space to load vec and shift.
7800         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7801         if (ae == StrIntrinsicNode::UL) {
7802           int tail_off = int_cnt2-8;
7803           pmovzxbw(vec, Address(str2, tail_off));
7804           psrldq(vec, -2*tail_off);
7805         }
7806         else {
7807           int tail_off = int_cnt2*(1<<scale2);
7808           movdqu(vec, Address(str2, tail_off-16));
7809           psrldq(vec, 16-tail_off);
7810         }
7811       }
7812     } else { // not constant substring
7813       cmpl(cnt2, stride);
7814       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7815 
7816       // We can read beyond string if srt+16 does not cross page boundary
7817       // since heaps are aligned and mapped by pages.
7818       assert(os::vm_page_size() < (int)G, "default page should be small");
7819       movl(result, str2); // We need only low 32 bits
7820       andl(result, (os::vm_page_size()-1));
7821       cmpl(result, (os::vm_page_size()-16));
7822       jccb(Assembler::belowEqual, CHECK_STR);
7823 
7824       // Move small strings to stack to allow load 16 bytes into vec.
7825       subptr(rsp, 16);
7826       int stk_offset = wordSize-(1<<scale2);
7827       push(cnt2);
7828 
7829       bind(COPY_SUBSTR);
7830       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7831         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7832         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7833       } else if (ae == StrIntrinsicNode::UU) {
7834         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7835         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7836       }
7837       decrement(cnt2);
7838       jccb(Assembler::notZero, COPY_SUBSTR);
7839 
7840       pop(cnt2);
7841       movptr(str2, rsp);  // New substring address
7842     } // non constant
7843 
7844     bind(CHECK_STR);
7845     cmpl(cnt1, stride);
7846     jccb(Assembler::aboveEqual, BIG_STRINGS);
7847 
7848     // Check cross page boundary.
7849     movl(result, str1); // We need only low 32 bits
7850     andl(result, (os::vm_page_size()-1));
7851     cmpl(result, (os::vm_page_size()-16));
7852     jccb(Assembler::belowEqual, BIG_STRINGS);
7853 
7854     subptr(rsp, 16);
7855     int stk_offset = -(1<<scale1);
7856     if (int_cnt2 < 0) { // not constant
7857       push(cnt2);
7858       stk_offset += wordSize;
7859     }
7860     movl(cnt2, cnt1);
7861 
7862     bind(COPY_STR);
7863     if (ae == StrIntrinsicNode::LL) {
7864       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7865       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7866     } else {
7867       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7868       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7869     }
7870     decrement(cnt2);
7871     jccb(Assembler::notZero, COPY_STR);
7872 
7873     if (int_cnt2 < 0) { // not constant
7874       pop(cnt2);
7875     }
7876     movptr(str1, rsp);  // New string address
7877 
7878     bind(BIG_STRINGS);
7879     // Load substring.
7880     if (int_cnt2 < 0) { // -1
7881       if (ae == StrIntrinsicNode::UL) {
7882         pmovzxbw(vec, Address(str2, 0));
7883       } else {
7884         movdqu(vec, Address(str2, 0));
7885       }
7886       push(cnt2);       // substr count
7887       push(str2);       // substr addr
7888       push(str1);       // string addr
7889     } else {
7890       // Small (< 8 chars) constant substrings are loaded already.
7891       movl(cnt2, int_cnt2);
7892     }
7893     push(tmp);  // original SP
7894 
7895   } // Finished loading
7896 
7897   //========================================================
7898   // Start search
7899   //
7900 
7901   movptr(result, str1); // string addr
7902 
7903   if (int_cnt2  < 0) {  // Only for non constant substring
7904     jmpb(SCAN_TO_SUBSTR);
7905 
7906     // SP saved at sp+0
7907     // String saved at sp+1*wordSize
7908     // Substr saved at sp+2*wordSize
7909     // Substr count saved at sp+3*wordSize
7910 
7911     // Reload substr for rescan, this code
7912     // is executed only for large substrings (> 8 chars)
7913     bind(RELOAD_SUBSTR);
7914     movptr(str2, Address(rsp, 2*wordSize));
7915     movl(cnt2, Address(rsp, 3*wordSize));
7916     if (ae == StrIntrinsicNode::UL) {
7917       pmovzxbw(vec, Address(str2, 0));
7918     } else {
7919       movdqu(vec, Address(str2, 0));
7920     }
7921     // We came here after the beginning of the substring was
7922     // matched but the rest of it was not so we need to search
7923     // again. Start from the next element after the previous match.
7924     subptr(str1, result); // Restore counter
7925     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7926       shrl(str1, 1);
7927     }
7928     addl(cnt1, str1);
7929     decrementl(cnt1);   // Shift to next element
7930     cmpl(cnt1, cnt2);
7931     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7932 
7933     addptr(result, (1<<scale1));
7934   } // non constant
7935 
7936   // Scan string for start of substr in 16-byte vectors
7937   bind(SCAN_TO_SUBSTR);
7938   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7939   pcmpestri(vec, Address(result, 0), mode);
7940   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7941   subl(cnt1, stride);
7942   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7943   cmpl(cnt1, cnt2);
7944   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7945   addptr(result, 16);
7946 
7947   bind(ADJUST_STR);
7948   cmpl(cnt1, stride); // Do not read beyond string
7949   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7950   // Back-up string to avoid reading beyond string.
7951   lea(result, Address(result, cnt1, scale1, -16));
7952   movl(cnt1, stride);
7953   jmpb(SCAN_TO_SUBSTR);
7954 
7955   // Found a potential substr
7956   bind(FOUND_CANDIDATE);
7957   // After pcmpestri tmp(rcx) contains matched element index
7958 
7959   // Make sure string is still long enough
7960   subl(cnt1, tmp);
7961   cmpl(cnt1, cnt2);
7962   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7963   // Left less then substring.
7964 
7965   bind(RET_NOT_FOUND);
7966   movl(result, -1);
7967   jmpb(CLEANUP);
7968 
7969   bind(FOUND_SUBSTR);
7970   // Compute start addr of substr
7971   lea(result, Address(result, tmp, scale1));
7972   if (int_cnt2 > 0) { // Constant substring
7973     // Repeat search for small substring (< 8 chars)
7974     // from new point without reloading substring.
7975     // Have to check that we don't read beyond string.
7976     cmpl(tmp, stride-int_cnt2);
7977     jccb(Assembler::greater, ADJUST_STR);
7978     // Fall through if matched whole substring.
7979   } else { // non constant
7980     assert(int_cnt2 == -1, "should be != 0");
7981 
7982     addl(tmp, cnt2);
7983     // Found result if we matched whole substring.
7984     cmpl(tmp, stride);
7985     jccb(Assembler::lessEqual, RET_FOUND);
7986 
7987     // Repeat search for small substring (<= 8 chars)
7988     // from new point 'str1' without reloading substring.
7989     cmpl(cnt2, stride);
7990     // Have to check that we don't read beyond string.
7991     jccb(Assembler::lessEqual, ADJUST_STR);
7992 
7993     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7994     // Compare the rest of substring (> 8 chars).
7995     movptr(str1, result);
7996 
7997     cmpl(tmp, cnt2);
7998     // First 8 chars are already matched.
7999     jccb(Assembler::equal, CHECK_NEXT);
8000 
8001     bind(SCAN_SUBSTR);
8002     pcmpestri(vec, Address(str1, 0), mode);
8003     // Need to reload strings pointers if not matched whole vector
8004     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
8005 
8006     bind(CHECK_NEXT);
8007     subl(cnt2, stride);
8008     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
8009     addptr(str1, 16);
8010     if (ae == StrIntrinsicNode::UL) {
8011       addptr(str2, 8);
8012     } else {
8013       addptr(str2, 16);
8014     }
8015     subl(cnt1, stride);
8016     cmpl(cnt2, stride); // Do not read beyond substring
8017     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
8018     // Back-up strings to avoid reading beyond substring.
8019 
8020     if (ae == StrIntrinsicNode::UL) {
8021       lea(str2, Address(str2, cnt2, scale2, -8));
8022       lea(str1, Address(str1, cnt2, scale1, -16));
8023     } else {
8024       lea(str2, Address(str2, cnt2, scale2, -16));
8025       lea(str1, Address(str1, cnt2, scale1, -16));
8026     }
8027     subl(cnt1, cnt2);
8028     movl(cnt2, stride);
8029     addl(cnt1, stride);
8030     bind(CONT_SCAN_SUBSTR);
8031     if (ae == StrIntrinsicNode::UL) {
8032       pmovzxbw(vec, Address(str2, 0));
8033     } else {
8034       movdqu(vec, Address(str2, 0));
8035     }
8036     jmp(SCAN_SUBSTR);
8037 
8038     bind(RET_FOUND_LONG);
8039     movptr(str1, Address(rsp, wordSize));
8040   } // non constant
8041 
8042   bind(RET_FOUND);
8043   // Compute substr offset
8044   subptr(result, str1);
8045   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
8046     shrl(result, 1); // index
8047   }
8048   bind(CLEANUP);
8049   pop(rsp); // restore SP
8050 
8051 } // string_indexof
8052 
8053 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
8054                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
8055   ShortBranchVerifier sbv(this);
8056   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
8057 
8058   int stride = 8;
8059 
8060   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
8061         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
8062         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
8063         FOUND_SEQ_CHAR, DONE_LABEL;
8064 
8065   movptr(result, str1);
8066   if (UseAVX >= 2) {
8067     cmpl(cnt1, stride);
8068     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8069     cmpl(cnt1, 2*stride);
8070     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
8071     movdl(vec1, ch);
8072     vpbroadcastw(vec1, vec1);
8073     vpxor(vec2, vec2);
8074     movl(tmp, cnt1);
8075     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
8076     andl(cnt1,0x0000000F);  //tail count (in chars)
8077 
8078     bind(SCAN_TO_16_CHAR_LOOP);
8079     vmovdqu(vec3, Address(result, 0));
8080     vpcmpeqw(vec3, vec3, vec1, 1);
8081     vptest(vec2, vec3);
8082     jcc(Assembler::carryClear, FOUND_CHAR);
8083     addptr(result, 32);
8084     subl(tmp, 2*stride);
8085     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
8086     jmp(SCAN_TO_8_CHAR);
8087     bind(SCAN_TO_8_CHAR_INIT);
8088     movdl(vec1, ch);
8089     pshuflw(vec1, vec1, 0x00);
8090     pshufd(vec1, vec1, 0);
8091     pxor(vec2, vec2);
8092   }
8093   bind(SCAN_TO_8_CHAR);
8094   cmpl(cnt1, stride);
8095   if (UseAVX >= 2) {
8096     jcc(Assembler::less, SCAN_TO_CHAR);
8097   } else {
8098     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
8099     movdl(vec1, ch);
8100     pshuflw(vec1, vec1, 0x00);
8101     pshufd(vec1, vec1, 0);
8102     pxor(vec2, vec2);
8103   }
8104   movl(tmp, cnt1);
8105   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
8106   andl(cnt1,0x00000007);  //tail count (in chars)
8107 
8108   bind(SCAN_TO_8_CHAR_LOOP);
8109   movdqu(vec3, Address(result, 0));
8110   pcmpeqw(vec3, vec1);
8111   ptest(vec2, vec3);
8112   jcc(Assembler::carryClear, FOUND_CHAR);
8113   addptr(result, 16);
8114   subl(tmp, stride);
8115   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
8116   bind(SCAN_TO_CHAR);
8117   testl(cnt1, cnt1);
8118   jcc(Assembler::zero, RET_NOT_FOUND);
8119   bind(SCAN_TO_CHAR_LOOP);
8120   load_unsigned_short(tmp, Address(result, 0));
8121   cmpl(ch, tmp);
8122   jccb(Assembler::equal, FOUND_SEQ_CHAR);
8123   addptr(result, 2);
8124   subl(cnt1, 1);
8125   jccb(Assembler::zero, RET_NOT_FOUND);
8126   jmp(SCAN_TO_CHAR_LOOP);
8127 
8128   bind(RET_NOT_FOUND);
8129   movl(result, -1);
8130   jmpb(DONE_LABEL);
8131 
8132   bind(FOUND_CHAR);
8133   if (UseAVX >= 2) {
8134     vpmovmskb(tmp, vec3);
8135   } else {
8136     pmovmskb(tmp, vec3);
8137   }
8138   bsfl(ch, tmp);
8139   addl(result, ch);
8140 
8141   bind(FOUND_SEQ_CHAR);
8142   subptr(result, str1);
8143   shrl(result, 1);
8144 
8145   bind(DONE_LABEL);
8146 } // string_indexof_char
8147 
8148 // helper function for string_compare
8149 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
8150                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
8151                                         Address::ScaleFactor scale2, Register index, int ae) {
8152   if (ae == StrIntrinsicNode::LL) {
8153     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
8154     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
8155   } else if (ae == StrIntrinsicNode::UU) {
8156     load_unsigned_short(elem1, Address(str1, index, scale, 0));
8157     load_unsigned_short(elem2, Address(str2, index, scale, 0));
8158   } else {
8159     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
8160     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
8161   }
8162 }
8163 
8164 // Compare strings, used for char[] and byte[].
8165 void MacroAssembler::string_compare(Register str1, Register str2,
8166                                     Register cnt1, Register cnt2, Register result,
8167                                     XMMRegister vec1, int ae) {
8168   ShortBranchVerifier sbv(this);
8169   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
8170   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
8171   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8172   int stride2x2 = 0x40;
8173   Address::ScaleFactor scale = Address::no_scale;
8174   Address::ScaleFactor scale1 = Address::no_scale;
8175   Address::ScaleFactor scale2 = Address::no_scale;
8176 
8177   if (ae != StrIntrinsicNode::LL) {
8178     stride2x2 = 0x20;
8179   }
8180 
8181   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8182     shrl(cnt2, 1);
8183   }
8184   // Compute the minimum of the string lengths and the
8185   // difference of the string lengths (stack).
8186   // Do the conditional move stuff
8187   movl(result, cnt1);
8188   subl(cnt1, cnt2);
8189   push(cnt1);
8190   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
8191 
8192   // Is the minimum length zero?
8193   testl(cnt2, cnt2);
8194   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8195   if (ae == StrIntrinsicNode::LL) {
8196     // Load first bytes
8197     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
8198     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
8199   } else if (ae == StrIntrinsicNode::UU) {
8200     // Load first characters
8201     load_unsigned_short(result, Address(str1, 0));
8202     load_unsigned_short(cnt1, Address(str2, 0));
8203   } else {
8204     load_unsigned_byte(result, Address(str1, 0));
8205     load_unsigned_short(cnt1, Address(str2, 0));
8206   }
8207   subl(result, cnt1);
8208   jcc(Assembler::notZero,  POP_LABEL);
8209 
8210   if (ae == StrIntrinsicNode::UU) {
8211     // Divide length by 2 to get number of chars
8212     shrl(cnt2, 1);
8213   }
8214   cmpl(cnt2, 1);
8215   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8216 
8217   // Check if the strings start at the same location and setup scale and stride
8218   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8219     cmpptr(str1, str2);
8220     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8221     if (ae == StrIntrinsicNode::LL) {
8222       scale = Address::times_1;
8223       stride = 16;
8224     } else {
8225       scale = Address::times_2;
8226       stride = 8;
8227     }
8228   } else {
8229     scale1 = Address::times_1;
8230     scale2 = Address::times_2;
8231     // scale not used
8232     stride = 8;
8233   }
8234 
8235   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8236     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8237     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8238     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
8239     Label COMPARE_TAIL_LONG;
8240     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
8241 
8242     int pcmpmask = 0x19;
8243     if (ae == StrIntrinsicNode::LL) {
8244       pcmpmask &= ~0x01;
8245     }
8246 
8247     // Setup to compare 16-chars (32-bytes) vectors,
8248     // start from first character again because it has aligned address.
8249     if (ae == StrIntrinsicNode::LL) {
8250       stride2 = 32;
8251     } else {
8252       stride2 = 16;
8253     }
8254     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8255       adr_stride = stride << scale;
8256     } else {
8257       adr_stride1 = 8;  //stride << scale1;
8258       adr_stride2 = 16; //stride << scale2;
8259     }
8260 
8261     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8262     // rax and rdx are used by pcmpestri as elements counters
8263     movl(result, cnt2);
8264     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8265     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8266 
8267     // fast path : compare first 2 8-char vectors.
8268     bind(COMPARE_16_CHARS);
8269     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8270       movdqu(vec1, Address(str1, 0));
8271     } else {
8272       pmovzxbw(vec1, Address(str1, 0));
8273     }
8274     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8275     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8276 
8277     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8278       movdqu(vec1, Address(str1, adr_stride));
8279       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8280     } else {
8281       pmovzxbw(vec1, Address(str1, adr_stride1));
8282       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8283     }
8284     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8285     addl(cnt1, stride);
8286 
8287     // Compare the characters at index in cnt1
8288     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8289     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8290     subl(result, cnt2);
8291     jmp(POP_LABEL);
8292 
8293     // Setup the registers to start vector comparison loop
8294     bind(COMPARE_WIDE_VECTORS);
8295     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8296       lea(str1, Address(str1, result, scale));
8297       lea(str2, Address(str2, result, scale));
8298     } else {
8299       lea(str1, Address(str1, result, scale1));
8300       lea(str2, Address(str2, result, scale2));
8301     }
8302     subl(result, stride2);
8303     subl(cnt2, stride2);
8304     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8305     negptr(result);
8306 
8307     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8308     bind(COMPARE_WIDE_VECTORS_LOOP);
8309 
8310 #ifdef _LP64
8311     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8312       cmpl(cnt2, stride2x2);
8313       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8314       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8315       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8316 
8317       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8318       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8319         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8320         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8321       } else {
8322         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8323         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8324       }
8325       kortestql(k7, k7);
8326       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8327       addptr(result, stride2x2);  // update since we already compared at this addr
8328       subl(cnt2, stride2x2);      // and sub the size too
8329       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8330 
8331       vpxor(vec1, vec1);
8332       jmpb(COMPARE_WIDE_TAIL);
8333     }//if (VM_Version::supports_avx512vlbw())
8334 #endif // _LP64
8335 
8336 
8337     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8338     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8339       vmovdqu(vec1, Address(str1, result, scale));
8340       vpxor(vec1, Address(str2, result, scale));
8341     } else {
8342       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8343       vpxor(vec1, Address(str2, result, scale2));
8344     }
8345     vptest(vec1, vec1);
8346     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8347     addptr(result, stride2);
8348     subl(cnt2, stride2);
8349     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8350     // clean upper bits of YMM registers
8351     vpxor(vec1, vec1);
8352 
8353     // compare wide vectors tail
8354     bind(COMPARE_WIDE_TAIL);
8355     testptr(result, result);
8356     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8357 
8358     movl(result, stride2);
8359     movl(cnt2, result);
8360     negptr(result);
8361     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8362 
8363     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8364     bind(VECTOR_NOT_EQUAL);
8365     // clean upper bits of YMM registers
8366     vpxor(vec1, vec1);
8367     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8368       lea(str1, Address(str1, result, scale));
8369       lea(str2, Address(str2, result, scale));
8370     } else {
8371       lea(str1, Address(str1, result, scale1));
8372       lea(str2, Address(str2, result, scale2));
8373     }
8374     jmp(COMPARE_16_CHARS);
8375 
8376     // Compare tail chars, length between 1 to 15 chars
8377     bind(COMPARE_TAIL_LONG);
8378     movl(cnt2, result);
8379     cmpl(cnt2, stride);
8380     jcc(Assembler::less, COMPARE_SMALL_STR);
8381 
8382     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8383       movdqu(vec1, Address(str1, 0));
8384     } else {
8385       pmovzxbw(vec1, Address(str1, 0));
8386     }
8387     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8388     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8389     subptr(cnt2, stride);
8390     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8391     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8392       lea(str1, Address(str1, result, scale));
8393       lea(str2, Address(str2, result, scale));
8394     } else {
8395       lea(str1, Address(str1, result, scale1));
8396       lea(str2, Address(str2, result, scale2));
8397     }
8398     negptr(cnt2);
8399     jmpb(WHILE_HEAD_LABEL);
8400 
8401     bind(COMPARE_SMALL_STR);
8402   } else if (UseSSE42Intrinsics) {
8403     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8404     int pcmpmask = 0x19;
8405     // Setup to compare 8-char (16-byte) vectors,
8406     // start from first character again because it has aligned address.
8407     movl(result, cnt2);
8408     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8409     if (ae == StrIntrinsicNode::LL) {
8410       pcmpmask &= ~0x01;
8411     }
8412     jcc(Assembler::zero, COMPARE_TAIL);
8413     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8414       lea(str1, Address(str1, result, scale));
8415       lea(str2, Address(str2, result, scale));
8416     } else {
8417       lea(str1, Address(str1, result, scale1));
8418       lea(str2, Address(str2, result, scale2));
8419     }
8420     negptr(result);
8421 
8422     // pcmpestri
8423     //   inputs:
8424     //     vec1- substring
8425     //     rax - negative string length (elements count)
8426     //     mem - scanned string
8427     //     rdx - string length (elements count)
8428     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8429     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8430     //   outputs:
8431     //     rcx - first mismatched element index
8432     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8433 
8434     bind(COMPARE_WIDE_VECTORS);
8435     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8436       movdqu(vec1, Address(str1, result, scale));
8437       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8438     } else {
8439       pmovzxbw(vec1, Address(str1, result, scale1));
8440       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8441     }
8442     // After pcmpestri cnt1(rcx) contains mismatched element index
8443 
8444     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8445     addptr(result, stride);
8446     subptr(cnt2, stride);
8447     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8448 
8449     // compare wide vectors tail
8450     testptr(result, result);
8451     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8452 
8453     movl(cnt2, stride);
8454     movl(result, stride);
8455     negptr(result);
8456     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8457       movdqu(vec1, Address(str1, result, scale));
8458       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8459     } else {
8460       pmovzxbw(vec1, Address(str1, result, scale1));
8461       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8462     }
8463     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8464 
8465     // Mismatched characters in the vectors
8466     bind(VECTOR_NOT_EQUAL);
8467     addptr(cnt1, result);
8468     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8469     subl(result, cnt2);
8470     jmpb(POP_LABEL);
8471 
8472     bind(COMPARE_TAIL); // limit is zero
8473     movl(cnt2, result);
8474     // Fallthru to tail compare
8475   }
8476   // Shift str2 and str1 to the end of the arrays, negate min
8477   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8478     lea(str1, Address(str1, cnt2, scale));
8479     lea(str2, Address(str2, cnt2, scale));
8480   } else {
8481     lea(str1, Address(str1, cnt2, scale1));
8482     lea(str2, Address(str2, cnt2, scale2));
8483   }
8484   decrementl(cnt2);  // first character was compared already
8485   negptr(cnt2);
8486 
8487   // Compare the rest of the elements
8488   bind(WHILE_HEAD_LABEL);
8489   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8490   subl(result, cnt1);
8491   jccb(Assembler::notZero, POP_LABEL);
8492   increment(cnt2);
8493   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8494 
8495   // Strings are equal up to min length.  Return the length difference.
8496   bind(LENGTH_DIFF_LABEL);
8497   pop(result);
8498   if (ae == StrIntrinsicNode::UU) {
8499     // Divide diff by 2 to get number of chars
8500     sarl(result, 1);
8501   }
8502   jmpb(DONE_LABEL);
8503 
8504 #ifdef _LP64
8505   if (VM_Version::supports_avx512vlbw()) {
8506 
8507     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8508 
8509     kmovql(cnt1, k7);
8510     notq(cnt1);
8511     bsfq(cnt2, cnt1);
8512     if (ae != StrIntrinsicNode::LL) {
8513       // Divide diff by 2 to get number of chars
8514       sarl(cnt2, 1);
8515     }
8516     addq(result, cnt2);
8517     if (ae == StrIntrinsicNode::LL) {
8518       load_unsigned_byte(cnt1, Address(str2, result));
8519       load_unsigned_byte(result, Address(str1, result));
8520     } else if (ae == StrIntrinsicNode::UU) {
8521       load_unsigned_short(cnt1, Address(str2, result, scale));
8522       load_unsigned_short(result, Address(str1, result, scale));
8523     } else {
8524       load_unsigned_short(cnt1, Address(str2, result, scale2));
8525       load_unsigned_byte(result, Address(str1, result, scale1));
8526     }
8527     subl(result, cnt1);
8528     jmpb(POP_LABEL);
8529   }//if (VM_Version::supports_avx512vlbw())
8530 #endif // _LP64
8531 
8532   // Discard the stored length difference
8533   bind(POP_LABEL);
8534   pop(cnt1);
8535 
8536   // That's it
8537   bind(DONE_LABEL);
8538   if(ae == StrIntrinsicNode::UL) {
8539     negl(result);
8540   }
8541 
8542 }
8543 
8544 // Search for Non-ASCII character (Negative byte value) in a byte array,
8545 // return true if it has any and false otherwise.
8546 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8547 //   @HotSpotIntrinsicCandidate
8548 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8549 //     for (int i = off; i < off + len; i++) {
8550 //       if (ba[i] < 0) {
8551 //         return true;
8552 //       }
8553 //     }
8554 //     return false;
8555 //   }
8556 void MacroAssembler::has_negatives(Register ary1, Register len,
8557   Register result, Register tmp1,
8558   XMMRegister vec1, XMMRegister vec2) {
8559   // rsi: byte array
8560   // rcx: len
8561   // rax: result
8562   ShortBranchVerifier sbv(this);
8563   assert_different_registers(ary1, len, result, tmp1);
8564   assert_different_registers(vec1, vec2);
8565   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8566 
8567   // len == 0
8568   testl(len, len);
8569   jcc(Assembler::zero, FALSE_LABEL);
8570 
8571   if ((UseAVX > 2) && // AVX512
8572     VM_Version::supports_avx512vlbw() &&
8573     VM_Version::supports_bmi2()) {
8574 
8575     set_vector_masking();  // opening of the stub context for programming mask registers
8576 
8577     Label test_64_loop, test_tail;
8578     Register tmp3_aliased = len;
8579 
8580     movl(tmp1, len);
8581     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8582 
8583     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8584     andl(len, ~(64 - 1));    // vector count (in chars)
8585     jccb(Assembler::zero, test_tail);
8586 
8587     lea(ary1, Address(ary1, len, Address::times_1));
8588     negptr(len);
8589 
8590     bind(test_64_loop);
8591     // Check whether our 64 elements of size byte contain negatives
8592     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8593     kortestql(k2, k2);
8594     jcc(Assembler::notZero, TRUE_LABEL);
8595 
8596     addptr(len, 64);
8597     jccb(Assembler::notZero, test_64_loop);
8598 
8599 
8600     bind(test_tail);
8601     // bail out when there is nothing to be done
8602     testl(tmp1, -1);
8603     jcc(Assembler::zero, FALSE_LABEL);
8604 
8605     // Save k1
8606     kmovql(k3, k1);
8607 
8608     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8609 #ifdef _LP64
8610     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8611     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8612     notq(tmp3_aliased);
8613     kmovql(k1, tmp3_aliased);
8614 #else
8615     Label k_init;
8616     jmp(k_init);
8617 
8618     // We could not read 64-bits from a general purpose register thus we move
8619     // data required to compose 64 1's to the instruction stream
8620     // We emit 64 byte wide series of elements from 0..63 which later on would
8621     // be used as a compare targets with tail count contained in tmp1 register.
8622     // Result would be a k1 register having tmp1 consecutive number or 1
8623     // counting from least significant bit.
8624     address tmp = pc();
8625     emit_int64(0x0706050403020100);
8626     emit_int64(0x0F0E0D0C0B0A0908);
8627     emit_int64(0x1716151413121110);
8628     emit_int64(0x1F1E1D1C1B1A1918);
8629     emit_int64(0x2726252423222120);
8630     emit_int64(0x2F2E2D2C2B2A2928);
8631     emit_int64(0x3736353433323130);
8632     emit_int64(0x3F3E3D3C3B3A3938);
8633 
8634     bind(k_init);
8635     lea(len, InternalAddress(tmp));
8636     // create mask to test for negative byte inside a vector
8637     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8638     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8639 
8640 #endif
8641     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8642     ktestq(k2, k1);
8643     // Restore k1
8644     kmovql(k1, k3);
8645     jcc(Assembler::notZero, TRUE_LABEL);
8646 
8647     jmp(FALSE_LABEL);
8648 
8649     clear_vector_masking();   // closing of the stub context for programming mask registers
8650   } else {
8651     movl(result, len); // copy
8652 
8653     if (UseAVX == 2 && UseSSE >= 2) {
8654       // With AVX2, use 32-byte vector compare
8655       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8656 
8657       // Compare 32-byte vectors
8658       andl(result, 0x0000001f);  //   tail count (in bytes)
8659       andl(len, 0xffffffe0);   // vector count (in bytes)
8660       jccb(Assembler::zero, COMPARE_TAIL);
8661 
8662       lea(ary1, Address(ary1, len, Address::times_1));
8663       negptr(len);
8664 
8665       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8666       movdl(vec2, tmp1);
8667       vpbroadcastd(vec2, vec2);
8668 
8669       bind(COMPARE_WIDE_VECTORS);
8670       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8671       vptest(vec1, vec2);
8672       jccb(Assembler::notZero, TRUE_LABEL);
8673       addptr(len, 32);
8674       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8675 
8676       testl(result, result);
8677       jccb(Assembler::zero, FALSE_LABEL);
8678 
8679       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8680       vptest(vec1, vec2);
8681       jccb(Assembler::notZero, TRUE_LABEL);
8682       jmpb(FALSE_LABEL);
8683 
8684       bind(COMPARE_TAIL); // len is zero
8685       movl(len, result);
8686       // Fallthru to tail compare
8687     } else if (UseSSE42Intrinsics) {
8688       // With SSE4.2, use double quad vector compare
8689       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8690 
8691       // Compare 16-byte vectors
8692       andl(result, 0x0000000f);  //   tail count (in bytes)
8693       andl(len, 0xfffffff0);   // vector count (in bytes)
8694       jccb(Assembler::zero, COMPARE_TAIL);
8695 
8696       lea(ary1, Address(ary1, len, Address::times_1));
8697       negptr(len);
8698 
8699       movl(tmp1, 0x80808080);
8700       movdl(vec2, tmp1);
8701       pshufd(vec2, vec2, 0);
8702 
8703       bind(COMPARE_WIDE_VECTORS);
8704       movdqu(vec1, Address(ary1, len, Address::times_1));
8705       ptest(vec1, vec2);
8706       jccb(Assembler::notZero, TRUE_LABEL);
8707       addptr(len, 16);
8708       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8709 
8710       testl(result, result);
8711       jccb(Assembler::zero, FALSE_LABEL);
8712 
8713       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8714       ptest(vec1, vec2);
8715       jccb(Assembler::notZero, TRUE_LABEL);
8716       jmpb(FALSE_LABEL);
8717 
8718       bind(COMPARE_TAIL); // len is zero
8719       movl(len, result);
8720       // Fallthru to tail compare
8721     }
8722   }
8723   // Compare 4-byte vectors
8724   andl(len, 0xfffffffc); // vector count (in bytes)
8725   jccb(Assembler::zero, COMPARE_CHAR);
8726 
8727   lea(ary1, Address(ary1, len, Address::times_1));
8728   negptr(len);
8729 
8730   bind(COMPARE_VECTORS);
8731   movl(tmp1, Address(ary1, len, Address::times_1));
8732   andl(tmp1, 0x80808080);
8733   jccb(Assembler::notZero, TRUE_LABEL);
8734   addptr(len, 4);
8735   jcc(Assembler::notZero, COMPARE_VECTORS);
8736 
8737   // Compare trailing char (final 2 bytes), if any
8738   bind(COMPARE_CHAR);
8739   testl(result, 0x2);   // tail  char
8740   jccb(Assembler::zero, COMPARE_BYTE);
8741   load_unsigned_short(tmp1, Address(ary1, 0));
8742   andl(tmp1, 0x00008080);
8743   jccb(Assembler::notZero, TRUE_LABEL);
8744   subptr(result, 2);
8745   lea(ary1, Address(ary1, 2));
8746 
8747   bind(COMPARE_BYTE);
8748   testl(result, 0x1);   // tail  byte
8749   jccb(Assembler::zero, FALSE_LABEL);
8750   load_unsigned_byte(tmp1, Address(ary1, 0));
8751   andl(tmp1, 0x00000080);
8752   jccb(Assembler::notEqual, TRUE_LABEL);
8753   jmpb(FALSE_LABEL);
8754 
8755   bind(TRUE_LABEL);
8756   movl(result, 1);   // return true
8757   jmpb(DONE);
8758 
8759   bind(FALSE_LABEL);
8760   xorl(result, result); // return false
8761 
8762   // That's it
8763   bind(DONE);
8764   if (UseAVX >= 2 && UseSSE >= 2) {
8765     // clean upper bits of YMM registers
8766     vpxor(vec1, vec1);
8767     vpxor(vec2, vec2);
8768   }
8769 }
8770 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8771 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8772                                    Register limit, Register result, Register chr,
8773                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8774   ShortBranchVerifier sbv(this);
8775   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8776 
8777   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8778   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8779 
8780   if (is_array_equ) {
8781     // Check the input args
8782     cmpptr(ary1, ary2);
8783     oopDesc::bs()->asm_acmp_barrier(this, ary1, ary2);
8784     jcc(Assembler::equal, TRUE_LABEL);
8785 
8786     // Need additional checks for arrays_equals.
8787     testptr(ary1, ary1);
8788     jcc(Assembler::zero, FALSE_LABEL);
8789     testptr(ary2, ary2);
8790     jcc(Assembler::zero, FALSE_LABEL);
8791 
8792     // Check the lengths
8793     movl(limit, Address(ary1, length_offset));
8794     cmpl(limit, Address(ary2, length_offset));
8795     jcc(Assembler::notEqual, FALSE_LABEL);
8796   }
8797 
8798   // count == 0
8799   testl(limit, limit);
8800   jcc(Assembler::zero, TRUE_LABEL);
8801 
8802   if (is_array_equ) {
8803     // Load array address
8804     lea(ary1, Address(ary1, base_offset));
8805     lea(ary2, Address(ary2, base_offset));
8806   }
8807 
8808   if (is_array_equ && is_char) {
8809     // arrays_equals when used for char[].
8810     shll(limit, 1);      // byte count != 0
8811   }
8812   movl(result, limit); // copy
8813 
8814   if (UseAVX >= 2) {
8815     // With AVX2, use 32-byte vector compare
8816     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8817 
8818     // Compare 32-byte vectors
8819     andl(result, 0x0000001f);  //   tail count (in bytes)
8820     andl(limit, 0xffffffe0);   // vector count (in bytes)
8821     jcc(Assembler::zero, COMPARE_TAIL);
8822 
8823     lea(ary1, Address(ary1, limit, Address::times_1));
8824     lea(ary2, Address(ary2, limit, Address::times_1));
8825     negptr(limit);
8826 
8827     bind(COMPARE_WIDE_VECTORS);
8828 
8829 #ifdef _LP64
8830     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8831       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8832 
8833       cmpl(limit, -64);
8834       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8835 
8836       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8837 
8838       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8839       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8840       kortestql(k7, k7);
8841       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8842       addptr(limit, 64);  // update since we already compared at this addr
8843       cmpl(limit, -64);
8844       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8845 
8846       // At this point we may still need to compare -limit+result bytes.
8847       // We could execute the next two instruction and just continue via non-wide path:
8848       //  cmpl(limit, 0);
8849       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8850       // But since we stopped at the points ary{1,2}+limit which are
8851       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8852       // (|limit| <= 32 and result < 32),
8853       // we may just compare the last 64 bytes.
8854       //
8855       addptr(result, -64);   // it is safe, bc we just came from this area
8856       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8857       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8858       kortestql(k7, k7);
8859       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8860 
8861       jmp(TRUE_LABEL);
8862 
8863       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8864 
8865     }//if (VM_Version::supports_avx512vlbw())
8866 #endif //_LP64
8867 
8868     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8869     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8870     vpxor(vec1, vec2);
8871 
8872     vptest(vec1, vec1);
8873     jcc(Assembler::notZero, FALSE_LABEL);
8874     addptr(limit, 32);
8875     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8876 
8877     testl(result, result);
8878     jcc(Assembler::zero, TRUE_LABEL);
8879 
8880     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8881     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8882     vpxor(vec1, vec2);
8883 
8884     vptest(vec1, vec1);
8885     jccb(Assembler::notZero, FALSE_LABEL);
8886     jmpb(TRUE_LABEL);
8887 
8888     bind(COMPARE_TAIL); // limit is zero
8889     movl(limit, result);
8890     // Fallthru to tail compare
8891   } else if (UseSSE42Intrinsics) {
8892     // With SSE4.2, use double quad vector compare
8893     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8894 
8895     // Compare 16-byte vectors
8896     andl(result, 0x0000000f);  //   tail count (in bytes)
8897     andl(limit, 0xfffffff0);   // vector count (in bytes)
8898     jcc(Assembler::zero, COMPARE_TAIL);
8899 
8900     lea(ary1, Address(ary1, limit, Address::times_1));
8901     lea(ary2, Address(ary2, limit, Address::times_1));
8902     negptr(limit);
8903 
8904     bind(COMPARE_WIDE_VECTORS);
8905     movdqu(vec1, Address(ary1, limit, Address::times_1));
8906     movdqu(vec2, Address(ary2, limit, Address::times_1));
8907     pxor(vec1, vec2);
8908 
8909     ptest(vec1, vec1);
8910     jcc(Assembler::notZero, FALSE_LABEL);
8911     addptr(limit, 16);
8912     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8913 
8914     testl(result, result);
8915     jcc(Assembler::zero, TRUE_LABEL);
8916 
8917     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8918     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8919     pxor(vec1, vec2);
8920 
8921     ptest(vec1, vec1);
8922     jccb(Assembler::notZero, FALSE_LABEL);
8923     jmpb(TRUE_LABEL);
8924 
8925     bind(COMPARE_TAIL); // limit is zero
8926     movl(limit, result);
8927     // Fallthru to tail compare
8928   }
8929 
8930   // Compare 4-byte vectors
8931   andl(limit, 0xfffffffc); // vector count (in bytes)
8932   jccb(Assembler::zero, COMPARE_CHAR);
8933 
8934   lea(ary1, Address(ary1, limit, Address::times_1));
8935   lea(ary2, Address(ary2, limit, Address::times_1));
8936   negptr(limit);
8937 
8938   bind(COMPARE_VECTORS);
8939   movl(chr, Address(ary1, limit, Address::times_1));
8940   cmpl(chr, Address(ary2, limit, Address::times_1));
8941   jccb(Assembler::notEqual, FALSE_LABEL);
8942   addptr(limit, 4);
8943   jcc(Assembler::notZero, COMPARE_VECTORS);
8944 
8945   // Compare trailing char (final 2 bytes), if any
8946   bind(COMPARE_CHAR);
8947   testl(result, 0x2);   // tail  char
8948   jccb(Assembler::zero, COMPARE_BYTE);
8949   load_unsigned_short(chr, Address(ary1, 0));
8950   load_unsigned_short(limit, Address(ary2, 0));
8951   cmpl(chr, limit);
8952   jccb(Assembler::notEqual, FALSE_LABEL);
8953 
8954   if (is_array_equ && is_char) {
8955     bind(COMPARE_BYTE);
8956   } else {
8957     lea(ary1, Address(ary1, 2));
8958     lea(ary2, Address(ary2, 2));
8959 
8960     bind(COMPARE_BYTE);
8961     testl(result, 0x1);   // tail  byte
8962     jccb(Assembler::zero, TRUE_LABEL);
8963     load_unsigned_byte(chr, Address(ary1, 0));
8964     load_unsigned_byte(limit, Address(ary2, 0));
8965     cmpl(chr, limit);
8966     jccb(Assembler::notEqual, FALSE_LABEL);
8967   }
8968   bind(TRUE_LABEL);
8969   movl(result, 1);   // return true
8970   jmpb(DONE);
8971 
8972   bind(FALSE_LABEL);
8973   xorl(result, result); // return false
8974 
8975   // That's it
8976   bind(DONE);
8977   if (UseAVX >= 2) {
8978     // clean upper bits of YMM registers
8979     vpxor(vec1, vec1);
8980     vpxor(vec2, vec2);
8981   }
8982 }
8983 
8984 #endif
8985 
8986 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8987                                    Register to, Register value, Register count,
8988                                    Register rtmp, XMMRegister xtmp) {
8989   ShortBranchVerifier sbv(this);
8990   assert_different_registers(to, value, count, rtmp);
8991   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8992   Label L_fill_2_bytes, L_fill_4_bytes;
8993 
8994   int shift = -1;
8995   switch (t) {
8996     case T_BYTE:
8997       shift = 2;
8998       break;
8999     case T_SHORT:
9000       shift = 1;
9001       break;
9002     case T_INT:
9003       shift = 0;
9004       break;
9005     default: ShouldNotReachHere();
9006   }
9007 
9008   if (t == T_BYTE) {
9009     andl(value, 0xff);
9010     movl(rtmp, value);
9011     shll(rtmp, 8);
9012     orl(value, rtmp);
9013   }
9014   if (t == T_SHORT) {
9015     andl(value, 0xffff);
9016   }
9017   if (t == T_BYTE || t == T_SHORT) {
9018     movl(rtmp, value);
9019     shll(rtmp, 16);
9020     orl(value, rtmp);
9021   }
9022 
9023   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
9024   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
9025   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
9026     // align source address at 4 bytes address boundary
9027     if (t == T_BYTE) {
9028       // One byte misalignment happens only for byte arrays
9029       testptr(to, 1);
9030       jccb(Assembler::zero, L_skip_align1);
9031       movb(Address(to, 0), value);
9032       increment(to);
9033       decrement(count);
9034       BIND(L_skip_align1);
9035     }
9036     // Two bytes misalignment happens only for byte and short (char) arrays
9037     testptr(to, 2);
9038     jccb(Assembler::zero, L_skip_align2);
9039     movw(Address(to, 0), value);
9040     addptr(to, 2);
9041     subl(count, 1<<(shift-1));
9042     BIND(L_skip_align2);
9043   }
9044   if (UseSSE < 2) {
9045     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9046     // Fill 32-byte chunks
9047     subl(count, 8 << shift);
9048     jcc(Assembler::less, L_check_fill_8_bytes);
9049     align(16);
9050 
9051     BIND(L_fill_32_bytes_loop);
9052 
9053     for (int i = 0; i < 32; i += 4) {
9054       movl(Address(to, i), value);
9055     }
9056 
9057     addptr(to, 32);
9058     subl(count, 8 << shift);
9059     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9060     BIND(L_check_fill_8_bytes);
9061     addl(count, 8 << shift);
9062     jccb(Assembler::zero, L_exit);
9063     jmpb(L_fill_8_bytes);
9064 
9065     //
9066     // length is too short, just fill qwords
9067     //
9068     BIND(L_fill_8_bytes_loop);
9069     movl(Address(to, 0), value);
9070     movl(Address(to, 4), value);
9071     addptr(to, 8);
9072     BIND(L_fill_8_bytes);
9073     subl(count, 1 << (shift + 1));
9074     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9075     // fall through to fill 4 bytes
9076   } else {
9077     Label L_fill_32_bytes;
9078     if (!UseUnalignedLoadStores) {
9079       // align to 8 bytes, we know we are 4 byte aligned to start
9080       testptr(to, 4);
9081       jccb(Assembler::zero, L_fill_32_bytes);
9082       movl(Address(to, 0), value);
9083       addptr(to, 4);
9084       subl(count, 1<<shift);
9085     }
9086     BIND(L_fill_32_bytes);
9087     {
9088       assert( UseSSE >= 2, "supported cpu only" );
9089       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
9090       if (UseAVX > 2) {
9091         movl(rtmp, 0xffff);
9092         kmovwl(k1, rtmp);
9093       }
9094       movdl(xtmp, value);
9095       if (UseAVX > 2 && UseUnalignedLoadStores) {
9096         // Fill 64-byte chunks
9097         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9098         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
9099 
9100         subl(count, 16 << shift);
9101         jcc(Assembler::less, L_check_fill_32_bytes);
9102         align(16);
9103 
9104         BIND(L_fill_64_bytes_loop);
9105         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
9106         addptr(to, 64);
9107         subl(count, 16 << shift);
9108         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9109 
9110         BIND(L_check_fill_32_bytes);
9111         addl(count, 8 << shift);
9112         jccb(Assembler::less, L_check_fill_8_bytes);
9113         vmovdqu(Address(to, 0), xtmp);
9114         addptr(to, 32);
9115         subl(count, 8 << shift);
9116 
9117         BIND(L_check_fill_8_bytes);
9118       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
9119         // Fill 64-byte chunks
9120         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
9121         vpbroadcastd(xtmp, xtmp);
9122 
9123         subl(count, 16 << shift);
9124         jcc(Assembler::less, L_check_fill_32_bytes);
9125         align(16);
9126 
9127         BIND(L_fill_64_bytes_loop);
9128         vmovdqu(Address(to, 0), xtmp);
9129         vmovdqu(Address(to, 32), xtmp);
9130         addptr(to, 64);
9131         subl(count, 16 << shift);
9132         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
9133 
9134         BIND(L_check_fill_32_bytes);
9135         addl(count, 8 << shift);
9136         jccb(Assembler::less, L_check_fill_8_bytes);
9137         vmovdqu(Address(to, 0), xtmp);
9138         addptr(to, 32);
9139         subl(count, 8 << shift);
9140 
9141         BIND(L_check_fill_8_bytes);
9142         // clean upper bits of YMM registers
9143         movdl(xtmp, value);
9144         pshufd(xtmp, xtmp, 0);
9145       } else {
9146         // Fill 32-byte chunks
9147         pshufd(xtmp, xtmp, 0);
9148 
9149         subl(count, 8 << shift);
9150         jcc(Assembler::less, L_check_fill_8_bytes);
9151         align(16);
9152 
9153         BIND(L_fill_32_bytes_loop);
9154 
9155         if (UseUnalignedLoadStores) {
9156           movdqu(Address(to, 0), xtmp);
9157           movdqu(Address(to, 16), xtmp);
9158         } else {
9159           movq(Address(to, 0), xtmp);
9160           movq(Address(to, 8), xtmp);
9161           movq(Address(to, 16), xtmp);
9162           movq(Address(to, 24), xtmp);
9163         }
9164 
9165         addptr(to, 32);
9166         subl(count, 8 << shift);
9167         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
9168 
9169         BIND(L_check_fill_8_bytes);
9170       }
9171       addl(count, 8 << shift);
9172       jccb(Assembler::zero, L_exit);
9173       jmpb(L_fill_8_bytes);
9174 
9175       //
9176       // length is too short, just fill qwords
9177       //
9178       BIND(L_fill_8_bytes_loop);
9179       movq(Address(to, 0), xtmp);
9180       addptr(to, 8);
9181       BIND(L_fill_8_bytes);
9182       subl(count, 1 << (shift + 1));
9183       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
9184     }
9185   }
9186   // fill trailing 4 bytes
9187   BIND(L_fill_4_bytes);
9188   testl(count, 1<<shift);
9189   jccb(Assembler::zero, L_fill_2_bytes);
9190   movl(Address(to, 0), value);
9191   if (t == T_BYTE || t == T_SHORT) {
9192     addptr(to, 4);
9193     BIND(L_fill_2_bytes);
9194     // fill trailing 2 bytes
9195     testl(count, 1<<(shift-1));
9196     jccb(Assembler::zero, L_fill_byte);
9197     movw(Address(to, 0), value);
9198     if (t == T_BYTE) {
9199       addptr(to, 2);
9200       BIND(L_fill_byte);
9201       // fill trailing byte
9202       testl(count, 1);
9203       jccb(Assembler::zero, L_exit);
9204       movb(Address(to, 0), value);
9205     } else {
9206       BIND(L_fill_byte);
9207     }
9208   } else {
9209     BIND(L_fill_2_bytes);
9210   }
9211   BIND(L_exit);
9212 }
9213 
9214 // encode char[] to byte[] in ISO_8859_1
9215    //@HotSpotIntrinsicCandidate
9216    //private static int implEncodeISOArray(byte[] sa, int sp,
9217    //byte[] da, int dp, int len) {
9218    //  int i = 0;
9219    //  for (; i < len; i++) {
9220    //    char c = StringUTF16.getChar(sa, sp++);
9221    //    if (c > '\u00FF')
9222    //      break;
9223    //    da[dp++] = (byte)c;
9224    //  }
9225    //  return i;
9226    //}
9227 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
9228   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9229   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9230   Register tmp5, Register result) {
9231 
9232   // rsi: src
9233   // rdi: dst
9234   // rdx: len
9235   // rcx: tmp5
9236   // rax: result
9237   ShortBranchVerifier sbv(this);
9238   assert_different_registers(src, dst, len, tmp5, result);
9239   Label L_done, L_copy_1_char, L_copy_1_char_exit;
9240 
9241   // set result
9242   xorl(result, result);
9243   // check for zero length
9244   testl(len, len);
9245   jcc(Assembler::zero, L_done);
9246 
9247   movl(result, len);
9248 
9249   // Setup pointers
9250   lea(src, Address(src, len, Address::times_2)); // char[]
9251   lea(dst, Address(dst, len, Address::times_1)); // byte[]
9252   negptr(len);
9253 
9254   if (UseSSE42Intrinsics || UseAVX >= 2) {
9255     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
9256     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
9257 
9258     if (UseAVX >= 2) {
9259       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
9260       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9261       movdl(tmp1Reg, tmp5);
9262       vpbroadcastd(tmp1Reg, tmp1Reg);
9263       jmp(L_chars_32_check);
9264 
9265       bind(L_copy_32_chars);
9266       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
9267       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
9268       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9269       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9270       jccb(Assembler::notZero, L_copy_32_chars_exit);
9271       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9272       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
9273       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
9274 
9275       bind(L_chars_32_check);
9276       addptr(len, 32);
9277       jcc(Assembler::lessEqual, L_copy_32_chars);
9278 
9279       bind(L_copy_32_chars_exit);
9280       subptr(len, 16);
9281       jccb(Assembler::greater, L_copy_16_chars_exit);
9282 
9283     } else if (UseSSE42Intrinsics) {
9284       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9285       movdl(tmp1Reg, tmp5);
9286       pshufd(tmp1Reg, tmp1Reg, 0);
9287       jmpb(L_chars_16_check);
9288     }
9289 
9290     bind(L_copy_16_chars);
9291     if (UseAVX >= 2) {
9292       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9293       vptest(tmp2Reg, tmp1Reg);
9294       jcc(Assembler::notZero, L_copy_16_chars_exit);
9295       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9296       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9297     } else {
9298       if (UseAVX > 0) {
9299         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9300         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9301         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9302       } else {
9303         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9304         por(tmp2Reg, tmp3Reg);
9305         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9306         por(tmp2Reg, tmp4Reg);
9307       }
9308       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9309       jccb(Assembler::notZero, L_copy_16_chars_exit);
9310       packuswb(tmp3Reg, tmp4Reg);
9311     }
9312     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9313 
9314     bind(L_chars_16_check);
9315     addptr(len, 16);
9316     jcc(Assembler::lessEqual, L_copy_16_chars);
9317 
9318     bind(L_copy_16_chars_exit);
9319     if (UseAVX >= 2) {
9320       // clean upper bits of YMM registers
9321       vpxor(tmp2Reg, tmp2Reg);
9322       vpxor(tmp3Reg, tmp3Reg);
9323       vpxor(tmp4Reg, tmp4Reg);
9324       movdl(tmp1Reg, tmp5);
9325       pshufd(tmp1Reg, tmp1Reg, 0);
9326     }
9327     subptr(len, 8);
9328     jccb(Assembler::greater, L_copy_8_chars_exit);
9329 
9330     bind(L_copy_8_chars);
9331     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9332     ptest(tmp3Reg, tmp1Reg);
9333     jccb(Assembler::notZero, L_copy_8_chars_exit);
9334     packuswb(tmp3Reg, tmp1Reg);
9335     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9336     addptr(len, 8);
9337     jccb(Assembler::lessEqual, L_copy_8_chars);
9338 
9339     bind(L_copy_8_chars_exit);
9340     subptr(len, 8);
9341     jccb(Assembler::zero, L_done);
9342   }
9343 
9344   bind(L_copy_1_char);
9345   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9346   testl(tmp5, 0xff00);      // check if Unicode char
9347   jccb(Assembler::notZero, L_copy_1_char_exit);
9348   movb(Address(dst, len, Address::times_1, 0), tmp5);
9349   addptr(len, 1);
9350   jccb(Assembler::less, L_copy_1_char);
9351 
9352   bind(L_copy_1_char_exit);
9353   addptr(result, len); // len is negative count of not processed elements
9354 
9355   bind(L_done);
9356 }
9357 
9358 #ifdef _LP64
9359 /**
9360  * Helper for multiply_to_len().
9361  */
9362 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9363   addq(dest_lo, src1);
9364   adcq(dest_hi, 0);
9365   addq(dest_lo, src2);
9366   adcq(dest_hi, 0);
9367 }
9368 
9369 /**
9370  * Multiply 64 bit by 64 bit first loop.
9371  */
9372 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9373                                            Register y, Register y_idx, Register z,
9374                                            Register carry, Register product,
9375                                            Register idx, Register kdx) {
9376   //
9377   //  jlong carry, x[], y[], z[];
9378   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9379   //    huge_128 product = y[idx] * x[xstart] + carry;
9380   //    z[kdx] = (jlong)product;
9381   //    carry  = (jlong)(product >>> 64);
9382   //  }
9383   //  z[xstart] = carry;
9384   //
9385 
9386   Label L_first_loop, L_first_loop_exit;
9387   Label L_one_x, L_one_y, L_multiply;
9388 
9389   decrementl(xstart);
9390   jcc(Assembler::negative, L_one_x);
9391 
9392   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9393   rorq(x_xstart, 32); // convert big-endian to little-endian
9394 
9395   bind(L_first_loop);
9396   decrementl(idx);
9397   jcc(Assembler::negative, L_first_loop_exit);
9398   decrementl(idx);
9399   jcc(Assembler::negative, L_one_y);
9400   movq(y_idx, Address(y, idx, Address::times_4,  0));
9401   rorq(y_idx, 32); // convert big-endian to little-endian
9402   bind(L_multiply);
9403   movq(product, x_xstart);
9404   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9405   addq(product, carry);
9406   adcq(rdx, 0);
9407   subl(kdx, 2);
9408   movl(Address(z, kdx, Address::times_4,  4), product);
9409   shrq(product, 32);
9410   movl(Address(z, kdx, Address::times_4,  0), product);
9411   movq(carry, rdx);
9412   jmp(L_first_loop);
9413 
9414   bind(L_one_y);
9415   movl(y_idx, Address(y,  0));
9416   jmp(L_multiply);
9417 
9418   bind(L_one_x);
9419   movl(x_xstart, Address(x,  0));
9420   jmp(L_first_loop);
9421 
9422   bind(L_first_loop_exit);
9423 }
9424 
9425 /**
9426  * Multiply 64 bit by 64 bit and add 128 bit.
9427  */
9428 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9429                                             Register yz_idx, Register idx,
9430                                             Register carry, Register product, int offset) {
9431   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9432   //     z[kdx] = (jlong)product;
9433 
9434   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9435   rorq(yz_idx, 32); // convert big-endian to little-endian
9436   movq(product, x_xstart);
9437   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9438   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9439   rorq(yz_idx, 32); // convert big-endian to little-endian
9440 
9441   add2_with_carry(rdx, product, carry, yz_idx);
9442 
9443   movl(Address(z, idx, Address::times_4,  offset+4), product);
9444   shrq(product, 32);
9445   movl(Address(z, idx, Address::times_4,  offset), product);
9446 
9447 }
9448 
9449 /**
9450  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9451  */
9452 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9453                                              Register yz_idx, Register idx, Register jdx,
9454                                              Register carry, Register product,
9455                                              Register carry2) {
9456   //   jlong carry, x[], y[], z[];
9457   //   int kdx = ystart+1;
9458   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9459   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9460   //     z[kdx+idx+1] = (jlong)product;
9461   //     jlong carry2  = (jlong)(product >>> 64);
9462   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9463   //     z[kdx+idx] = (jlong)product;
9464   //     carry  = (jlong)(product >>> 64);
9465   //   }
9466   //   idx += 2;
9467   //   if (idx > 0) {
9468   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9469   //     z[kdx+idx] = (jlong)product;
9470   //     carry  = (jlong)(product >>> 64);
9471   //   }
9472   //
9473 
9474   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9475 
9476   movl(jdx, idx);
9477   andl(jdx, 0xFFFFFFFC);
9478   shrl(jdx, 2);
9479 
9480   bind(L_third_loop);
9481   subl(jdx, 1);
9482   jcc(Assembler::negative, L_third_loop_exit);
9483   subl(idx, 4);
9484 
9485   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9486   movq(carry2, rdx);
9487 
9488   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9489   movq(carry, rdx);
9490   jmp(L_third_loop);
9491 
9492   bind (L_third_loop_exit);
9493 
9494   andl (idx, 0x3);
9495   jcc(Assembler::zero, L_post_third_loop_done);
9496 
9497   Label L_check_1;
9498   subl(idx, 2);
9499   jcc(Assembler::negative, L_check_1);
9500 
9501   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9502   movq(carry, rdx);
9503 
9504   bind (L_check_1);
9505   addl (idx, 0x2);
9506   andl (idx, 0x1);
9507   subl(idx, 1);
9508   jcc(Assembler::negative, L_post_third_loop_done);
9509 
9510   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9511   movq(product, x_xstart);
9512   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9513   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9514 
9515   add2_with_carry(rdx, product, yz_idx, carry);
9516 
9517   movl(Address(z, idx, Address::times_4,  0), product);
9518   shrq(product, 32);
9519 
9520   shlq(rdx, 32);
9521   orq(product, rdx);
9522   movq(carry, product);
9523 
9524   bind(L_post_third_loop_done);
9525 }
9526 
9527 /**
9528  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9529  *
9530  */
9531 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9532                                                   Register carry, Register carry2,
9533                                                   Register idx, Register jdx,
9534                                                   Register yz_idx1, Register yz_idx2,
9535                                                   Register tmp, Register tmp3, Register tmp4) {
9536   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9537 
9538   //   jlong carry, x[], y[], z[];
9539   //   int kdx = ystart+1;
9540   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9541   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9542   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9543   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9544   //     carry  = (jlong)(tmp4 >>> 64);
9545   //     z[kdx+idx+1] = (jlong)tmp3;
9546   //     z[kdx+idx] = (jlong)tmp4;
9547   //   }
9548   //   idx += 2;
9549   //   if (idx > 0) {
9550   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9551   //     z[kdx+idx] = (jlong)yz_idx1;
9552   //     carry  = (jlong)(yz_idx1 >>> 64);
9553   //   }
9554   //
9555 
9556   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9557 
9558   movl(jdx, idx);
9559   andl(jdx, 0xFFFFFFFC);
9560   shrl(jdx, 2);
9561 
9562   bind(L_third_loop);
9563   subl(jdx, 1);
9564   jcc(Assembler::negative, L_third_loop_exit);
9565   subl(idx, 4);
9566 
9567   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9568   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9569   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9570   rorxq(yz_idx2, yz_idx2, 32);
9571 
9572   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9573   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9574 
9575   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9576   rorxq(yz_idx1, yz_idx1, 32);
9577   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9578   rorxq(yz_idx2, yz_idx2, 32);
9579 
9580   if (VM_Version::supports_adx()) {
9581     adcxq(tmp3, carry);
9582     adoxq(tmp3, yz_idx1);
9583 
9584     adcxq(tmp4, tmp);
9585     adoxq(tmp4, yz_idx2);
9586 
9587     movl(carry, 0); // does not affect flags
9588     adcxq(carry2, carry);
9589     adoxq(carry2, carry);
9590   } else {
9591     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9592     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9593   }
9594   movq(carry, carry2);
9595 
9596   movl(Address(z, idx, Address::times_4, 12), tmp3);
9597   shrq(tmp3, 32);
9598   movl(Address(z, idx, Address::times_4,  8), tmp3);
9599 
9600   movl(Address(z, idx, Address::times_4,  4), tmp4);
9601   shrq(tmp4, 32);
9602   movl(Address(z, idx, Address::times_4,  0), tmp4);
9603 
9604   jmp(L_third_loop);
9605 
9606   bind (L_third_loop_exit);
9607 
9608   andl (idx, 0x3);
9609   jcc(Assembler::zero, L_post_third_loop_done);
9610 
9611   Label L_check_1;
9612   subl(idx, 2);
9613   jcc(Assembler::negative, L_check_1);
9614 
9615   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9616   rorxq(yz_idx1, yz_idx1, 32);
9617   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9618   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9619   rorxq(yz_idx2, yz_idx2, 32);
9620 
9621   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9622 
9623   movl(Address(z, idx, Address::times_4,  4), tmp3);
9624   shrq(tmp3, 32);
9625   movl(Address(z, idx, Address::times_4,  0), tmp3);
9626   movq(carry, tmp4);
9627 
9628   bind (L_check_1);
9629   addl (idx, 0x2);
9630   andl (idx, 0x1);
9631   subl(idx, 1);
9632   jcc(Assembler::negative, L_post_third_loop_done);
9633   movl(tmp4, Address(y, idx, Address::times_4,  0));
9634   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9635   movl(tmp4, Address(z, idx, Address::times_4,  0));
9636 
9637   add2_with_carry(carry2, tmp3, tmp4, carry);
9638 
9639   movl(Address(z, idx, Address::times_4,  0), tmp3);
9640   shrq(tmp3, 32);
9641 
9642   shlq(carry2, 32);
9643   orq(tmp3, carry2);
9644   movq(carry, tmp3);
9645 
9646   bind(L_post_third_loop_done);
9647 }
9648 
9649 /**
9650  * Code for BigInteger::multiplyToLen() instrinsic.
9651  *
9652  * rdi: x
9653  * rax: xlen
9654  * rsi: y
9655  * rcx: ylen
9656  * r8:  z
9657  * r11: zlen
9658  * r12: tmp1
9659  * r13: tmp2
9660  * r14: tmp3
9661  * r15: tmp4
9662  * rbx: tmp5
9663  *
9664  */
9665 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9666                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9667   ShortBranchVerifier sbv(this);
9668   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9669 
9670   push(tmp1);
9671   push(tmp2);
9672   push(tmp3);
9673   push(tmp4);
9674   push(tmp5);
9675 
9676   push(xlen);
9677   push(zlen);
9678 
9679   const Register idx = tmp1;
9680   const Register kdx = tmp2;
9681   const Register xstart = tmp3;
9682 
9683   const Register y_idx = tmp4;
9684   const Register carry = tmp5;
9685   const Register product  = xlen;
9686   const Register x_xstart = zlen;  // reuse register
9687 
9688   // First Loop.
9689   //
9690   //  final static long LONG_MASK = 0xffffffffL;
9691   //  int xstart = xlen - 1;
9692   //  int ystart = ylen - 1;
9693   //  long carry = 0;
9694   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9695   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9696   //    z[kdx] = (int)product;
9697   //    carry = product >>> 32;
9698   //  }
9699   //  z[xstart] = (int)carry;
9700   //
9701 
9702   movl(idx, ylen);      // idx = ylen;
9703   movl(kdx, zlen);      // kdx = xlen+ylen;
9704   xorq(carry, carry);   // carry = 0;
9705 
9706   Label L_done;
9707 
9708   movl(xstart, xlen);
9709   decrementl(xstart);
9710   jcc(Assembler::negative, L_done);
9711 
9712   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9713 
9714   Label L_second_loop;
9715   testl(kdx, kdx);
9716   jcc(Assembler::zero, L_second_loop);
9717 
9718   Label L_carry;
9719   subl(kdx, 1);
9720   jcc(Assembler::zero, L_carry);
9721 
9722   movl(Address(z, kdx, Address::times_4,  0), carry);
9723   shrq(carry, 32);
9724   subl(kdx, 1);
9725 
9726   bind(L_carry);
9727   movl(Address(z, kdx, Address::times_4,  0), carry);
9728 
9729   // Second and third (nested) loops.
9730   //
9731   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9732   //   carry = 0;
9733   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9734   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9735   //                    (z[k] & LONG_MASK) + carry;
9736   //     z[k] = (int)product;
9737   //     carry = product >>> 32;
9738   //   }
9739   //   z[i] = (int)carry;
9740   // }
9741   //
9742   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9743 
9744   const Register jdx = tmp1;
9745 
9746   bind(L_second_loop);
9747   xorl(carry, carry);    // carry = 0;
9748   movl(jdx, ylen);       // j = ystart+1
9749 
9750   subl(xstart, 1);       // i = xstart-1;
9751   jcc(Assembler::negative, L_done);
9752 
9753   push (z);
9754 
9755   Label L_last_x;
9756   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9757   subl(xstart, 1);       // i = xstart-1;
9758   jcc(Assembler::negative, L_last_x);
9759 
9760   if (UseBMI2Instructions) {
9761     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9762     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9763   } else {
9764     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9765     rorq(x_xstart, 32);  // convert big-endian to little-endian
9766   }
9767 
9768   Label L_third_loop_prologue;
9769   bind(L_third_loop_prologue);
9770 
9771   push (x);
9772   push (xstart);
9773   push (ylen);
9774 
9775 
9776   if (UseBMI2Instructions) {
9777     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9778   } else { // !UseBMI2Instructions
9779     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9780   }
9781 
9782   pop(ylen);
9783   pop(xlen);
9784   pop(x);
9785   pop(z);
9786 
9787   movl(tmp3, xlen);
9788   addl(tmp3, 1);
9789   movl(Address(z, tmp3, Address::times_4,  0), carry);
9790   subl(tmp3, 1);
9791   jccb(Assembler::negative, L_done);
9792 
9793   shrq(carry, 32);
9794   movl(Address(z, tmp3, Address::times_4,  0), carry);
9795   jmp(L_second_loop);
9796 
9797   // Next infrequent code is moved outside loops.
9798   bind(L_last_x);
9799   if (UseBMI2Instructions) {
9800     movl(rdx, Address(x,  0));
9801   } else {
9802     movl(x_xstart, Address(x,  0));
9803   }
9804   jmp(L_third_loop_prologue);
9805 
9806   bind(L_done);
9807 
9808   pop(zlen);
9809   pop(xlen);
9810 
9811   pop(tmp5);
9812   pop(tmp4);
9813   pop(tmp3);
9814   pop(tmp2);
9815   pop(tmp1);
9816 }
9817 
9818 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9819   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9820   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9821   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9822   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9823   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9824   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9825   Label SAME_TILL_END, DONE;
9826   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9827 
9828   //scale is in rcx in both Win64 and Unix
9829   ShortBranchVerifier sbv(this);
9830 
9831   shlq(length);
9832   xorq(result, result);
9833 
9834   if ((UseAVX > 2) &&
9835       VM_Version::supports_avx512vlbw()) {
9836     set_vector_masking();  // opening of the stub context for programming mask registers
9837     cmpq(length, 64);
9838     jcc(Assembler::less, VECTOR32_TAIL);
9839     movq(tmp1, length);
9840     andq(tmp1, 0x3F);      // tail count
9841     andq(length, ~(0x3F)); //vector count
9842 
9843     bind(VECTOR64_LOOP);
9844     // AVX512 code to compare 64 byte vectors.
9845     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9846     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9847     kortestql(k7, k7);
9848     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9849     addq(result, 64);
9850     subq(length, 64);
9851     jccb(Assembler::notZero, VECTOR64_LOOP);
9852 
9853     //bind(VECTOR64_TAIL);
9854     testq(tmp1, tmp1);
9855     jcc(Assembler::zero, SAME_TILL_END);
9856 
9857     bind(VECTOR64_TAIL);
9858     // AVX512 code to compare upto 63 byte vectors.
9859     // Save k1
9860     kmovql(k3, k1);
9861     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9862     shlxq(tmp2, tmp2, tmp1);
9863     notq(tmp2);
9864     kmovql(k1, tmp2);
9865 
9866     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9867     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9868 
9869     ktestql(k7, k1);
9870     // Restore k1
9871     kmovql(k1, k3);
9872     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9873 
9874     bind(VECTOR64_NOT_EQUAL);
9875     kmovql(tmp1, k7);
9876     notq(tmp1);
9877     tzcntq(tmp1, tmp1);
9878     addq(result, tmp1);
9879     shrq(result);
9880     jmp(DONE);
9881     bind(VECTOR32_TAIL);
9882     clear_vector_masking();   // closing of the stub context for programming mask registers
9883   }
9884 
9885   cmpq(length, 8);
9886   jcc(Assembler::equal, VECTOR8_LOOP);
9887   jcc(Assembler::less, VECTOR4_TAIL);
9888 
9889   if (UseAVX >= 2) {
9890 
9891     cmpq(length, 16);
9892     jcc(Assembler::equal, VECTOR16_LOOP);
9893     jcc(Assembler::less, VECTOR8_LOOP);
9894 
9895     cmpq(length, 32);
9896     jccb(Assembler::less, VECTOR16_TAIL);
9897 
9898     subq(length, 32);
9899     bind(VECTOR32_LOOP);
9900     vmovdqu(rymm0, Address(obja, result));
9901     vmovdqu(rymm1, Address(objb, result));
9902     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9903     vptest(rymm2, rymm2);
9904     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9905     addq(result, 32);
9906     subq(length, 32);
9907     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9908     addq(length, 32);
9909     jcc(Assembler::equal, SAME_TILL_END);
9910     //falling through if less than 32 bytes left //close the branch here.
9911 
9912     bind(VECTOR16_TAIL);
9913     cmpq(length, 16);
9914     jccb(Assembler::less, VECTOR8_TAIL);
9915     bind(VECTOR16_LOOP);
9916     movdqu(rymm0, Address(obja, result));
9917     movdqu(rymm1, Address(objb, result));
9918     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9919     ptest(rymm2, rymm2);
9920     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9921     addq(result, 16);
9922     subq(length, 16);
9923     jcc(Assembler::equal, SAME_TILL_END);
9924     //falling through if less than 16 bytes left
9925   } else {//regular intrinsics
9926 
9927     cmpq(length, 16);
9928     jccb(Assembler::less, VECTOR8_TAIL);
9929 
9930     subq(length, 16);
9931     bind(VECTOR16_LOOP);
9932     movdqu(rymm0, Address(obja, result));
9933     movdqu(rymm1, Address(objb, result));
9934     pxor(rymm0, rymm1);
9935     ptest(rymm0, rymm0);
9936     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9937     addq(result, 16);
9938     subq(length, 16);
9939     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9940     addq(length, 16);
9941     jcc(Assembler::equal, SAME_TILL_END);
9942     //falling through if less than 16 bytes left
9943   }
9944 
9945   bind(VECTOR8_TAIL);
9946   cmpq(length, 8);
9947   jccb(Assembler::less, VECTOR4_TAIL);
9948   bind(VECTOR8_LOOP);
9949   movq(tmp1, Address(obja, result));
9950   movq(tmp2, Address(objb, result));
9951   xorq(tmp1, tmp2);
9952   testq(tmp1, tmp1);
9953   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9954   addq(result, 8);
9955   subq(length, 8);
9956   jcc(Assembler::equal, SAME_TILL_END);
9957   //falling through if less than 8 bytes left
9958 
9959   bind(VECTOR4_TAIL);
9960   cmpq(length, 4);
9961   jccb(Assembler::less, BYTES_TAIL);
9962   bind(VECTOR4_LOOP);
9963   movl(tmp1, Address(obja, result));
9964   xorl(tmp1, Address(objb, result));
9965   testl(tmp1, tmp1);
9966   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9967   addq(result, 4);
9968   subq(length, 4);
9969   jcc(Assembler::equal, SAME_TILL_END);
9970   //falling through if less than 4 bytes left
9971 
9972   bind(BYTES_TAIL);
9973   bind(BYTES_LOOP);
9974   load_unsigned_byte(tmp1, Address(obja, result));
9975   load_unsigned_byte(tmp2, Address(objb, result));
9976   xorl(tmp1, tmp2);
9977   testl(tmp1, tmp1);
9978   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9979   decq(length);
9980   jccb(Assembler::zero, SAME_TILL_END);
9981   incq(result);
9982   load_unsigned_byte(tmp1, Address(obja, result));
9983   load_unsigned_byte(tmp2, Address(objb, result));
9984   xorl(tmp1, tmp2);
9985   testl(tmp1, tmp1);
9986   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9987   decq(length);
9988   jccb(Assembler::zero, SAME_TILL_END);
9989   incq(result);
9990   load_unsigned_byte(tmp1, Address(obja, result));
9991   load_unsigned_byte(tmp2, Address(objb, result));
9992   xorl(tmp1, tmp2);
9993   testl(tmp1, tmp1);
9994   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9995   jmpb(SAME_TILL_END);
9996 
9997   if (UseAVX >= 2) {
9998     bind(VECTOR32_NOT_EQUAL);
9999     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
10000     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
10001     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
10002     vpmovmskb(tmp1, rymm0);
10003     bsfq(tmp1, tmp1);
10004     addq(result, tmp1);
10005     shrq(result);
10006     jmpb(DONE);
10007   }
10008 
10009   bind(VECTOR16_NOT_EQUAL);
10010   if (UseAVX >= 2) {
10011     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
10012     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
10013     pxor(rymm0, rymm2);
10014   } else {
10015     pcmpeqb(rymm2, rymm2);
10016     pxor(rymm0, rymm1);
10017     pcmpeqb(rymm0, rymm1);
10018     pxor(rymm0, rymm2);
10019   }
10020   pmovmskb(tmp1, rymm0);
10021   bsfq(tmp1, tmp1);
10022   addq(result, tmp1);
10023   shrq(result);
10024   jmpb(DONE);
10025 
10026   bind(VECTOR8_NOT_EQUAL);
10027   bind(VECTOR4_NOT_EQUAL);
10028   bsfq(tmp1, tmp1);
10029   shrq(tmp1, 3);
10030   addq(result, tmp1);
10031   bind(BYTES_NOT_EQUAL);
10032   shrq(result);
10033   jmpb(DONE);
10034 
10035   bind(SAME_TILL_END);
10036   mov64(result, -1);
10037 
10038   bind(DONE);
10039 }
10040 
10041 //Helper functions for square_to_len()
10042 
10043 /**
10044  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
10045  * Preserves x and z and modifies rest of the registers.
10046  */
10047 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10048   // Perform square and right shift by 1
10049   // Handle odd xlen case first, then for even xlen do the following
10050   // jlong carry = 0;
10051   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
10052   //     huge_128 product = x[j:j+1] * x[j:j+1];
10053   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
10054   //     z[i+2:i+3] = (jlong)(product >>> 1);
10055   //     carry = (jlong)product;
10056   // }
10057 
10058   xorq(tmp5, tmp5);     // carry
10059   xorq(rdxReg, rdxReg);
10060   xorl(tmp1, tmp1);     // index for x
10061   xorl(tmp4, tmp4);     // index for z
10062 
10063   Label L_first_loop, L_first_loop_exit;
10064 
10065   testl(xlen, 1);
10066   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
10067 
10068   // Square and right shift by 1 the odd element using 32 bit multiply
10069   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
10070   imulq(raxReg, raxReg);
10071   shrq(raxReg, 1);
10072   adcq(tmp5, 0);
10073   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
10074   incrementl(tmp1);
10075   addl(tmp4, 2);
10076 
10077   // Square and  right shift by 1 the rest using 64 bit multiply
10078   bind(L_first_loop);
10079   cmpptr(tmp1, xlen);
10080   jccb(Assembler::equal, L_first_loop_exit);
10081 
10082   // Square
10083   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
10084   rorq(raxReg, 32);    // convert big-endian to little-endian
10085   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
10086 
10087   // Right shift by 1 and save carry
10088   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
10089   rcrq(rdxReg, 1);
10090   rcrq(raxReg, 1);
10091   adcq(tmp5, 0);
10092 
10093   // Store result in z
10094   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
10095   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
10096 
10097   // Update indices for x and z
10098   addl(tmp1, 2);
10099   addl(tmp4, 4);
10100   jmp(L_first_loop);
10101 
10102   bind(L_first_loop_exit);
10103 }
10104 
10105 
10106 /**
10107  * Perform the following multiply add operation using BMI2 instructions
10108  * carry:sum = sum + op1*op2 + carry
10109  * op2 should be in rdx
10110  * op2 is preserved, all other registers are modified
10111  */
10112 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
10113   // assert op2 is rdx
10114   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
10115   addq(sum, carry);
10116   adcq(tmp2, 0);
10117   addq(sum, op1);
10118   adcq(tmp2, 0);
10119   movq(carry, tmp2);
10120 }
10121 
10122 /**
10123  * Perform the following multiply add operation:
10124  * carry:sum = sum + op1*op2 + carry
10125  * Preserves op1, op2 and modifies rest of registers
10126  */
10127 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
10128   // rdx:rax = op1 * op2
10129   movq(raxReg, op2);
10130   mulq(op1);
10131 
10132   //  rdx:rax = sum + carry + rdx:rax
10133   addq(sum, carry);
10134   adcq(rdxReg, 0);
10135   addq(sum, raxReg);
10136   adcq(rdxReg, 0);
10137 
10138   // carry:sum = rdx:sum
10139   movq(carry, rdxReg);
10140 }
10141 
10142 /**
10143  * Add 64 bit long carry into z[] with carry propogation.
10144  * Preserves z and carry register values and modifies rest of registers.
10145  *
10146  */
10147 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
10148   Label L_fourth_loop, L_fourth_loop_exit;
10149 
10150   movl(tmp1, 1);
10151   subl(zlen, 2);
10152   addq(Address(z, zlen, Address::times_4, 0), carry);
10153 
10154   bind(L_fourth_loop);
10155   jccb(Assembler::carryClear, L_fourth_loop_exit);
10156   subl(zlen, 2);
10157   jccb(Assembler::negative, L_fourth_loop_exit);
10158   addq(Address(z, zlen, Address::times_4, 0), tmp1);
10159   jmp(L_fourth_loop);
10160   bind(L_fourth_loop_exit);
10161 }
10162 
10163 /**
10164  * Shift z[] left by 1 bit.
10165  * Preserves x, len, z and zlen registers and modifies rest of the registers.
10166  *
10167  */
10168 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
10169 
10170   Label L_fifth_loop, L_fifth_loop_exit;
10171 
10172   // Fifth loop
10173   // Perform primitiveLeftShift(z, zlen, 1)
10174 
10175   const Register prev_carry = tmp1;
10176   const Register new_carry = tmp4;
10177   const Register value = tmp2;
10178   const Register zidx = tmp3;
10179 
10180   // int zidx, carry;
10181   // long value;
10182   // carry = 0;
10183   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
10184   //    (carry:value)  = (z[i] << 1) | carry ;
10185   //    z[i] = value;
10186   // }
10187 
10188   movl(zidx, zlen);
10189   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
10190 
10191   bind(L_fifth_loop);
10192   decl(zidx);  // Use decl to preserve carry flag
10193   decl(zidx);
10194   jccb(Assembler::negative, L_fifth_loop_exit);
10195 
10196   if (UseBMI2Instructions) {
10197      movq(value, Address(z, zidx, Address::times_4, 0));
10198      rclq(value, 1);
10199      rorxq(value, value, 32);
10200      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10201   }
10202   else {
10203     // clear new_carry
10204     xorl(new_carry, new_carry);
10205 
10206     // Shift z[i] by 1, or in previous carry and save new carry
10207     movq(value, Address(z, zidx, Address::times_4, 0));
10208     shlq(value, 1);
10209     adcl(new_carry, 0);
10210 
10211     orq(value, prev_carry);
10212     rorq(value, 0x20);
10213     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
10214 
10215     // Set previous carry = new carry
10216     movl(prev_carry, new_carry);
10217   }
10218   jmp(L_fifth_loop);
10219 
10220   bind(L_fifth_loop_exit);
10221 }
10222 
10223 
10224 /**
10225  * Code for BigInteger::squareToLen() intrinsic
10226  *
10227  * rdi: x
10228  * rsi: len
10229  * r8:  z
10230  * rcx: zlen
10231  * r12: tmp1
10232  * r13: tmp2
10233  * r14: tmp3
10234  * r15: tmp4
10235  * rbx: tmp5
10236  *
10237  */
10238 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) {
10239 
10240   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;
10241   push(tmp1);
10242   push(tmp2);
10243   push(tmp3);
10244   push(tmp4);
10245   push(tmp5);
10246 
10247   // First loop
10248   // Store the squares, right shifted one bit (i.e., divided by 2).
10249   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
10250 
10251   // Add in off-diagonal sums.
10252   //
10253   // Second, third (nested) and fourth loops.
10254   // zlen +=2;
10255   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
10256   //    carry = 0;
10257   //    long op2 = x[xidx:xidx+1];
10258   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
10259   //       k -= 2;
10260   //       long op1 = x[j:j+1];
10261   //       long sum = z[k:k+1];
10262   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
10263   //       z[k:k+1] = sum;
10264   //    }
10265   //    add_one_64(z, k, carry, tmp_regs);
10266   // }
10267 
10268   const Register carry = tmp5;
10269   const Register sum = tmp3;
10270   const Register op1 = tmp4;
10271   Register op2 = tmp2;
10272 
10273   push(zlen);
10274   push(len);
10275   addl(zlen,2);
10276   bind(L_second_loop);
10277   xorq(carry, carry);
10278   subl(zlen, 4);
10279   subl(len, 2);
10280   push(zlen);
10281   push(len);
10282   cmpl(len, 0);
10283   jccb(Assembler::lessEqual, L_second_loop_exit);
10284 
10285   // Multiply an array by one 64 bit long.
10286   if (UseBMI2Instructions) {
10287     op2 = rdxReg;
10288     movq(op2, Address(x, len, Address::times_4,  0));
10289     rorxq(op2, op2, 32);
10290   }
10291   else {
10292     movq(op2, Address(x, len, Address::times_4,  0));
10293     rorq(op2, 32);
10294   }
10295 
10296   bind(L_third_loop);
10297   decrementl(len);
10298   jccb(Assembler::negative, L_third_loop_exit);
10299   decrementl(len);
10300   jccb(Assembler::negative, L_last_x);
10301 
10302   movq(op1, Address(x, len, Address::times_4,  0));
10303   rorq(op1, 32);
10304 
10305   bind(L_multiply);
10306   subl(zlen, 2);
10307   movq(sum, Address(z, zlen, Address::times_4,  0));
10308 
10309   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10310   if (UseBMI2Instructions) {
10311     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10312   }
10313   else {
10314     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10315   }
10316 
10317   movq(Address(z, zlen, Address::times_4, 0), sum);
10318 
10319   jmp(L_third_loop);
10320   bind(L_third_loop_exit);
10321 
10322   // Fourth loop
10323   // Add 64 bit long carry into z with carry propogation.
10324   // Uses offsetted zlen.
10325   add_one_64(z, zlen, carry, tmp1);
10326 
10327   pop(len);
10328   pop(zlen);
10329   jmp(L_second_loop);
10330 
10331   // Next infrequent code is moved outside loops.
10332   bind(L_last_x);
10333   movl(op1, Address(x, 0));
10334   jmp(L_multiply);
10335 
10336   bind(L_second_loop_exit);
10337   pop(len);
10338   pop(zlen);
10339   pop(len);
10340   pop(zlen);
10341 
10342   // Fifth loop
10343   // Shift z left 1 bit.
10344   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10345 
10346   // z[zlen-1] |= x[len-1] & 1;
10347   movl(tmp3, Address(x, len, Address::times_4, -4));
10348   andl(tmp3, 1);
10349   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10350 
10351   pop(tmp5);
10352   pop(tmp4);
10353   pop(tmp3);
10354   pop(tmp2);
10355   pop(tmp1);
10356 }
10357 
10358 /**
10359  * Helper function for mul_add()
10360  * Multiply the in[] by int k and add to out[] starting at offset offs using
10361  * 128 bit by 32 bit multiply and return the carry in tmp5.
10362  * Only quad int aligned length of in[] is operated on in this function.
10363  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10364  * This function preserves out, in and k registers.
10365  * len and offset point to the appropriate index in "in" & "out" correspondingly
10366  * tmp5 has the carry.
10367  * other registers are temporary and are modified.
10368  *
10369  */
10370 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10371   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10372   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10373 
10374   Label L_first_loop, L_first_loop_exit;
10375 
10376   movl(tmp1, len);
10377   shrl(tmp1, 2);
10378 
10379   bind(L_first_loop);
10380   subl(tmp1, 1);
10381   jccb(Assembler::negative, L_first_loop_exit);
10382 
10383   subl(len, 4);
10384   subl(offset, 4);
10385 
10386   Register op2 = tmp2;
10387   const Register sum = tmp3;
10388   const Register op1 = tmp4;
10389   const Register carry = tmp5;
10390 
10391   if (UseBMI2Instructions) {
10392     op2 = rdxReg;
10393   }
10394 
10395   movq(op1, Address(in, len, Address::times_4,  8));
10396   rorq(op1, 32);
10397   movq(sum, Address(out, offset, Address::times_4,  8));
10398   rorq(sum, 32);
10399   if (UseBMI2Instructions) {
10400     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10401   }
10402   else {
10403     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10404   }
10405   // Store back in big endian from little endian
10406   rorq(sum, 0x20);
10407   movq(Address(out, offset, Address::times_4,  8), sum);
10408 
10409   movq(op1, Address(in, len, Address::times_4,  0));
10410   rorq(op1, 32);
10411   movq(sum, Address(out, offset, Address::times_4,  0));
10412   rorq(sum, 32);
10413   if (UseBMI2Instructions) {
10414     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10415   }
10416   else {
10417     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10418   }
10419   // Store back in big endian from little endian
10420   rorq(sum, 0x20);
10421   movq(Address(out, offset, Address::times_4,  0), sum);
10422 
10423   jmp(L_first_loop);
10424   bind(L_first_loop_exit);
10425 }
10426 
10427 /**
10428  * Code for BigInteger::mulAdd() intrinsic
10429  *
10430  * rdi: out
10431  * rsi: in
10432  * r11: offs (out.length - offset)
10433  * rcx: len
10434  * r8:  k
10435  * r12: tmp1
10436  * r13: tmp2
10437  * r14: tmp3
10438  * r15: tmp4
10439  * rbx: tmp5
10440  * Multiply the in[] by word k and add to out[], return the carry in rax
10441  */
10442 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10443    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10444    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10445 
10446   Label L_carry, L_last_in, L_done;
10447 
10448 // carry = 0;
10449 // for (int j=len-1; j >= 0; j--) {
10450 //    long product = (in[j] & LONG_MASK) * kLong +
10451 //                   (out[offs] & LONG_MASK) + carry;
10452 //    out[offs--] = (int)product;
10453 //    carry = product >>> 32;
10454 // }
10455 //
10456   push(tmp1);
10457   push(tmp2);
10458   push(tmp3);
10459   push(tmp4);
10460   push(tmp5);
10461 
10462   Register op2 = tmp2;
10463   const Register sum = tmp3;
10464   const Register op1 = tmp4;
10465   const Register carry =  tmp5;
10466 
10467   if (UseBMI2Instructions) {
10468     op2 = rdxReg;
10469     movl(op2, k);
10470   }
10471   else {
10472     movl(op2, k);
10473   }
10474 
10475   xorq(carry, carry);
10476 
10477   //First loop
10478 
10479   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10480   //The carry is in tmp5
10481   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10482 
10483   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10484   decrementl(len);
10485   jccb(Assembler::negative, L_carry);
10486   decrementl(len);
10487   jccb(Assembler::negative, L_last_in);
10488 
10489   movq(op1, Address(in, len, Address::times_4,  0));
10490   rorq(op1, 32);
10491 
10492   subl(offs, 2);
10493   movq(sum, Address(out, offs, Address::times_4,  0));
10494   rorq(sum, 32);
10495 
10496   if (UseBMI2Instructions) {
10497     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10498   }
10499   else {
10500     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10501   }
10502 
10503   // Store back in big endian from little endian
10504   rorq(sum, 0x20);
10505   movq(Address(out, offs, Address::times_4,  0), sum);
10506 
10507   testl(len, len);
10508   jccb(Assembler::zero, L_carry);
10509 
10510   //Multiply the last in[] entry, if any
10511   bind(L_last_in);
10512   movl(op1, Address(in, 0));
10513   movl(sum, Address(out, offs, Address::times_4,  -4));
10514 
10515   movl(raxReg, k);
10516   mull(op1); //tmp4 * eax -> edx:eax
10517   addl(sum, carry);
10518   adcl(rdxReg, 0);
10519   addl(sum, raxReg);
10520   adcl(rdxReg, 0);
10521   movl(carry, rdxReg);
10522 
10523   movl(Address(out, offs, Address::times_4,  -4), sum);
10524 
10525   bind(L_carry);
10526   //return tmp5/carry as carry in rax
10527   movl(rax, carry);
10528 
10529   bind(L_done);
10530   pop(tmp5);
10531   pop(tmp4);
10532   pop(tmp3);
10533   pop(tmp2);
10534   pop(tmp1);
10535 }
10536 #endif
10537 
10538 /**
10539  * Emits code to update CRC-32 with a byte value according to constants in table
10540  *
10541  * @param [in,out]crc   Register containing the crc.
10542  * @param [in]val       Register containing the byte to fold into the CRC.
10543  * @param [in]table     Register containing the table of crc constants.
10544  *
10545  * uint32_t crc;
10546  * val = crc_table[(val ^ crc) & 0xFF];
10547  * crc = val ^ (crc >> 8);
10548  *
10549  */
10550 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10551   xorl(val, crc);
10552   andl(val, 0xFF);
10553   shrl(crc, 8); // unsigned shift
10554   xorl(crc, Address(table, val, Address::times_4, 0));
10555 }
10556 
10557 /**
10558  * Fold 128-bit data chunk
10559  */
10560 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10561   if (UseAVX > 0) {
10562     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10563     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10564     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10565     pxor(xcrc, xtmp);
10566   } else {
10567     movdqa(xtmp, xcrc);
10568     pclmulhdq(xtmp, xK);   // [123:64]
10569     pclmulldq(xcrc, xK);   // [63:0]
10570     pxor(xcrc, xtmp);
10571     movdqu(xtmp, Address(buf, offset));
10572     pxor(xcrc, xtmp);
10573   }
10574 }
10575 
10576 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10577   if (UseAVX > 0) {
10578     vpclmulhdq(xtmp, xK, xcrc);
10579     vpclmulldq(xcrc, xK, xcrc);
10580     pxor(xcrc, xbuf);
10581     pxor(xcrc, xtmp);
10582   } else {
10583     movdqa(xtmp, xcrc);
10584     pclmulhdq(xtmp, xK);
10585     pclmulldq(xcrc, xK);
10586     pxor(xcrc, xbuf);
10587     pxor(xcrc, xtmp);
10588   }
10589 }
10590 
10591 /**
10592  * 8-bit folds to compute 32-bit CRC
10593  *
10594  * uint64_t xcrc;
10595  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10596  */
10597 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10598   movdl(tmp, xcrc);
10599   andl(tmp, 0xFF);
10600   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10601   psrldq(xcrc, 1); // unsigned shift one byte
10602   pxor(xcrc, xtmp);
10603 }
10604 
10605 /**
10606  * uint32_t crc;
10607  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10608  */
10609 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10610   movl(tmp, crc);
10611   andl(tmp, 0xFF);
10612   shrl(crc, 8);
10613   xorl(crc, Address(table, tmp, Address::times_4, 0));
10614 }
10615 
10616 /**
10617  * @param crc   register containing existing CRC (32-bit)
10618  * @param buf   register pointing to input byte buffer (byte*)
10619  * @param len   register containing number of bytes
10620  * @param table register that will contain address of CRC table
10621  * @param tmp   scratch register
10622  */
10623 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10624   assert_different_registers(crc, buf, len, table, tmp, rax);
10625 
10626   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10627   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10628 
10629   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10630   // context for the registers used, where all instructions below are using 128-bit mode
10631   // On EVEX without VL and BW, these instructions will all be AVX.
10632   if (VM_Version::supports_avx512vlbw()) {
10633     movl(tmp, 0xffff);
10634     kmovwl(k1, tmp);
10635   }
10636 
10637   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10638   notl(crc); // ~crc
10639   cmpl(len, 16);
10640   jcc(Assembler::less, L_tail);
10641 
10642   // Align buffer to 16 bytes
10643   movl(tmp, buf);
10644   andl(tmp, 0xF);
10645   jccb(Assembler::zero, L_aligned);
10646   subl(tmp,  16);
10647   addl(len, tmp);
10648 
10649   align(4);
10650   BIND(L_align_loop);
10651   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10652   update_byte_crc32(crc, rax, table);
10653   increment(buf);
10654   incrementl(tmp);
10655   jccb(Assembler::less, L_align_loop);
10656 
10657   BIND(L_aligned);
10658   movl(tmp, len); // save
10659   shrl(len, 4);
10660   jcc(Assembler::zero, L_tail_restore);
10661 
10662   // Fold crc into first bytes of vector
10663   movdqa(xmm1, Address(buf, 0));
10664   movdl(rax, xmm1);
10665   xorl(crc, rax);
10666   if (VM_Version::supports_sse4_1()) {
10667     pinsrd(xmm1, crc, 0);
10668   } else {
10669     pinsrw(xmm1, crc, 0);
10670     shrl(crc, 16);
10671     pinsrw(xmm1, crc, 1);
10672   }
10673   addptr(buf, 16);
10674   subl(len, 4); // len > 0
10675   jcc(Assembler::less, L_fold_tail);
10676 
10677   movdqa(xmm2, Address(buf,  0));
10678   movdqa(xmm3, Address(buf, 16));
10679   movdqa(xmm4, Address(buf, 32));
10680   addptr(buf, 48);
10681   subl(len, 3);
10682   jcc(Assembler::lessEqual, L_fold_512b);
10683 
10684   // Fold total 512 bits of polynomial on each iteration,
10685   // 128 bits per each of 4 parallel streams.
10686   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10687 
10688   align(32);
10689   BIND(L_fold_512b_loop);
10690   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10691   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10692   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10693   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10694   addptr(buf, 64);
10695   subl(len, 4);
10696   jcc(Assembler::greater, L_fold_512b_loop);
10697 
10698   // Fold 512 bits to 128 bits.
10699   BIND(L_fold_512b);
10700   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10701   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10702   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10703   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10704 
10705   // Fold the rest of 128 bits data chunks
10706   BIND(L_fold_tail);
10707   addl(len, 3);
10708   jccb(Assembler::lessEqual, L_fold_128b);
10709   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10710 
10711   BIND(L_fold_tail_loop);
10712   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10713   addptr(buf, 16);
10714   decrementl(len);
10715   jccb(Assembler::greater, L_fold_tail_loop);
10716 
10717   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10718   BIND(L_fold_128b);
10719   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10720   if (UseAVX > 0) {
10721     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10722     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10723     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10724   } else {
10725     movdqa(xmm2, xmm0);
10726     pclmulqdq(xmm2, xmm1, 0x1);
10727     movdqa(xmm3, xmm0);
10728     pand(xmm3, xmm2);
10729     pclmulqdq(xmm0, xmm3, 0x1);
10730   }
10731   psrldq(xmm1, 8);
10732   psrldq(xmm2, 4);
10733   pxor(xmm0, xmm1);
10734   pxor(xmm0, xmm2);
10735 
10736   // 8 8-bit folds to compute 32-bit CRC.
10737   for (int j = 0; j < 4; j++) {
10738     fold_8bit_crc32(xmm0, table, xmm1, rax);
10739   }
10740   movdl(crc, xmm0); // mov 32 bits to general register
10741   for (int j = 0; j < 4; j++) {
10742     fold_8bit_crc32(crc, table, rax);
10743   }
10744 
10745   BIND(L_tail_restore);
10746   movl(len, tmp); // restore
10747   BIND(L_tail);
10748   andl(len, 0xf);
10749   jccb(Assembler::zero, L_exit);
10750 
10751   // Fold the rest of bytes
10752   align(4);
10753   BIND(L_tail_loop);
10754   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10755   update_byte_crc32(crc, rax, table);
10756   increment(buf);
10757   decrementl(len);
10758   jccb(Assembler::greater, L_tail_loop);
10759 
10760   BIND(L_exit);
10761   notl(crc); // ~c
10762 }
10763 
10764 #ifdef _LP64
10765 // S. Gueron / Information Processing Letters 112 (2012) 184
10766 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10767 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10768 // Output: the 64-bit carry-less product of B * CONST
10769 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10770                                      Register tmp1, Register tmp2, Register tmp3) {
10771   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10772   if (n > 0) {
10773     addq(tmp3, n * 256 * 8);
10774   }
10775   //    Q1 = TABLEExt[n][B & 0xFF];
10776   movl(tmp1, in);
10777   andl(tmp1, 0x000000FF);
10778   shll(tmp1, 3);
10779   addq(tmp1, tmp3);
10780   movq(tmp1, Address(tmp1, 0));
10781 
10782   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10783   movl(tmp2, in);
10784   shrl(tmp2, 8);
10785   andl(tmp2, 0x000000FF);
10786   shll(tmp2, 3);
10787   addq(tmp2, tmp3);
10788   movq(tmp2, Address(tmp2, 0));
10789 
10790   shlq(tmp2, 8);
10791   xorq(tmp1, tmp2);
10792 
10793   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10794   movl(tmp2, in);
10795   shrl(tmp2, 16);
10796   andl(tmp2, 0x000000FF);
10797   shll(tmp2, 3);
10798   addq(tmp2, tmp3);
10799   movq(tmp2, Address(tmp2, 0));
10800 
10801   shlq(tmp2, 16);
10802   xorq(tmp1, tmp2);
10803 
10804   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10805   shrl(in, 24);
10806   andl(in, 0x000000FF);
10807   shll(in, 3);
10808   addq(in, tmp3);
10809   movq(in, Address(in, 0));
10810 
10811   shlq(in, 24);
10812   xorq(in, tmp1);
10813   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10814 }
10815 
10816 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10817                                       Register in_out,
10818                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10819                                       XMMRegister w_xtmp2,
10820                                       Register tmp1,
10821                                       Register n_tmp2, Register n_tmp3) {
10822   if (is_pclmulqdq_supported) {
10823     movdl(w_xtmp1, in_out); // modified blindly
10824 
10825     movl(tmp1, const_or_pre_comp_const_index);
10826     movdl(w_xtmp2, tmp1);
10827     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10828 
10829     movdq(in_out, w_xtmp1);
10830   } else {
10831     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10832   }
10833 }
10834 
10835 // Recombination Alternative 2: No bit-reflections
10836 // T1 = (CRC_A * U1) << 1
10837 // T2 = (CRC_B * U2) << 1
10838 // C1 = T1 >> 32
10839 // C2 = T2 >> 32
10840 // T1 = T1 & 0xFFFFFFFF
10841 // T2 = T2 & 0xFFFFFFFF
10842 // T1 = CRC32(0, T1)
10843 // T2 = CRC32(0, T2)
10844 // C1 = C1 ^ T1
10845 // C2 = C2 ^ T2
10846 // CRC = C1 ^ C2 ^ CRC_C
10847 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,
10848                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10849                                      Register tmp1, Register tmp2,
10850                                      Register n_tmp3) {
10851   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10852   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10853   shlq(in_out, 1);
10854   movl(tmp1, in_out);
10855   shrq(in_out, 32);
10856   xorl(tmp2, tmp2);
10857   crc32(tmp2, tmp1, 4);
10858   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10859   shlq(in1, 1);
10860   movl(tmp1, in1);
10861   shrq(in1, 32);
10862   xorl(tmp2, tmp2);
10863   crc32(tmp2, tmp1, 4);
10864   xorl(in1, tmp2);
10865   xorl(in_out, in1);
10866   xorl(in_out, in2);
10867 }
10868 
10869 // Set N to predefined value
10870 // Subtract from a lenght of a buffer
10871 // execute in a loop:
10872 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10873 // for i = 1 to N do
10874 //  CRC_A = CRC32(CRC_A, A[i])
10875 //  CRC_B = CRC32(CRC_B, B[i])
10876 //  CRC_C = CRC32(CRC_C, C[i])
10877 // end for
10878 // Recombine
10879 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,
10880                                        Register in_out1, Register in_out2, Register in_out3,
10881                                        Register tmp1, Register tmp2, Register tmp3,
10882                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10883                                        Register tmp4, Register tmp5,
10884                                        Register n_tmp6) {
10885   Label L_processPartitions;
10886   Label L_processPartition;
10887   Label L_exit;
10888 
10889   bind(L_processPartitions);
10890   cmpl(in_out1, 3 * size);
10891   jcc(Assembler::less, L_exit);
10892     xorl(tmp1, tmp1);
10893     xorl(tmp2, tmp2);
10894     movq(tmp3, in_out2);
10895     addq(tmp3, size);
10896 
10897     bind(L_processPartition);
10898       crc32(in_out3, Address(in_out2, 0), 8);
10899       crc32(tmp1, Address(in_out2, size), 8);
10900       crc32(tmp2, Address(in_out2, size * 2), 8);
10901       addq(in_out2, 8);
10902       cmpq(in_out2, tmp3);
10903       jcc(Assembler::less, L_processPartition);
10904     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10905             w_xtmp1, w_xtmp2, w_xtmp3,
10906             tmp4, tmp5,
10907             n_tmp6);
10908     addq(in_out2, 2 * size);
10909     subl(in_out1, 3 * size);
10910     jmp(L_processPartitions);
10911 
10912   bind(L_exit);
10913 }
10914 #else
10915 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10916                                      Register tmp1, Register tmp2, Register tmp3,
10917                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10918   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10919   if (n > 0) {
10920     addl(tmp3, n * 256 * 8);
10921   }
10922   //    Q1 = TABLEExt[n][B & 0xFF];
10923   movl(tmp1, in_out);
10924   andl(tmp1, 0x000000FF);
10925   shll(tmp1, 3);
10926   addl(tmp1, tmp3);
10927   movq(xtmp1, Address(tmp1, 0));
10928 
10929   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10930   movl(tmp2, in_out);
10931   shrl(tmp2, 8);
10932   andl(tmp2, 0x000000FF);
10933   shll(tmp2, 3);
10934   addl(tmp2, tmp3);
10935   movq(xtmp2, Address(tmp2, 0));
10936 
10937   psllq(xtmp2, 8);
10938   pxor(xtmp1, xtmp2);
10939 
10940   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10941   movl(tmp2, in_out);
10942   shrl(tmp2, 16);
10943   andl(tmp2, 0x000000FF);
10944   shll(tmp2, 3);
10945   addl(tmp2, tmp3);
10946   movq(xtmp2, Address(tmp2, 0));
10947 
10948   psllq(xtmp2, 16);
10949   pxor(xtmp1, xtmp2);
10950 
10951   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10952   shrl(in_out, 24);
10953   andl(in_out, 0x000000FF);
10954   shll(in_out, 3);
10955   addl(in_out, tmp3);
10956   movq(xtmp2, Address(in_out, 0));
10957 
10958   psllq(xtmp2, 24);
10959   pxor(xtmp1, xtmp2); // Result in CXMM
10960   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10961 }
10962 
10963 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10964                                       Register in_out,
10965                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10966                                       XMMRegister w_xtmp2,
10967                                       Register tmp1,
10968                                       Register n_tmp2, Register n_tmp3) {
10969   if (is_pclmulqdq_supported) {
10970     movdl(w_xtmp1, in_out);
10971 
10972     movl(tmp1, const_or_pre_comp_const_index);
10973     movdl(w_xtmp2, tmp1);
10974     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10975     // Keep result in XMM since GPR is 32 bit in length
10976   } else {
10977     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10978   }
10979 }
10980 
10981 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,
10982                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10983                                      Register tmp1, Register tmp2,
10984                                      Register n_tmp3) {
10985   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10986   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10987 
10988   psllq(w_xtmp1, 1);
10989   movdl(tmp1, w_xtmp1);
10990   psrlq(w_xtmp1, 32);
10991   movdl(in_out, w_xtmp1);
10992 
10993   xorl(tmp2, tmp2);
10994   crc32(tmp2, tmp1, 4);
10995   xorl(in_out, tmp2);
10996 
10997   psllq(w_xtmp2, 1);
10998   movdl(tmp1, w_xtmp2);
10999   psrlq(w_xtmp2, 32);
11000   movdl(in1, w_xtmp2);
11001 
11002   xorl(tmp2, tmp2);
11003   crc32(tmp2, tmp1, 4);
11004   xorl(in1, tmp2);
11005   xorl(in_out, in1);
11006   xorl(in_out, in2);
11007 }
11008 
11009 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,
11010                                        Register in_out1, Register in_out2, Register in_out3,
11011                                        Register tmp1, Register tmp2, Register tmp3,
11012                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11013                                        Register tmp4, Register tmp5,
11014                                        Register n_tmp6) {
11015   Label L_processPartitions;
11016   Label L_processPartition;
11017   Label L_exit;
11018 
11019   bind(L_processPartitions);
11020   cmpl(in_out1, 3 * size);
11021   jcc(Assembler::less, L_exit);
11022     xorl(tmp1, tmp1);
11023     xorl(tmp2, tmp2);
11024     movl(tmp3, in_out2);
11025     addl(tmp3, size);
11026 
11027     bind(L_processPartition);
11028       crc32(in_out3, Address(in_out2, 0), 4);
11029       crc32(tmp1, Address(in_out2, size), 4);
11030       crc32(tmp2, Address(in_out2, size*2), 4);
11031       crc32(in_out3, Address(in_out2, 0+4), 4);
11032       crc32(tmp1, Address(in_out2, size+4), 4);
11033       crc32(tmp2, Address(in_out2, size*2+4), 4);
11034       addl(in_out2, 8);
11035       cmpl(in_out2, tmp3);
11036       jcc(Assembler::less, L_processPartition);
11037 
11038         push(tmp3);
11039         push(in_out1);
11040         push(in_out2);
11041         tmp4 = tmp3;
11042         tmp5 = in_out1;
11043         n_tmp6 = in_out2;
11044 
11045       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
11046             w_xtmp1, w_xtmp2, w_xtmp3,
11047             tmp4, tmp5,
11048             n_tmp6);
11049 
11050         pop(in_out2);
11051         pop(in_out1);
11052         pop(tmp3);
11053 
11054     addl(in_out2, 2 * size);
11055     subl(in_out1, 3 * size);
11056     jmp(L_processPartitions);
11057 
11058   bind(L_exit);
11059 }
11060 #endif //LP64
11061 
11062 #ifdef _LP64
11063 // Algorithm 2: Pipelined usage of the CRC32 instruction.
11064 // Input: A buffer I of L bytes.
11065 // Output: the CRC32C value of the buffer.
11066 // Notations:
11067 // Write L = 24N + r, with N = floor (L/24).
11068 // r = L mod 24 (0 <= r < 24).
11069 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
11070 // N quadwords, and R consists of r bytes.
11071 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
11072 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
11073 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
11074 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
11075 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11076                                           Register tmp1, Register tmp2, Register tmp3,
11077                                           Register tmp4, Register tmp5, Register tmp6,
11078                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11079                                           bool is_pclmulqdq_supported) {
11080   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11081   Label L_wordByWord;
11082   Label L_byteByByteProlog;
11083   Label L_byteByByte;
11084   Label L_exit;
11085 
11086   if (is_pclmulqdq_supported ) {
11087     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11088     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
11089 
11090     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11091     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11092 
11093     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11094     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11095     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
11096   } else {
11097     const_or_pre_comp_const_index[0] = 1;
11098     const_or_pre_comp_const_index[1] = 0;
11099 
11100     const_or_pre_comp_const_index[2] = 3;
11101     const_or_pre_comp_const_index[3] = 2;
11102 
11103     const_or_pre_comp_const_index[4] = 5;
11104     const_or_pre_comp_const_index[5] = 4;
11105    }
11106   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11107                     in2, in1, in_out,
11108                     tmp1, tmp2, tmp3,
11109                     w_xtmp1, w_xtmp2, w_xtmp3,
11110                     tmp4, tmp5,
11111                     tmp6);
11112   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11113                     in2, in1, in_out,
11114                     tmp1, tmp2, tmp3,
11115                     w_xtmp1, w_xtmp2, w_xtmp3,
11116                     tmp4, tmp5,
11117                     tmp6);
11118   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11119                     in2, in1, in_out,
11120                     tmp1, tmp2, tmp3,
11121                     w_xtmp1, w_xtmp2, w_xtmp3,
11122                     tmp4, tmp5,
11123                     tmp6);
11124   movl(tmp1, in2);
11125   andl(tmp1, 0x00000007);
11126   negl(tmp1);
11127   addl(tmp1, in2);
11128   addq(tmp1, in1);
11129 
11130   BIND(L_wordByWord);
11131   cmpq(in1, tmp1);
11132   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11133     crc32(in_out, Address(in1, 0), 4);
11134     addq(in1, 4);
11135     jmp(L_wordByWord);
11136 
11137   BIND(L_byteByByteProlog);
11138   andl(in2, 0x00000007);
11139   movl(tmp2, 1);
11140 
11141   BIND(L_byteByByte);
11142   cmpl(tmp2, in2);
11143   jccb(Assembler::greater, L_exit);
11144     crc32(in_out, Address(in1, 0), 1);
11145     incq(in1);
11146     incl(tmp2);
11147     jmp(L_byteByByte);
11148 
11149   BIND(L_exit);
11150 }
11151 #else
11152 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
11153                                           Register tmp1, Register  tmp2, Register tmp3,
11154                                           Register tmp4, Register  tmp5, Register tmp6,
11155                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
11156                                           bool is_pclmulqdq_supported) {
11157   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
11158   Label L_wordByWord;
11159   Label L_byteByByteProlog;
11160   Label L_byteByByte;
11161   Label L_exit;
11162 
11163   if (is_pclmulqdq_supported) {
11164     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
11165     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
11166 
11167     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
11168     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
11169 
11170     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
11171     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
11172   } else {
11173     const_or_pre_comp_const_index[0] = 1;
11174     const_or_pre_comp_const_index[1] = 0;
11175 
11176     const_or_pre_comp_const_index[2] = 3;
11177     const_or_pre_comp_const_index[3] = 2;
11178 
11179     const_or_pre_comp_const_index[4] = 5;
11180     const_or_pre_comp_const_index[5] = 4;
11181   }
11182   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
11183                     in2, in1, in_out,
11184                     tmp1, tmp2, tmp3,
11185                     w_xtmp1, w_xtmp2, w_xtmp3,
11186                     tmp4, tmp5,
11187                     tmp6);
11188   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
11189                     in2, in1, in_out,
11190                     tmp1, tmp2, tmp3,
11191                     w_xtmp1, w_xtmp2, w_xtmp3,
11192                     tmp4, tmp5,
11193                     tmp6);
11194   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
11195                     in2, in1, in_out,
11196                     tmp1, tmp2, tmp3,
11197                     w_xtmp1, w_xtmp2, w_xtmp3,
11198                     tmp4, tmp5,
11199                     tmp6);
11200   movl(tmp1, in2);
11201   andl(tmp1, 0x00000007);
11202   negl(tmp1);
11203   addl(tmp1, in2);
11204   addl(tmp1, in1);
11205 
11206   BIND(L_wordByWord);
11207   cmpl(in1, tmp1);
11208   jcc(Assembler::greaterEqual, L_byteByByteProlog);
11209     crc32(in_out, Address(in1,0), 4);
11210     addl(in1, 4);
11211     jmp(L_wordByWord);
11212 
11213   BIND(L_byteByByteProlog);
11214   andl(in2, 0x00000007);
11215   movl(tmp2, 1);
11216 
11217   BIND(L_byteByByte);
11218   cmpl(tmp2, in2);
11219   jccb(Assembler::greater, L_exit);
11220     movb(tmp1, Address(in1, 0));
11221     crc32(in_out, tmp1, 1);
11222     incl(in1);
11223     incl(tmp2);
11224     jmp(L_byteByByte);
11225 
11226   BIND(L_exit);
11227 }
11228 #endif // LP64
11229 #undef BIND
11230 #undef BLOCK_COMMENT
11231 
11232 // Compress char[] array to byte[].
11233 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
11234 //   @HotSpotIntrinsicCandidate
11235 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
11236 //     for (int i = 0; i < len; i++) {
11237 //       int c = src[srcOff++];
11238 //       if (c >>> 8 != 0) {
11239 //         return 0;
11240 //       }
11241 //       dst[dstOff++] = (byte)c;
11242 //     }
11243 //     return len;
11244 //   }
11245 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
11246   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
11247   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
11248   Register tmp5, Register result) {
11249   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
11250 
11251   // rsi: src
11252   // rdi: dst
11253   // rdx: len
11254   // rcx: tmp5
11255   // rax: result
11256 
11257   // rsi holds start addr of source char[] to be compressed
11258   // rdi holds start addr of destination byte[]
11259   // rdx holds length
11260 
11261   assert(len != result, "");
11262 
11263   // save length for return
11264   push(len);
11265 
11266   if ((UseAVX > 2) && // AVX512
11267     VM_Version::supports_avx512vlbw() &&
11268     VM_Version::supports_bmi2()) {
11269 
11270     set_vector_masking();  // opening of the stub context for programming mask registers
11271 
11272     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
11273 
11274     // alignement
11275     Label post_alignement;
11276 
11277     // if length of the string is less than 16, handle it in an old fashioned
11278     // way
11279     testl(len, -32);
11280     jcc(Assembler::zero, below_threshold);
11281 
11282     // First check whether a character is compressable ( <= 0xFF).
11283     // Create mask to test for Unicode chars inside zmm vector
11284     movl(result, 0x00FF);
11285     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
11286 
11287     // Save k1
11288     kmovql(k3, k1);
11289 
11290     testl(len, -64);
11291     jcc(Assembler::zero, post_alignement);
11292 
11293     movl(tmp5, dst);
11294     andl(tmp5, (32 - 1));
11295     negl(tmp5);
11296     andl(tmp5, (32 - 1));
11297 
11298     // bail out when there is nothing to be done
11299     testl(tmp5, 0xFFFFFFFF);
11300     jcc(Assembler::zero, post_alignement);
11301 
11302     // ~(~0 << len), where len is the # of remaining elements to process
11303     movl(result, 0xFFFFFFFF);
11304     shlxl(result, result, tmp5);
11305     notl(result);
11306     kmovdl(k1, result);
11307 
11308     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11309     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11310     ktestd(k2, k1);
11311     jcc(Assembler::carryClear, restore_k1_return_zero);
11312 
11313     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11314 
11315     addptr(src, tmp5);
11316     addptr(src, tmp5);
11317     addptr(dst, tmp5);
11318     subl(len, tmp5);
11319 
11320     bind(post_alignement);
11321     // end of alignement
11322 
11323     movl(tmp5, len);
11324     andl(tmp5, (32 - 1));    // tail count (in chars)
11325     andl(len, ~(32 - 1));    // vector count (in chars)
11326     jcc(Assembler::zero, copy_loop_tail);
11327 
11328     lea(src, Address(src, len, Address::times_2));
11329     lea(dst, Address(dst, len, Address::times_1));
11330     negptr(len);
11331 
11332     bind(copy_32_loop);
11333     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11334     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11335     kortestdl(k2, k2);
11336     jcc(Assembler::carryClear, restore_k1_return_zero);
11337 
11338     // All elements in current processed chunk are valid candidates for
11339     // compression. Write a truncated byte elements to the memory.
11340     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11341     addptr(len, 32);
11342     jcc(Assembler::notZero, copy_32_loop);
11343 
11344     bind(copy_loop_tail);
11345     // bail out when there is nothing to be done
11346     testl(tmp5, 0xFFFFFFFF);
11347     // Restore k1
11348     kmovql(k1, k3);
11349     jcc(Assembler::zero, return_length);
11350 
11351     movl(len, tmp5);
11352 
11353     // ~(~0 << len), where len is the # of remaining elements to process
11354     movl(result, 0xFFFFFFFF);
11355     shlxl(result, result, len);
11356     notl(result);
11357 
11358     kmovdl(k1, result);
11359 
11360     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11361     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11362     ktestd(k2, k1);
11363     jcc(Assembler::carryClear, restore_k1_return_zero);
11364 
11365     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11366     // Restore k1
11367     kmovql(k1, k3);
11368     jmp(return_length);
11369 
11370     bind(restore_k1_return_zero);
11371     // Restore k1
11372     kmovql(k1, k3);
11373     jmp(return_zero);
11374 
11375     clear_vector_masking();   // closing of the stub context for programming mask registers
11376   }
11377   if (UseSSE42Intrinsics) {
11378     Label copy_32_loop, copy_16, copy_tail;
11379 
11380     bind(below_threshold);
11381 
11382     movl(result, len);
11383 
11384     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11385 
11386     // vectored compression
11387     andl(len, 0xfffffff0);    // vector count (in chars)
11388     andl(result, 0x0000000f);    // tail count (in chars)
11389     testl(len, len);
11390     jccb(Assembler::zero, copy_16);
11391 
11392     // compress 16 chars per iter
11393     movdl(tmp1Reg, tmp5);
11394     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11395     pxor(tmp4Reg, tmp4Reg);
11396 
11397     lea(src, Address(src, len, Address::times_2));
11398     lea(dst, Address(dst, len, Address::times_1));
11399     negptr(len);
11400 
11401     bind(copy_32_loop);
11402     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11403     por(tmp4Reg, tmp2Reg);
11404     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11405     por(tmp4Reg, tmp3Reg);
11406     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11407     jcc(Assembler::notZero, return_zero);
11408     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11409     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11410     addptr(len, 16);
11411     jcc(Assembler::notZero, copy_32_loop);
11412 
11413     // compress next vector of 8 chars (if any)
11414     bind(copy_16);
11415     movl(len, result);
11416     andl(len, 0xfffffff8);    // vector count (in chars)
11417     andl(result, 0x00000007);    // tail count (in chars)
11418     testl(len, len);
11419     jccb(Assembler::zero, copy_tail);
11420 
11421     movdl(tmp1Reg, tmp5);
11422     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11423     pxor(tmp3Reg, tmp3Reg);
11424 
11425     movdqu(tmp2Reg, Address(src, 0));
11426     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11427     jccb(Assembler::notZero, return_zero);
11428     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11429     movq(Address(dst, 0), tmp2Reg);
11430     addptr(src, 16);
11431     addptr(dst, 8);
11432 
11433     bind(copy_tail);
11434     movl(len, result);
11435   }
11436   // compress 1 char per iter
11437   testl(len, len);
11438   jccb(Assembler::zero, return_length);
11439   lea(src, Address(src, len, Address::times_2));
11440   lea(dst, Address(dst, len, Address::times_1));
11441   negptr(len);
11442 
11443   bind(copy_chars_loop);
11444   load_unsigned_short(result, Address(src, len, Address::times_2));
11445   testl(result, 0xff00);      // check if Unicode char
11446   jccb(Assembler::notZero, return_zero);
11447   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11448   increment(len);
11449   jcc(Assembler::notZero, copy_chars_loop);
11450 
11451   // if compression succeeded, return length
11452   bind(return_length);
11453   pop(result);
11454   jmpb(done);
11455 
11456   // if compression failed, return 0
11457   bind(return_zero);
11458   xorl(result, result);
11459   addptr(rsp, wordSize);
11460 
11461   bind(done);
11462 }
11463 
11464 // Inflate byte[] array to char[].
11465 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11466 //   @HotSpotIntrinsicCandidate
11467 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11468 //     for (int i = 0; i < len; i++) {
11469 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11470 //     }
11471 //   }
11472 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11473   XMMRegister tmp1, Register tmp2) {
11474   Label copy_chars_loop, done, below_threshold;
11475   // rsi: src
11476   // rdi: dst
11477   // rdx: len
11478   // rcx: tmp2
11479 
11480   // rsi holds start addr of source byte[] to be inflated
11481   // rdi holds start addr of destination char[]
11482   // rdx holds length
11483   assert_different_registers(src, dst, len, tmp2);
11484 
11485   if ((UseAVX > 2) && // AVX512
11486     VM_Version::supports_avx512vlbw() &&
11487     VM_Version::supports_bmi2()) {
11488 
11489     set_vector_masking();  // opening of the stub context for programming mask registers
11490 
11491     Label copy_32_loop, copy_tail;
11492     Register tmp3_aliased = len;
11493 
11494     // if length of the string is less than 16, handle it in an old fashioned
11495     // way
11496     testl(len, -16);
11497     jcc(Assembler::zero, below_threshold);
11498 
11499     // In order to use only one arithmetic operation for the main loop we use
11500     // this pre-calculation
11501     movl(tmp2, len);
11502     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11503     andl(len, -32);     // vector count
11504     jccb(Assembler::zero, copy_tail);
11505 
11506     lea(src, Address(src, len, Address::times_1));
11507     lea(dst, Address(dst, len, Address::times_2));
11508     negptr(len);
11509 
11510 
11511     // inflate 32 chars per iter
11512     bind(copy_32_loop);
11513     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11514     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11515     addptr(len, 32);
11516     jcc(Assembler::notZero, copy_32_loop);
11517 
11518     bind(copy_tail);
11519     // bail out when there is nothing to be done
11520     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11521     jcc(Assembler::zero, done);
11522 
11523     // Save k1
11524     kmovql(k2, k1);
11525 
11526     // ~(~0 << length), where length is the # of remaining elements to process
11527     movl(tmp3_aliased, -1);
11528     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11529     notl(tmp3_aliased);
11530     kmovdl(k1, tmp3_aliased);
11531     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11532     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11533 
11534     // Restore k1
11535     kmovql(k1, k2);
11536     jmp(done);
11537 
11538     clear_vector_masking();   // closing of the stub context for programming mask registers
11539   }
11540   if (UseSSE42Intrinsics) {
11541     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11542 
11543     movl(tmp2, len);
11544 
11545     if (UseAVX > 1) {
11546       andl(tmp2, (16 - 1));
11547       andl(len, -16);
11548       jccb(Assembler::zero, copy_new_tail);
11549     } else {
11550       andl(tmp2, 0x00000007);   // tail count (in chars)
11551       andl(len, 0xfffffff8);    // vector count (in chars)
11552       jccb(Assembler::zero, copy_tail);
11553     }
11554 
11555     // vectored inflation
11556     lea(src, Address(src, len, Address::times_1));
11557     lea(dst, Address(dst, len, Address::times_2));
11558     negptr(len);
11559 
11560     if (UseAVX > 1) {
11561       bind(copy_16_loop);
11562       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11563       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11564       addptr(len, 16);
11565       jcc(Assembler::notZero, copy_16_loop);
11566 
11567       bind(below_threshold);
11568       bind(copy_new_tail);
11569       if ((UseAVX > 2) &&
11570         VM_Version::supports_avx512vlbw() &&
11571         VM_Version::supports_bmi2()) {
11572         movl(tmp2, len);
11573       } else {
11574         movl(len, tmp2);
11575       }
11576       andl(tmp2, 0x00000007);
11577       andl(len, 0xFFFFFFF8);
11578       jccb(Assembler::zero, copy_tail);
11579 
11580       pmovzxbw(tmp1, Address(src, 0));
11581       movdqu(Address(dst, 0), tmp1);
11582       addptr(src, 8);
11583       addptr(dst, 2 * 8);
11584 
11585       jmp(copy_tail, true);
11586     }
11587 
11588     // inflate 8 chars per iter
11589     bind(copy_8_loop);
11590     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11591     movdqu(Address(dst, len, Address::times_2), tmp1);
11592     addptr(len, 8);
11593     jcc(Assembler::notZero, copy_8_loop);
11594 
11595     bind(copy_tail);
11596     movl(len, tmp2);
11597 
11598     cmpl(len, 4);
11599     jccb(Assembler::less, copy_bytes);
11600 
11601     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11602     pmovzxbw(tmp1, tmp1);
11603     movq(Address(dst, 0), tmp1);
11604     subptr(len, 4);
11605     addptr(src, 4);
11606     addptr(dst, 8);
11607 
11608     bind(copy_bytes);
11609   }
11610   testl(len, len);
11611   jccb(Assembler::zero, done);
11612   lea(src, Address(src, len, Address::times_1));
11613   lea(dst, Address(dst, len, Address::times_2));
11614   negptr(len);
11615 
11616   // inflate 1 char per iter
11617   bind(copy_chars_loop);
11618   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11619   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11620   increment(len);
11621   jcc(Assembler::notZero, copy_chars_loop);
11622 
11623   bind(done);
11624 }
11625 
11626 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11627   switch (cond) {
11628     // Note some conditions are synonyms for others
11629     case Assembler::zero:         return Assembler::notZero;
11630     case Assembler::notZero:      return Assembler::zero;
11631     case Assembler::less:         return Assembler::greaterEqual;
11632     case Assembler::lessEqual:    return Assembler::greater;
11633     case Assembler::greater:      return Assembler::lessEqual;
11634     case Assembler::greaterEqual: return Assembler::less;
11635     case Assembler::below:        return Assembler::aboveEqual;
11636     case Assembler::belowEqual:   return Assembler::above;
11637     case Assembler::above:        return Assembler::belowEqual;
11638     case Assembler::aboveEqual:   return Assembler::below;
11639     case Assembler::overflow:     return Assembler::noOverflow;
11640     case Assembler::noOverflow:   return Assembler::overflow;
11641     case Assembler::negative:     return Assembler::positive;
11642     case Assembler::positive:     return Assembler::negative;
11643     case Assembler::parity:       return Assembler::noParity;
11644     case Assembler::noParity:     return Assembler::parity;
11645   }
11646   ShouldNotReachHere(); return Assembler::overflow;
11647 }
11648 
11649 SkipIfEqual::SkipIfEqual(
11650     MacroAssembler* masm, const bool* flag_addr, bool value) {
11651   _masm = masm;
11652   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11653   _masm->jcc(Assembler::equal, _label);
11654 }
11655 
11656 SkipIfEqual::~SkipIfEqual() {
11657   _masm->bind(_label);
11658 }
11659 
11660 // 32-bit Windows has its own fast-path implementation
11661 // of get_thread
11662 #if !defined(WIN32) || defined(_LP64)
11663 
11664 // This is simply a call to Thread::current()
11665 void MacroAssembler::get_thread(Register thread) {
11666   if (thread != rax) {
11667     push(rax);
11668   }
11669   LP64_ONLY(push(rdi);)
11670   LP64_ONLY(push(rsi);)
11671   push(rdx);
11672   push(rcx);
11673 #ifdef _LP64
11674   push(r8);
11675   push(r9);
11676   push(r10);
11677   push(r11);
11678 #endif
11679 
11680   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11681 
11682 #ifdef _LP64
11683   pop(r11);
11684   pop(r10);
11685   pop(r9);
11686   pop(r8);
11687 #endif
11688   pop(rcx);
11689   pop(rdx);
11690   LP64_ONLY(pop(rsi);)
11691   LP64_ONLY(pop(rdi);)
11692   if (thread != rax) {
11693     mov(thread, rax);
11694     pop(rax);
11695   }
11696 }
11697 
11698 #endif
11699 
11700 void MacroAssembler::save_vector_registers() {
11701   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11702   if (UseAVX > 2) {
11703     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11704   }
11705 
11706   if (UseSSE == 1)  {
11707     subptr(rsp, sizeof(jdouble)*8);
11708     for (int n = 0; n < 8; n++) {
11709       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11710     }
11711   } else if (UseSSE >= 2)  {
11712     if (UseAVX > 2) {
11713       push(rbx);
11714       movl(rbx, 0xffff);
11715       kmovwl(k1, rbx);
11716       pop(rbx);
11717     }
11718 #ifdef COMPILER2
11719     if (MaxVectorSize > 16) {
11720       if(UseAVX > 2) {
11721         // Save upper half of ZMM registers
11722         subptr(rsp, 32*num_xmm_regs);
11723         for (int n = 0; n < num_xmm_regs; n++) {
11724           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11725         }
11726       }
11727       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11728       // Save upper half of YMM registers
11729       subptr(rsp, 16*num_xmm_regs);
11730       for (int n = 0; n < num_xmm_regs; n++) {
11731         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11732       }
11733     }
11734 #endif
11735     // Save whole 128bit (16 bytes) XMM registers
11736     subptr(rsp, 16*num_xmm_regs);
11737 #ifdef _LP64
11738     if (VM_Version::supports_evex()) {
11739       for (int n = 0; n < num_xmm_regs; n++) {
11740         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11741       }
11742     } else {
11743       for (int n = 0; n < num_xmm_regs; n++) {
11744         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11745       }
11746     }
11747 #else
11748     for (int n = 0; n < num_xmm_regs; n++) {
11749       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11750     }
11751 #endif
11752   }
11753 }
11754 
11755 void MacroAssembler::restore_vector_registers() {
11756   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11757   if (UseAVX > 2) {
11758     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11759   }
11760   if (UseSSE == 1)  {
11761     for (int n = 0; n < 8; n++) {
11762       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11763     }
11764     addptr(rsp, sizeof(jdouble)*8);
11765   } else if (UseSSE >= 2)  {
11766     // Restore whole 128bit (16 bytes) XMM registers
11767 #ifdef _LP64
11768   if (VM_Version::supports_evex()) {
11769     for (int n = 0; n < num_xmm_regs; n++) {
11770       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11771     }
11772   } else {
11773     for (int n = 0; n < num_xmm_regs; n++) {
11774       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11775     }
11776   }
11777 #else
11778   for (int n = 0; n < num_xmm_regs; n++) {
11779     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11780   }
11781 #endif
11782     addptr(rsp, 16*num_xmm_regs);
11783 
11784 #ifdef COMPILER2
11785     if (MaxVectorSize > 16) {
11786       // Restore upper half of YMM registers.
11787       for (int n = 0; n < num_xmm_regs; n++) {
11788         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11789       }
11790       addptr(rsp, 16*num_xmm_regs);
11791       if(UseAVX > 2) {
11792         for (int n = 0; n < num_xmm_regs; n++) {
11793           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11794         }
11795         addptr(rsp, 32*num_xmm_regs);
11796       }
11797     }
11798 #endif
11799   }
11800 }