1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/access.hpp"
  37 #include "oops/klass.inline.hpp"
  38 #include "prims/methodHandles.hpp"
  39 #include "runtime/biasedLocking.hpp"
  40 #include "runtime/flags/flagSetting.hpp"
  41 #include "runtime/interfaceSupport.inline.hpp"
  42 #include "runtime/objectMonitor.hpp"
  43 #include "runtime/os.hpp"
  44 #include "runtime/safepoint.hpp"
  45 #include "runtime/safepointMechanism.hpp"
  46 #include "runtime/sharedRuntime.hpp"
  47 #include "runtime/stubRoutines.hpp"
  48 #include "runtime/thread.hpp"
  49 #include "utilities/macros.hpp"
  50 #include "crc32c.h"
  51 #ifdef COMPILER2
  52 #include "opto/intrinsicnode.hpp"
  53 #endif
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #define STOP(error) stop(error)
  58 #else
  59 #define BLOCK_COMMENT(str) block_comment(str)
  60 #define STOP(error) block_comment(error); stop(error)
  61 #endif
  62 
  63 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  64 
  65 #ifdef ASSERT
  66 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  67 #endif
  68 
  69 static Assembler::Condition reverse[] = {
  70     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  71     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  72     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  73     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  74     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  75     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  76     Assembler::above          /* belowEqual    = 0x6 */ ,
  77     Assembler::belowEqual     /* above         = 0x7 */ ,
  78     Assembler::positive       /* negative      = 0x8 */ ,
  79     Assembler::negative       /* positive      = 0x9 */ ,
  80     Assembler::noParity       /* parity        = 0xa */ ,
  81     Assembler::parity         /* noParity      = 0xb */ ,
  82     Assembler::greaterEqual   /* less          = 0xc */ ,
  83     Assembler::less           /* greaterEqual  = 0xd */ ,
  84     Assembler::greater        /* lessEqual     = 0xe */ ,
  85     Assembler::lessEqual      /* greater       = 0xf, */
  86 
  87 };
  88 
  89 
  90 // Implementation of MacroAssembler
  91 
  92 // First all the versions that have distinct versions depending on 32/64 bit
  93 // Unless the difference is trivial (1 line or so).
  94 
  95 #ifndef _LP64
  96 
  97 // 32bit versions
  98 
  99 Address MacroAssembler::as_Address(AddressLiteral adr) {
 100   return Address(adr.target(), adr.rspec());
 101 }
 102 
 103 Address MacroAssembler::as_Address(ArrayAddress adr) {
 104   return Address::make_array(adr);
 105 }
 106 
 107 void MacroAssembler::call_VM_leaf_base(address entry_point,
 108                                        int number_of_arguments) {
 109   call(RuntimeAddress(entry_point));
 110   increment(rsp, number_of_arguments * wordSize);
 111 }
 112 
 113 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 114   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 115 }
 116 
 117 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 118   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 122   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 126   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 127 }
 128 
 129 void MacroAssembler::extend_sign(Register hi, Register lo) {
 130   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 131   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 132     cdql();
 133   } else {
 134     movl(hi, lo);
 135     sarl(hi, 31);
 136   }
 137 }
 138 
 139 void MacroAssembler::jC2(Register tmp, Label& L) {
 140   // set parity bit if FPU flag C2 is set (via rax)
 141   save_rax(tmp);
 142   fwait(); fnstsw_ax();
 143   sahf();
 144   restore_rax(tmp);
 145   // branch
 146   jcc(Assembler::parity, L);
 147 }
 148 
 149 void MacroAssembler::jnC2(Register tmp, Label& L) {
 150   // set parity bit if FPU flag C2 is set (via rax)
 151   save_rax(tmp);
 152   fwait(); fnstsw_ax();
 153   sahf();
 154   restore_rax(tmp);
 155   // branch
 156   jcc(Assembler::noParity, L);
 157 }
 158 
 159 // 32bit can do a case table jump in one instruction but we no longer allow the base
 160 // to be installed in the Address class
 161 void MacroAssembler::jump(ArrayAddress entry) {
 162   jmp(as_Address(entry));
 163 }
 164 
 165 // Note: y_lo will be destroyed
 166 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 167   // Long compare for Java (semantics as described in JVM spec.)
 168   Label high, low, done;
 169 
 170   cmpl(x_hi, y_hi);
 171   jcc(Assembler::less, low);
 172   jcc(Assembler::greater, high);
 173   // x_hi is the return register
 174   xorl(x_hi, x_hi);
 175   cmpl(x_lo, y_lo);
 176   jcc(Assembler::below, low);
 177   jcc(Assembler::equal, done);
 178 
 179   bind(high);
 180   xorl(x_hi, x_hi);
 181   increment(x_hi);
 182   jmp(done);
 183 
 184   bind(low);
 185   xorl(x_hi, x_hi);
 186   decrementl(x_hi);
 187 
 188   bind(done);
 189 }
 190 
 191 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 192     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 193 }
 194 
 195 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 196   // leal(dst, as_Address(adr));
 197   // see note in movl as to why we must use a move
 198   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 199 }
 200 
 201 void MacroAssembler::leave() {
 202   mov(rsp, rbp);
 203   pop(rbp);
 204 }
 205 
 206 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 207   // Multiplication of two Java long values stored on the stack
 208   // as illustrated below. Result is in rdx:rax.
 209   //
 210   // rsp ---> [  ??  ] \               \
 211   //            ....    | y_rsp_offset  |
 212   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 213   //          [ y_hi ]                  | (in bytes)
 214   //            ....                    |
 215   //          [ x_lo ]                 /
 216   //          [ x_hi ]
 217   //            ....
 218   //
 219   // Basic idea: lo(result) = lo(x_lo * y_lo)
 220   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 221   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 222   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 223   Label quick;
 224   // load x_hi, y_hi and check if quick
 225   // multiplication is possible
 226   movl(rbx, x_hi);
 227   movl(rcx, y_hi);
 228   movl(rax, rbx);
 229   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 230   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 231   // do full multiplication
 232   // 1st step
 233   mull(y_lo);                                    // x_hi * y_lo
 234   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 235   // 2nd step
 236   movl(rax, x_lo);
 237   mull(rcx);                                     // x_lo * y_hi
 238   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 239   // 3rd step
 240   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 241   movl(rax, x_lo);
 242   mull(y_lo);                                    // x_lo * y_lo
 243   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 244 }
 245 
 246 void MacroAssembler::lneg(Register hi, Register lo) {
 247   negl(lo);
 248   adcl(hi, 0);
 249   negl(hi);
 250 }
 251 
 252 void MacroAssembler::lshl(Register hi, Register lo) {
 253   // Java shift left long support (semantics as described in JVM spec., p.305)
 254   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 255   // shift value is in rcx !
 256   assert(hi != rcx, "must not use rcx");
 257   assert(lo != rcx, "must not use rcx");
 258   const Register s = rcx;                        // shift count
 259   const int      n = BitsPerWord;
 260   Label L;
 261   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 262   cmpl(s, n);                                    // if (s < n)
 263   jcc(Assembler::less, L);                       // else (s >= n)
 264   movl(hi, lo);                                  // x := x << n
 265   xorl(lo, lo);
 266   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 267   bind(L);                                       // s (mod n) < n
 268   shldl(hi, lo);                                 // x := x << s
 269   shll(lo);
 270 }
 271 
 272 
 273 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 274   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 275   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 276   assert(hi != rcx, "must not use rcx");
 277   assert(lo != rcx, "must not use rcx");
 278   const Register s = rcx;                        // shift count
 279   const int      n = BitsPerWord;
 280   Label L;
 281   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 282   cmpl(s, n);                                    // if (s < n)
 283   jcc(Assembler::less, L);                       // else (s >= n)
 284   movl(lo, hi);                                  // x := x >> n
 285   if (sign_extension) sarl(hi, 31);
 286   else                xorl(hi, hi);
 287   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 288   bind(L);                                       // s (mod n) < n
 289   shrdl(lo, hi);                                 // x := x >> s
 290   if (sign_extension) sarl(hi);
 291   else                shrl(hi);
 292 }
 293 
 294 void MacroAssembler::movoop(Register dst, jobject obj) {
 295   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 296 }
 297 
 298 void MacroAssembler::movoop(Address dst, jobject obj) {
 299   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 300 }
 301 
 302 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 303   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 304 }
 305 
 306 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 307   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 308 }
 309 
 310 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 311   // scratch register is not used,
 312   // it is defined to match parameters of 64-bit version of this method.
 313   if (src.is_lval()) {
 314     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 315   } else {
 316     movl(dst, as_Address(src));
 317   }
 318 }
 319 
 320 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 321   movl(as_Address(dst), src);
 322 }
 323 
 324 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 325   movl(dst, as_Address(src));
 326 }
 327 
 328 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 329 void MacroAssembler::movptr(Address dst, intptr_t src) {
 330   movl(dst, src);
 331 }
 332 
 333 
 334 void MacroAssembler::pop_callee_saved_registers() {
 335   pop(rcx);
 336   pop(rdx);
 337   pop(rdi);
 338   pop(rsi);
 339 }
 340 
 341 void MacroAssembler::pop_fTOS() {
 342   fld_d(Address(rsp, 0));
 343   addl(rsp, 2 * wordSize);
 344 }
 345 
 346 void MacroAssembler::push_callee_saved_registers() {
 347   push(rsi);
 348   push(rdi);
 349   push(rdx);
 350   push(rcx);
 351 }
 352 
 353 void MacroAssembler::push_fTOS() {
 354   subl(rsp, 2 * wordSize);
 355   fstp_d(Address(rsp, 0));
 356 }
 357 
 358 
 359 void MacroAssembler::pushoop(jobject obj) {
 360   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 361 }
 362 
 363 void MacroAssembler::pushklass(Metadata* obj) {
 364   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 365 }
 366 
 367 void MacroAssembler::pushptr(AddressLiteral src) {
 368   if (src.is_lval()) {
 369     push_literal32((int32_t)src.target(), src.rspec());
 370   } else {
 371     pushl(as_Address(src));
 372   }
 373 }
 374 
 375 void MacroAssembler::set_word_if_not_zero(Register dst) {
 376   xorl(dst, dst);
 377   set_byte_if_not_zero(dst);
 378 }
 379 
 380 static void pass_arg0(MacroAssembler* masm, Register arg) {
 381   masm->push(arg);
 382 }
 383 
 384 static void pass_arg1(MacroAssembler* masm, Register arg) {
 385   masm->push(arg);
 386 }
 387 
 388 static void pass_arg2(MacroAssembler* masm, Register arg) {
 389   masm->push(arg);
 390 }
 391 
 392 static void pass_arg3(MacroAssembler* masm, Register arg) {
 393   masm->push(arg);
 394 }
 395 
 396 #ifndef PRODUCT
 397 extern "C" void findpc(intptr_t x);
 398 #endif
 399 
 400 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 401   // In order to get locks to work, we need to fake a in_VM state
 402   JavaThread* thread = JavaThread::current();
 403   JavaThreadState saved_state = thread->thread_state();
 404   thread->set_thread_state(_thread_in_vm);
 405   if (ShowMessageBoxOnError) {
 406     JavaThread* thread = JavaThread::current();
 407     JavaThreadState saved_state = thread->thread_state();
 408     thread->set_thread_state(_thread_in_vm);
 409     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 410       ttyLocker ttyl;
 411       BytecodeCounter::print();
 412     }
 413     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 414     // This is the value of eip which points to where verify_oop will return.
 415     if (os::message_box(msg, "Execution stopped, print registers?")) {
 416       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 417       BREAKPOINT;
 418     }
 419   } else {
 420     ttyLocker ttyl;
 421     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 422   }
 423   // Don't assert holding the ttyLock
 424     assert(false, "DEBUG MESSAGE: %s", msg);
 425   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 426 }
 427 
 428 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 429   ttyLocker ttyl;
 430   FlagSetting fs(Debugging, true);
 431   tty->print_cr("eip = 0x%08x", eip);
 432 #ifndef PRODUCT
 433   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 434     tty->cr();
 435     findpc(eip);
 436     tty->cr();
 437   }
 438 #endif
 439 #define PRINT_REG(rax) \
 440   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 441   PRINT_REG(rax);
 442   PRINT_REG(rbx);
 443   PRINT_REG(rcx);
 444   PRINT_REG(rdx);
 445   PRINT_REG(rdi);
 446   PRINT_REG(rsi);
 447   PRINT_REG(rbp);
 448   PRINT_REG(rsp);
 449 #undef PRINT_REG
 450   // Print some words near top of staack.
 451   int* dump_sp = (int*) rsp;
 452   for (int col1 = 0; col1 < 8; col1++) {
 453     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 454     os::print_location(tty, *dump_sp++);
 455   }
 456   for (int row = 0; row < 16; row++) {
 457     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 458     for (int col = 0; col < 8; col++) {
 459       tty->print(" 0x%08x", *dump_sp++);
 460     }
 461     tty->cr();
 462   }
 463   // Print some instructions around pc:
 464   Disassembler::decode((address)eip-64, (address)eip);
 465   tty->print_cr("--------");
 466   Disassembler::decode((address)eip, (address)eip+32);
 467 }
 468 
 469 void MacroAssembler::stop(const char* msg) {
 470   ExternalAddress message((address)msg);
 471   // push address of message
 472   pushptr(message.addr());
 473   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 474   pusha();                                            // push registers
 475   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 476   hlt();
 477 }
 478 
 479 void MacroAssembler::warn(const char* msg) {
 480   push_CPU_state();
 481 
 482   ExternalAddress message((address) msg);
 483   // push address of message
 484   pushptr(message.addr());
 485 
 486   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 487   addl(rsp, wordSize);       // discard argument
 488   pop_CPU_state();
 489 }
 490 
 491 void MacroAssembler::print_state() {
 492   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 493   pusha();                                            // push registers
 494 
 495   push_CPU_state();
 496   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 497   pop_CPU_state();
 498 
 499   popa();
 500   addl(rsp, wordSize);
 501 }
 502 
 503 #else // _LP64
 504 
 505 // 64 bit versions
 506 
 507 Address MacroAssembler::as_Address(AddressLiteral adr) {
 508   // amd64 always does this as a pc-rel
 509   // we can be absolute or disp based on the instruction type
 510   // jmp/call are displacements others are absolute
 511   assert(!adr.is_lval(), "must be rval");
 512   assert(reachable(adr), "must be");
 513   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 514 
 515 }
 516 
 517 Address MacroAssembler::as_Address(ArrayAddress adr) {
 518   AddressLiteral base = adr.base();
 519   lea(rscratch1, base);
 520   Address index = adr.index();
 521   assert(index._disp == 0, "must not have disp"); // maybe it can?
 522   Address array(rscratch1, index._index, index._scale, index._disp);
 523   return array;
 524 }
 525 
 526 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 527   Label L, E;
 528 
 529 #ifdef _WIN64
 530   // Windows always allocates space for it's register args
 531   assert(num_args <= 4, "only register arguments supported");
 532   subq(rsp,  frame::arg_reg_save_area_bytes);
 533 #endif
 534 
 535   // Align stack if necessary
 536   testl(rsp, 15);
 537   jcc(Assembler::zero, L);
 538 
 539   subq(rsp, 8);
 540   {
 541     call(RuntimeAddress(entry_point));
 542   }
 543   addq(rsp, 8);
 544   jmp(E);
 545 
 546   bind(L);
 547   {
 548     call(RuntimeAddress(entry_point));
 549   }
 550 
 551   bind(E);
 552 
 553 #ifdef _WIN64
 554   // restore stack pointer
 555   addq(rsp, frame::arg_reg_save_area_bytes);
 556 #endif
 557 
 558 }
 559 
 560 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 561   assert(!src2.is_lval(), "should use cmpptr");
 562 
 563   if (reachable(src2)) {
 564     cmpq(src1, as_Address(src2));
 565   } else {
 566     lea(rscratch1, src2);
 567     Assembler::cmpq(src1, Address(rscratch1, 0));
 568   }
 569 }
 570 
 571 int MacroAssembler::corrected_idivq(Register reg) {
 572   // Full implementation of Java ldiv and lrem; checks for special
 573   // case as described in JVM spec., p.243 & p.271.  The function
 574   // returns the (pc) offset of the idivl instruction - may be needed
 575   // for implicit exceptions.
 576   //
 577   //         normal case                           special case
 578   //
 579   // input : rax: dividend                         min_long
 580   //         reg: divisor   (may not be eax/edx)   -1
 581   //
 582   // output: rax: quotient  (= rax idiv reg)       min_long
 583   //         rdx: remainder (= rax irem reg)       0
 584   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 585   static const int64_t min_long = 0x8000000000000000;
 586   Label normal_case, special_case;
 587 
 588   // check for special case
 589   cmp64(rax, ExternalAddress((address) &min_long));
 590   jcc(Assembler::notEqual, normal_case);
 591   xorl(rdx, rdx); // prepare rdx for possible special case (where
 592                   // remainder = 0)
 593   cmpq(reg, -1);
 594   jcc(Assembler::equal, special_case);
 595 
 596   // handle normal case
 597   bind(normal_case);
 598   cdqq();
 599   int idivq_offset = offset();
 600   idivq(reg);
 601 
 602   // normal and special case exit
 603   bind(special_case);
 604 
 605   return idivq_offset;
 606 }
 607 
 608 void MacroAssembler::decrementq(Register reg, int value) {
 609   if (value == min_jint) { subq(reg, value); return; }
 610   if (value <  0) { incrementq(reg, -value); return; }
 611   if (value == 0) {                        ; return; }
 612   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 613   /* else */      { subq(reg, value)       ; return; }
 614 }
 615 
 616 void MacroAssembler::decrementq(Address dst, int value) {
 617   if (value == min_jint) { subq(dst, value); return; }
 618   if (value <  0) { incrementq(dst, -value); return; }
 619   if (value == 0) {                        ; return; }
 620   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 621   /* else */      { subq(dst, value)       ; return; }
 622 }
 623 
 624 void MacroAssembler::incrementq(AddressLiteral dst) {
 625   if (reachable(dst)) {
 626     incrementq(as_Address(dst));
 627   } else {
 628     lea(rscratch1, dst);
 629     incrementq(Address(rscratch1, 0));
 630   }
 631 }
 632 
 633 void MacroAssembler::incrementq(Register reg, int value) {
 634   if (value == min_jint) { addq(reg, value); return; }
 635   if (value <  0) { decrementq(reg, -value); return; }
 636   if (value == 0) {                        ; return; }
 637   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 638   /* else */      { addq(reg, value)       ; return; }
 639 }
 640 
 641 void MacroAssembler::incrementq(Address dst, int value) {
 642   if (value == min_jint) { addq(dst, value); return; }
 643   if (value <  0) { decrementq(dst, -value); return; }
 644   if (value == 0) {                        ; return; }
 645   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 646   /* else */      { addq(dst, value)       ; return; }
 647 }
 648 
 649 // 32bit can do a case table jump in one instruction but we no longer allow the base
 650 // to be installed in the Address class
 651 void MacroAssembler::jump(ArrayAddress entry) {
 652   lea(rscratch1, entry.base());
 653   Address dispatch = entry.index();
 654   assert(dispatch._base == noreg, "must be");
 655   dispatch._base = rscratch1;
 656   jmp(dispatch);
 657 }
 658 
 659 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 660   ShouldNotReachHere(); // 64bit doesn't use two regs
 661   cmpq(x_lo, y_lo);
 662 }
 663 
 664 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 665     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 666 }
 667 
 668 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 669   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 670   movptr(dst, rscratch1);
 671 }
 672 
 673 void MacroAssembler::leave() {
 674   // %%% is this really better? Why not on 32bit too?
 675   emit_int8((unsigned char)0xC9); // LEAVE
 676 }
 677 
 678 void MacroAssembler::lneg(Register hi, Register lo) {
 679   ShouldNotReachHere(); // 64bit doesn't use two regs
 680   negq(lo);
 681 }
 682 
 683 void MacroAssembler::movoop(Register dst, jobject obj) {
 684   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 685 }
 686 
 687 void MacroAssembler::movoop(Address dst, jobject obj) {
 688   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 689   movq(dst, rscratch1);
 690 }
 691 
 692 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 693   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 694 }
 695 
 696 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 697   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 698   movq(dst, rscratch1);
 699 }
 700 
 701 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 702   if (src.is_lval()) {
 703     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 704   } else {
 705     if (reachable(src)) {
 706       movq(dst, as_Address(src));
 707     } else {
 708       lea(scratch, src);
 709       movq(dst, Address(scratch, 0));
 710     }
 711   }
 712 }
 713 
 714 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 715   movq(as_Address(dst), src);
 716 }
 717 
 718 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 719   movq(dst, as_Address(src));
 720 }
 721 
 722 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 723 void MacroAssembler::movptr(Address dst, intptr_t src) {
 724   mov64(rscratch1, src);
 725   movq(dst, rscratch1);
 726 }
 727 
 728 // These are mostly for initializing NULL
 729 void MacroAssembler::movptr(Address dst, int32_t src) {
 730   movslq(dst, src);
 731 }
 732 
 733 void MacroAssembler::movptr(Register dst, int32_t src) {
 734   mov64(dst, (intptr_t)src);
 735 }
 736 
 737 void MacroAssembler::pushoop(jobject obj) {
 738   movoop(rscratch1, obj);
 739   push(rscratch1);
 740 }
 741 
 742 void MacroAssembler::pushklass(Metadata* obj) {
 743   mov_metadata(rscratch1, obj);
 744   push(rscratch1);
 745 }
 746 
 747 void MacroAssembler::pushptr(AddressLiteral src) {
 748   lea(rscratch1, src);
 749   if (src.is_lval()) {
 750     push(rscratch1);
 751   } else {
 752     pushq(Address(rscratch1, 0));
 753   }
 754 }
 755 
 756 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 757   // we must set sp to zero to clear frame
 758   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 759   // must clear fp, so that compiled frames are not confused; it is
 760   // possible that we need it only for debugging
 761   if (clear_fp) {
 762     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 763   }
 764 
 765   // Always clear the pc because it could have been set by make_walkable()
 766   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 767   vzeroupper();
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 773   vzeroupper();
 774   // determine last_java_sp register
 775   if (!last_java_sp->is_valid()) {
 776     last_java_sp = rsp;
 777   }
 778 
 779   // last_java_fp is optional
 780   if (last_java_fp->is_valid()) {
 781     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 782            last_java_fp);
 783   }
 784 
 785   // last_java_pc is optional
 786   if (last_java_pc != NULL) {
 787     Address java_pc(r15_thread,
 788                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 789     lea(rscratch1, InternalAddress(last_java_pc));
 790     movptr(java_pc, rscratch1);
 791   }
 792 
 793   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 794 }
 795 
 796 static void pass_arg0(MacroAssembler* masm, Register arg) {
 797   if (c_rarg0 != arg ) {
 798     masm->mov(c_rarg0, arg);
 799   }
 800 }
 801 
 802 static void pass_arg1(MacroAssembler* masm, Register arg) {
 803   if (c_rarg1 != arg ) {
 804     masm->mov(c_rarg1, arg);
 805   }
 806 }
 807 
 808 static void pass_arg2(MacroAssembler* masm, Register arg) {
 809   if (c_rarg2 != arg ) {
 810     masm->mov(c_rarg2, arg);
 811   }
 812 }
 813 
 814 static void pass_arg3(MacroAssembler* masm, Register arg) {
 815   if (c_rarg3 != arg ) {
 816     masm->mov(c_rarg3, arg);
 817   }
 818 }
 819 
 820 void MacroAssembler::stop(const char* msg) {
 821   address rip = pc();
 822   pusha(); // get regs on stack
 823   lea(c_rarg0, ExternalAddress((address) msg));
 824   lea(c_rarg1, InternalAddress(rip));
 825   movq(c_rarg2, rsp); // pass pointer to regs array
 826   andq(rsp, -16); // align stack as required by ABI
 827   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 828   hlt();
 829 }
 830 
 831 void MacroAssembler::warn(const char* msg) {
 832   push(rbp);
 833   movq(rbp, rsp);
 834   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 835   push_CPU_state();   // keeps alignment at 16 bytes
 836   lea(c_rarg0, ExternalAddress((address) msg));
 837   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 838   call(rax);
 839   pop_CPU_state();
 840   mov(rsp, rbp);
 841   pop(rbp);
 842 }
 843 
 844 void MacroAssembler::print_state() {
 845   address rip = pc();
 846   pusha();            // get regs on stack
 847   push(rbp);
 848   movq(rbp, rsp);
 849   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 850   push_CPU_state();   // keeps alignment at 16 bytes
 851 
 852   lea(c_rarg0, InternalAddress(rip));
 853   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 854   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 855 
 856   pop_CPU_state();
 857   mov(rsp, rbp);
 858   pop(rbp);
 859   popa();
 860 }
 861 
 862 #ifndef PRODUCT
 863 extern "C" void findpc(intptr_t x);
 864 #endif
 865 
 866 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 867   // In order to get locks to work, we need to fake a in_VM state
 868   if (ShowMessageBoxOnError) {
 869     JavaThread* thread = JavaThread::current();
 870     JavaThreadState saved_state = thread->thread_state();
 871     thread->set_thread_state(_thread_in_vm);
 872 #ifndef PRODUCT
 873     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 874       ttyLocker ttyl;
 875       BytecodeCounter::print();
 876     }
 877 #endif
 878     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 879     // XXX correct this offset for amd64
 880     // This is the value of eip which points to where verify_oop will return.
 881     if (os::message_box(msg, "Execution stopped, print registers?")) {
 882       print_state64(pc, regs);
 883       BREAKPOINT;
 884       assert(false, "start up GDB");
 885     }
 886     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 887   } else {
 888     ttyLocker ttyl;
 889     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 890                     msg);
 891     assert(false, "DEBUG MESSAGE: %s", msg);
 892   }
 893 }
 894 
 895 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 896   ttyLocker ttyl;
 897   FlagSetting fs(Debugging, true);
 898   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 899 #ifndef PRODUCT
 900   tty->cr();
 901   findpc(pc);
 902   tty->cr();
 903 #endif
 904 #define PRINT_REG(rax, value) \
 905   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 906   PRINT_REG(rax, regs[15]);
 907   PRINT_REG(rbx, regs[12]);
 908   PRINT_REG(rcx, regs[14]);
 909   PRINT_REG(rdx, regs[13]);
 910   PRINT_REG(rdi, regs[8]);
 911   PRINT_REG(rsi, regs[9]);
 912   PRINT_REG(rbp, regs[10]);
 913   PRINT_REG(rsp, regs[11]);
 914   PRINT_REG(r8 , regs[7]);
 915   PRINT_REG(r9 , regs[6]);
 916   PRINT_REG(r10, regs[5]);
 917   PRINT_REG(r11, regs[4]);
 918   PRINT_REG(r12, regs[3]);
 919   PRINT_REG(r13, regs[2]);
 920   PRINT_REG(r14, regs[1]);
 921   PRINT_REG(r15, regs[0]);
 922 #undef PRINT_REG
 923   // Print some words near top of staack.
 924   int64_t* rsp = (int64_t*) regs[11];
 925   int64_t* dump_sp = rsp;
 926   for (int col1 = 0; col1 < 8; col1++) {
 927     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 928     os::print_location(tty, *dump_sp++);
 929   }
 930   for (int row = 0; row < 25; row++) {
 931     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 932     for (int col = 0; col < 4; col++) {
 933       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 934     }
 935     tty->cr();
 936   }
 937   // Print some instructions around pc:
 938   Disassembler::decode((address)pc-64, (address)pc);
 939   tty->print_cr("--------");
 940   Disassembler::decode((address)pc, (address)pc+32);
 941 }
 942 
 943 #endif // _LP64
 944 
 945 // Now versions that are common to 32/64 bit
 946 
 947 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 948   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 949 }
 950 
 951 void MacroAssembler::addptr(Register dst, Register src) {
 952   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 953 }
 954 
 955 void MacroAssembler::addptr(Address dst, Register src) {
 956   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 957 }
 958 
 959 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 960   if (reachable(src)) {
 961     Assembler::addsd(dst, as_Address(src));
 962   } else {
 963     lea(rscratch1, src);
 964     Assembler::addsd(dst, Address(rscratch1, 0));
 965   }
 966 }
 967 
 968 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 969   if (reachable(src)) {
 970     addss(dst, as_Address(src));
 971   } else {
 972     lea(rscratch1, src);
 973     addss(dst, Address(rscratch1, 0));
 974   }
 975 }
 976 
 977 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 978   if (reachable(src)) {
 979     Assembler::addpd(dst, as_Address(src));
 980   } else {
 981     lea(rscratch1, src);
 982     Assembler::addpd(dst, Address(rscratch1, 0));
 983   }
 984 }
 985 
 986 void MacroAssembler::align(int modulus) {
 987   align(modulus, offset());
 988 }
 989 
 990 void MacroAssembler::align(int modulus, int target) {
 991   if (target % modulus != 0) {
 992     nop(modulus - (target % modulus));
 993   }
 994 }
 995 
 996 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 997   // Used in sign-masking with aligned address.
 998   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 999   if (reachable(src)) {
1000     Assembler::andpd(dst, as_Address(src));
1001   } else {
1002     lea(rscratch1, src);
1003     Assembler::andpd(dst, Address(rscratch1, 0));
1004   }
1005 }
1006 
1007 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1008   // Used in sign-masking with aligned address.
1009   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1010   if (reachable(src)) {
1011     Assembler::andps(dst, as_Address(src));
1012   } else {
1013     lea(rscratch1, src);
1014     Assembler::andps(dst, Address(rscratch1, 0));
1015   }
1016 }
1017 
1018 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1019   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1020 }
1021 
1022 void MacroAssembler::atomic_incl(Address counter_addr) {
1023   if (os::is_MP())
1024     lock();
1025   incrementl(counter_addr);
1026 }
1027 
1028 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1029   if (reachable(counter_addr)) {
1030     atomic_incl(as_Address(counter_addr));
1031   } else {
1032     lea(scr, counter_addr);
1033     atomic_incl(Address(scr, 0));
1034   }
1035 }
1036 
1037 #ifdef _LP64
1038 void MacroAssembler::atomic_incq(Address counter_addr) {
1039   if (os::is_MP())
1040     lock();
1041   incrementq(counter_addr);
1042 }
1043 
1044 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1045   if (reachable(counter_addr)) {
1046     atomic_incq(as_Address(counter_addr));
1047   } else {
1048     lea(scr, counter_addr);
1049     atomic_incq(Address(scr, 0));
1050   }
1051 }
1052 #endif
1053 
1054 // Writes to stack successive pages until offset reached to check for
1055 // stack overflow + shadow pages.  This clobbers tmp.
1056 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1057   movptr(tmp, rsp);
1058   // Bang stack for total size given plus shadow page size.
1059   // Bang one page at a time because large size can bang beyond yellow and
1060   // red zones.
1061   Label loop;
1062   bind(loop);
1063   movl(Address(tmp, (-os::vm_page_size())), size );
1064   subptr(tmp, os::vm_page_size());
1065   subl(size, os::vm_page_size());
1066   jcc(Assembler::greater, loop);
1067 
1068   // Bang down shadow pages too.
1069   // At this point, (tmp-0) is the last address touched, so don't
1070   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1071   // was post-decremented.)  Skip this address by starting at i=1, and
1072   // touch a few more pages below.  N.B.  It is important to touch all
1073   // the way down including all pages in the shadow zone.
1074   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1075     // this could be any sized move but this is can be a debugging crumb
1076     // so the bigger the better.
1077     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1078   }
1079 }
1080 
1081 void MacroAssembler::reserved_stack_check() {
1082     // testing if reserved zone needs to be enabled
1083     Label no_reserved_zone_enabling;
1084     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1085     NOT_LP64(get_thread(rsi);)
1086 
1087     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1088     jcc(Assembler::below, no_reserved_zone_enabling);
1089 
1090     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1091     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1092     should_not_reach_here();
1093 
1094     bind(no_reserved_zone_enabling);
1095 }
1096 
1097 int MacroAssembler::biased_locking_enter(Register lock_reg,
1098                                          Register obj_reg,
1099                                          Register swap_reg,
1100                                          Register tmp_reg,
1101                                          bool swap_reg_contains_mark,
1102                                          Label& done,
1103                                          Label* slow_case,
1104                                          BiasedLockingCounters* counters) {
1105   assert(UseBiasedLocking, "why call this otherwise?");
1106   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1107   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1108   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1109   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1110   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1111   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1112 
1113   if (PrintBiasedLockingStatistics && counters == NULL) {
1114     counters = BiasedLocking::counters();
1115   }
1116   // Biased locking
1117   // See whether the lock is currently biased toward our thread and
1118   // whether the epoch is still valid
1119   // Note that the runtime guarantees sufficient alignment of JavaThread
1120   // pointers to allow age to be placed into low bits
1121   // First check to see whether biasing is even enabled for this object
1122   Label cas_label;
1123   int null_check_offset = -1;
1124   if (!swap_reg_contains_mark) {
1125     null_check_offset = offset();
1126     movptr(swap_reg, mark_addr);
1127   }
1128   movptr(tmp_reg, swap_reg);
1129   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1130   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1131   jcc(Assembler::notEqual, cas_label);
1132   // The bias pattern is present in the object's header. Need to check
1133   // whether the bias owner and the epoch are both still current.
1134 #ifndef _LP64
1135   // Note that because there is no current thread register on x86_32 we
1136   // need to store off the mark word we read out of the object to
1137   // avoid reloading it and needing to recheck invariants below. This
1138   // store is unfortunate but it makes the overall code shorter and
1139   // simpler.
1140   movptr(saved_mark_addr, swap_reg);
1141 #endif
1142   if (swap_reg_contains_mark) {
1143     null_check_offset = offset();
1144   }
1145   load_prototype_header(tmp_reg, obj_reg);
1146 #ifdef _LP64
1147   orptr(tmp_reg, r15_thread);
1148   xorptr(tmp_reg, swap_reg);
1149   Register header_reg = tmp_reg;
1150 #else
1151   xorptr(tmp_reg, swap_reg);
1152   get_thread(swap_reg);
1153   xorptr(swap_reg, tmp_reg);
1154   Register header_reg = swap_reg;
1155 #endif
1156   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1157   if (counters != NULL) {
1158     cond_inc32(Assembler::zero,
1159                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1160   }
1161   jcc(Assembler::equal, done);
1162 
1163   Label try_revoke_bias;
1164   Label try_rebias;
1165 
1166   // At this point we know that the header has the bias pattern and
1167   // that we are not the bias owner in the current epoch. We need to
1168   // figure out more details about the state of the header in order to
1169   // know what operations can be legally performed on the object's
1170   // header.
1171 
1172   // If the low three bits in the xor result aren't clear, that means
1173   // the prototype header is no longer biased and we have to revoke
1174   // the bias on this object.
1175   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1176   jccb(Assembler::notZero, try_revoke_bias);
1177 
1178   // Biasing is still enabled for this data type. See whether the
1179   // epoch of the current bias is still valid, meaning that the epoch
1180   // bits of the mark word are equal to the epoch bits of the
1181   // prototype header. (Note that the prototype header's epoch bits
1182   // only change at a safepoint.) If not, attempt to rebias the object
1183   // toward the current thread. Note that we must be absolutely sure
1184   // that the current epoch is invalid in order to do this because
1185   // otherwise the manipulations it performs on the mark word are
1186   // illegal.
1187   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1188   jccb(Assembler::notZero, try_rebias);
1189 
1190   // The epoch of the current bias is still valid but we know nothing
1191   // about the owner; it might be set or it might be clear. Try to
1192   // acquire the bias of the object using an atomic operation. If this
1193   // fails we will go in to the runtime to revoke the object's bias.
1194   // Note that we first construct the presumed unbiased header so we
1195   // don't accidentally blow away another thread's valid bias.
1196   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1197   andptr(swap_reg,
1198          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1199 #ifdef _LP64
1200   movptr(tmp_reg, swap_reg);
1201   orptr(tmp_reg, r15_thread);
1202 #else
1203   get_thread(tmp_reg);
1204   orptr(tmp_reg, swap_reg);
1205 #endif
1206   if (os::is_MP()) {
1207     lock();
1208   }
1209   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1210   // If the biasing toward our thread failed, this means that
1211   // another thread succeeded in biasing it toward itself and we
1212   // need to revoke that bias. The revocation will occur in the
1213   // interpreter runtime in the slow case.
1214   if (counters != NULL) {
1215     cond_inc32(Assembler::zero,
1216                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1217   }
1218   if (slow_case != NULL) {
1219     jcc(Assembler::notZero, *slow_case);
1220   }
1221   jmp(done);
1222 
1223   bind(try_rebias);
1224   // At this point we know the epoch has expired, meaning that the
1225   // current "bias owner", if any, is actually invalid. Under these
1226   // circumstances _only_, we are allowed to use the current header's
1227   // value as the comparison value when doing the cas to acquire the
1228   // bias in the current epoch. In other words, we allow transfer of
1229   // the bias from one thread to another directly in this situation.
1230   //
1231   // FIXME: due to a lack of registers we currently blow away the age
1232   // bits in this situation. Should attempt to preserve them.
1233   load_prototype_header(tmp_reg, obj_reg);
1234 #ifdef _LP64
1235   orptr(tmp_reg, r15_thread);
1236 #else
1237   get_thread(swap_reg);
1238   orptr(tmp_reg, swap_reg);
1239   movptr(swap_reg, saved_mark_addr);
1240 #endif
1241   if (os::is_MP()) {
1242     lock();
1243   }
1244   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1245   // If the biasing toward our thread failed, then another thread
1246   // succeeded in biasing it toward itself and we need to revoke that
1247   // bias. The revocation will occur in the runtime in the slow case.
1248   if (counters != NULL) {
1249     cond_inc32(Assembler::zero,
1250                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1251   }
1252   if (slow_case != NULL) {
1253     jcc(Assembler::notZero, *slow_case);
1254   }
1255   jmp(done);
1256 
1257   bind(try_revoke_bias);
1258   // The prototype mark in the klass doesn't have the bias bit set any
1259   // more, indicating that objects of this data type are not supposed
1260   // to be biased any more. We are going to try to reset the mark of
1261   // this object to the prototype value and fall through to the
1262   // CAS-based locking scheme. Note that if our CAS fails, it means
1263   // that another thread raced us for the privilege of revoking the
1264   // bias of this particular object, so it's okay to continue in the
1265   // normal locking code.
1266   //
1267   // FIXME: due to a lack of registers we currently blow away the age
1268   // bits in this situation. Should attempt to preserve them.
1269   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1270   load_prototype_header(tmp_reg, obj_reg);
1271   if (os::is_MP()) {
1272     lock();
1273   }
1274   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1275   // Fall through to the normal CAS-based lock, because no matter what
1276   // the result of the above CAS, some thread must have succeeded in
1277   // removing the bias bit from the object's header.
1278   if (counters != NULL) {
1279     cond_inc32(Assembler::zero,
1280                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1281   }
1282 
1283   bind(cas_label);
1284 
1285   return null_check_offset;
1286 }
1287 
1288 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1289   assert(UseBiasedLocking, "why call this otherwise?");
1290 
1291   // Check for biased locking unlock case, which is a no-op
1292   // Note: we do not have to check the thread ID for two reasons.
1293   // First, the interpreter checks for IllegalMonitorStateException at
1294   // a higher level. Second, if the bias was revoked while we held the
1295   // lock, the object could not be rebiased toward another thread, so
1296   // the bias bit would be clear.
1297   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1298   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1299   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1300   jcc(Assembler::equal, done);
1301 }
1302 
1303 #ifdef COMPILER2
1304 
1305 #if INCLUDE_RTM_OPT
1306 
1307 // Update rtm_counters based on abort status
1308 // input: abort_status
1309 //        rtm_counters (RTMLockingCounters*)
1310 // flags are killed
1311 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1312 
1313   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1314   if (PrintPreciseRTMLockingStatistics) {
1315     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1316       Label check_abort;
1317       testl(abort_status, (1<<i));
1318       jccb(Assembler::equal, check_abort);
1319       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1320       bind(check_abort);
1321     }
1322   }
1323 }
1324 
1325 // Branch if (random & (count-1) != 0), count is 2^n
1326 // tmp, scr and flags are killed
1327 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1328   assert(tmp == rax, "");
1329   assert(scr == rdx, "");
1330   rdtsc(); // modifies EDX:EAX
1331   andptr(tmp, count-1);
1332   jccb(Assembler::notZero, brLabel);
1333 }
1334 
1335 // Perform abort ratio calculation, set no_rtm bit if high ratio
1336 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1337 // tmpReg, rtm_counters_Reg and flags are killed
1338 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1339                                                  Register rtm_counters_Reg,
1340                                                  RTMLockingCounters* rtm_counters,
1341                                                  Metadata* method_data) {
1342   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1343 
1344   if (RTMLockingCalculationDelay > 0) {
1345     // Delay calculation
1346     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1347     testptr(tmpReg, tmpReg);
1348     jccb(Assembler::equal, L_done);
1349   }
1350   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1351   //   Aborted transactions = abort_count * 100
1352   //   All transactions = total_count *  RTMTotalCountIncrRate
1353   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1354 
1355   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1356   cmpptr(tmpReg, RTMAbortThreshold);
1357   jccb(Assembler::below, L_check_always_rtm2);
1358   imulptr(tmpReg, tmpReg, 100);
1359 
1360   Register scrReg = rtm_counters_Reg;
1361   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1362   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1363   imulptr(scrReg, scrReg, RTMAbortRatio);
1364   cmpptr(tmpReg, scrReg);
1365   jccb(Assembler::below, L_check_always_rtm1);
1366   if (method_data != NULL) {
1367     // set rtm_state to "no rtm" in MDO
1368     mov_metadata(tmpReg, method_data);
1369     if (os::is_MP()) {
1370       lock();
1371     }
1372     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1373   }
1374   jmpb(L_done);
1375   bind(L_check_always_rtm1);
1376   // Reload RTMLockingCounters* address
1377   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1378   bind(L_check_always_rtm2);
1379   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1380   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1381   jccb(Assembler::below, L_done);
1382   if (method_data != NULL) {
1383     // set rtm_state to "always rtm" in MDO
1384     mov_metadata(tmpReg, method_data);
1385     if (os::is_MP()) {
1386       lock();
1387     }
1388     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1389   }
1390   bind(L_done);
1391 }
1392 
1393 // Update counters and perform abort ratio calculation
1394 // input:  abort_status_Reg
1395 // rtm_counters_Reg, flags are killed
1396 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1397                                    Register rtm_counters_Reg,
1398                                    RTMLockingCounters* rtm_counters,
1399                                    Metadata* method_data,
1400                                    bool profile_rtm) {
1401 
1402   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1403   // update rtm counters based on rax value at abort
1404   // reads abort_status_Reg, updates flags
1405   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1406   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1407   if (profile_rtm) {
1408     // Save abort status because abort_status_Reg is used by following code.
1409     if (RTMRetryCount > 0) {
1410       push(abort_status_Reg);
1411     }
1412     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1413     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1414     // restore abort status
1415     if (RTMRetryCount > 0) {
1416       pop(abort_status_Reg);
1417     }
1418   }
1419 }
1420 
1421 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1422 // inputs: retry_count_Reg
1423 //       : abort_status_Reg
1424 // output: retry_count_Reg decremented by 1
1425 // flags are killed
1426 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1427   Label doneRetry;
1428   assert(abort_status_Reg == rax, "");
1429   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1430   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1431   // if reason is in 0x6 and retry count != 0 then retry
1432   andptr(abort_status_Reg, 0x6);
1433   jccb(Assembler::zero, doneRetry);
1434   testl(retry_count_Reg, retry_count_Reg);
1435   jccb(Assembler::zero, doneRetry);
1436   pause();
1437   decrementl(retry_count_Reg);
1438   jmp(retryLabel);
1439   bind(doneRetry);
1440 }
1441 
1442 // Spin and retry if lock is busy,
1443 // inputs: box_Reg (monitor address)
1444 //       : retry_count_Reg
1445 // output: retry_count_Reg decremented by 1
1446 //       : clear z flag if retry count exceeded
1447 // tmp_Reg, scr_Reg, flags are killed
1448 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1449                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1450   Label SpinLoop, SpinExit, doneRetry;
1451   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1452 
1453   testl(retry_count_Reg, retry_count_Reg);
1454   jccb(Assembler::zero, doneRetry);
1455   decrementl(retry_count_Reg);
1456   movptr(scr_Reg, RTMSpinLoopCount);
1457 
1458   bind(SpinLoop);
1459   pause();
1460   decrementl(scr_Reg);
1461   jccb(Assembler::lessEqual, SpinExit);
1462   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1463   testptr(tmp_Reg, tmp_Reg);
1464   jccb(Assembler::notZero, SpinLoop);
1465 
1466   bind(SpinExit);
1467   jmp(retryLabel);
1468   bind(doneRetry);
1469   incrementl(retry_count_Reg); // clear z flag
1470 }
1471 
1472 // Use RTM for normal stack locks
1473 // Input: objReg (object to lock)
1474 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1475                                        Register retry_on_abort_count_Reg,
1476                                        RTMLockingCounters* stack_rtm_counters,
1477                                        Metadata* method_data, bool profile_rtm,
1478                                        Label& DONE_LABEL, Label& IsInflated) {
1479   assert(UseRTMForStackLocks, "why call this otherwise?");
1480   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1481   assert(tmpReg == rax, "");
1482   assert(scrReg == rdx, "");
1483   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1484 
1485   if (RTMRetryCount > 0) {
1486     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1487     bind(L_rtm_retry);
1488   }
1489   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1490   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1491   jcc(Assembler::notZero, IsInflated);
1492 
1493   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1494     Label L_noincrement;
1495     if (RTMTotalCountIncrRate > 1) {
1496       // tmpReg, scrReg and flags are killed
1497       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1498     }
1499     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1500     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1501     bind(L_noincrement);
1502   }
1503   xbegin(L_on_abort);
1504   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1505   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1506   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1507   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1508 
1509   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1510   if (UseRTMXendForLockBusy) {
1511     xend();
1512     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1513     jmp(L_decrement_retry);
1514   }
1515   else {
1516     xabort(0);
1517   }
1518   bind(L_on_abort);
1519   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1520     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1521   }
1522   bind(L_decrement_retry);
1523   if (RTMRetryCount > 0) {
1524     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1525     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1526   }
1527 }
1528 
1529 // Use RTM for inflating locks
1530 // inputs: objReg (object to lock)
1531 //         boxReg (on-stack box address (displaced header location) - KILLED)
1532 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1533 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1534                                           Register scrReg, Register retry_on_busy_count_Reg,
1535                                           Register retry_on_abort_count_Reg,
1536                                           RTMLockingCounters* rtm_counters,
1537                                           Metadata* method_data, bool profile_rtm,
1538                                           Label& DONE_LABEL) {
1539   assert(UseRTMLocking, "why call this otherwise?");
1540   assert(tmpReg == rax, "");
1541   assert(scrReg == rdx, "");
1542   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1543   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1544 
1545   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1546   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1547   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1548 
1549   if (RTMRetryCount > 0) {
1550     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1551     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1552     bind(L_rtm_retry);
1553   }
1554   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1555     Label L_noincrement;
1556     if (RTMTotalCountIncrRate > 1) {
1557       // tmpReg, scrReg and flags are killed
1558       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1559     }
1560     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1561     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1562     bind(L_noincrement);
1563   }
1564   xbegin(L_on_abort);
1565   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1566   movptr(tmpReg, Address(tmpReg, owner_offset));
1567   testptr(tmpReg, tmpReg);
1568   jcc(Assembler::zero, DONE_LABEL);
1569   if (UseRTMXendForLockBusy) {
1570     xend();
1571     jmp(L_decrement_retry);
1572   }
1573   else {
1574     xabort(0);
1575   }
1576   bind(L_on_abort);
1577   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1578   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1579     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1580   }
1581   if (RTMRetryCount > 0) {
1582     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1583     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1584   }
1585 
1586   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1587   testptr(tmpReg, tmpReg) ;
1588   jccb(Assembler::notZero, L_decrement_retry) ;
1589 
1590   // Appears unlocked - try to swing _owner from null to non-null.
1591   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1592 #ifdef _LP64
1593   Register threadReg = r15_thread;
1594 #else
1595   get_thread(scrReg);
1596   Register threadReg = scrReg;
1597 #endif
1598   if (os::is_MP()) {
1599     lock();
1600   }
1601   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1602 
1603   if (RTMRetryCount > 0) {
1604     // success done else retry
1605     jccb(Assembler::equal, DONE_LABEL) ;
1606     bind(L_decrement_retry);
1607     // Spin and retry if lock is busy.
1608     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1609   }
1610   else {
1611     bind(L_decrement_retry);
1612   }
1613 }
1614 
1615 #endif //  INCLUDE_RTM_OPT
1616 
1617 // Fast_Lock and Fast_Unlock used by C2
1618 
1619 // Because the transitions from emitted code to the runtime
1620 // monitorenter/exit helper stubs are so slow it's critical that
1621 // we inline both the stack-locking fast-path and the inflated fast path.
1622 //
1623 // See also: cmpFastLock and cmpFastUnlock.
1624 //
1625 // What follows is a specialized inline transliteration of the code
1626 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1627 // another option would be to emit TrySlowEnter and TrySlowExit methods
1628 // at startup-time.  These methods would accept arguments as
1629 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1630 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1631 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1632 // In practice, however, the # of lock sites is bounded and is usually small.
1633 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1634 // if the processor uses simple bimodal branch predictors keyed by EIP
1635 // Since the helper routines would be called from multiple synchronization
1636 // sites.
1637 //
1638 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1639 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1640 // to those specialized methods.  That'd give us a mostly platform-independent
1641 // implementation that the JITs could optimize and inline at their pleasure.
1642 // Done correctly, the only time we'd need to cross to native could would be
1643 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1644 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1645 // (b) explicit barriers or fence operations.
1646 //
1647 // TODO:
1648 //
1649 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1650 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1651 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1652 //    the lock operators would typically be faster than reifying Self.
1653 //
1654 // *  Ideally I'd define the primitives as:
1655 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1656 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1657 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1658 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1659 //    Furthermore the register assignments are overconstrained, possibly resulting in
1660 //    sub-optimal code near the synchronization site.
1661 //
1662 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1663 //    Alternately, use a better sp-proximity test.
1664 //
1665 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1666 //    Either one is sufficient to uniquely identify a thread.
1667 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1668 //
1669 // *  Intrinsify notify() and notifyAll() for the common cases where the
1670 //    object is locked by the calling thread but the waitlist is empty.
1671 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1672 //
1673 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1674 //    But beware of excessive branch density on AMD Opterons.
1675 //
1676 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1677 //    or failure of the fast-path.  If the fast-path fails then we pass
1678 //    control to the slow-path, typically in C.  In Fast_Lock and
1679 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1680 //    will emit a conditional branch immediately after the node.
1681 //    So we have branches to branches and lots of ICC.ZF games.
1682 //    Instead, it might be better to have C2 pass a "FailureLabel"
1683 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1684 //    will drop through the node.  ICC.ZF is undefined at exit.
1685 //    In the case of failure, the node will branch directly to the
1686 //    FailureLabel
1687 
1688 
1689 // obj: object to lock
1690 // box: on-stack box address (displaced header location) - KILLED
1691 // rax,: tmp -- KILLED
1692 // scr: tmp -- KILLED
1693 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1694                                Register scrReg, Register cx1Reg, Register cx2Reg,
1695                                BiasedLockingCounters* counters,
1696                                RTMLockingCounters* rtm_counters,
1697                                RTMLockingCounters* stack_rtm_counters,
1698                                Metadata* method_data,
1699                                bool use_rtm, bool profile_rtm) {
1700   // Ensure the register assignments are disjoint
1701   assert(tmpReg == rax, "");
1702 
1703   if (use_rtm) {
1704     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1705   } else {
1706     assert(cx1Reg == noreg, "");
1707     assert(cx2Reg == noreg, "");
1708     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1709   }
1710 
1711   if (counters != NULL) {
1712     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1713   }
1714   if (EmitSync & 1) {
1715       // set box->dhw = markOopDesc::unused_mark()
1716       // Force all sync thru slow-path: slow_enter() and slow_exit()
1717       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1718       cmpptr (rsp, (int32_t)NULL_WORD);
1719   } else {
1720     // Possible cases that we'll encounter in fast_lock
1721     // ------------------------------------------------
1722     // * Inflated
1723     //    -- unlocked
1724     //    -- Locked
1725     //       = by self
1726     //       = by other
1727     // * biased
1728     //    -- by Self
1729     //    -- by other
1730     // * neutral
1731     // * stack-locked
1732     //    -- by self
1733     //       = sp-proximity test hits
1734     //       = sp-proximity test generates false-negative
1735     //    -- by other
1736     //
1737 
1738     Label IsInflated, DONE_LABEL;
1739 
1740     // it's stack-locked, biased or neutral
1741     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1742     // order to reduce the number of conditional branches in the most common cases.
1743     // Beware -- there's a subtle invariant that fetch of the markword
1744     // at [FETCH], below, will never observe a biased encoding (*101b).
1745     // If this invariant is not held we risk exclusion (safety) failure.
1746     if (UseBiasedLocking && !UseOptoBiasInlining) {
1747       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1748     }
1749 
1750 #if INCLUDE_RTM_OPT
1751     if (UseRTMForStackLocks && use_rtm) {
1752       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1753                         stack_rtm_counters, method_data, profile_rtm,
1754                         DONE_LABEL, IsInflated);
1755     }
1756 #endif // INCLUDE_RTM_OPT
1757 
1758     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1759     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1760     jccb(Assembler::notZero, IsInflated);
1761 
1762     // Attempt stack-locking ...
1763     orptr (tmpReg, markOopDesc::unlocked_value);
1764     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1765     if (os::is_MP()) {
1766       lock();
1767     }
1768     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1769     if (counters != NULL) {
1770       cond_inc32(Assembler::equal,
1771                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1772     }
1773     jcc(Assembler::equal, DONE_LABEL);           // Success
1774 
1775     // Recursive locking.
1776     // The object is stack-locked: markword contains stack pointer to BasicLock.
1777     // Locked by current thread if difference with current SP is less than one page.
1778     subptr(tmpReg, rsp);
1779     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1780     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1781     movptr(Address(boxReg, 0), tmpReg);
1782     if (counters != NULL) {
1783       cond_inc32(Assembler::equal,
1784                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1785     }
1786     jmp(DONE_LABEL);
1787 
1788     bind(IsInflated);
1789     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1790 
1791 #if INCLUDE_RTM_OPT
1792     // Use the same RTM locking code in 32- and 64-bit VM.
1793     if (use_rtm) {
1794       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1795                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1796     } else {
1797 #endif // INCLUDE_RTM_OPT
1798 
1799 #ifndef _LP64
1800     // The object is inflated.
1801 
1802     // boxReg refers to the on-stack BasicLock in the current frame.
1803     // We'd like to write:
1804     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1805     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1806     // additional latency as we have another ST in the store buffer that must drain.
1807 
1808     if (EmitSync & 8192) {
1809        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1810        get_thread (scrReg);
1811        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1812        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1813        if (os::is_MP()) {
1814          lock();
1815        }
1816        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1817     } else
1818     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1819        // register juggle because we need tmpReg for cmpxchgptr below
1820        movptr(scrReg, boxReg);
1821        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1822 
1823        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1824        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1825           // prefetchw [eax + Offset(_owner)-2]
1826           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1827        }
1828 
1829        if ((EmitSync & 64) == 0) {
1830          // Optimistic form: consider XORL tmpReg,tmpReg
1831          movptr(tmpReg, NULL_WORD);
1832        } else {
1833          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1834          // Test-And-CAS instead of CAS
1835          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1836          testptr(tmpReg, tmpReg);                   // Locked ?
1837          jccb  (Assembler::notZero, DONE_LABEL);
1838        }
1839 
1840        // Appears unlocked - try to swing _owner from null to non-null.
1841        // Ideally, I'd manifest "Self" with get_thread and then attempt
1842        // to CAS the register containing Self into m->Owner.
1843        // But we don't have enough registers, so instead we can either try to CAS
1844        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1845        // we later store "Self" into m->Owner.  Transiently storing a stack address
1846        // (rsp or the address of the box) into  m->owner is harmless.
1847        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1848        if (os::is_MP()) {
1849          lock();
1850        }
1851        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1852        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1853        // If we weren't able to swing _owner from NULL to the BasicLock
1854        // then take the slow path.
1855        jccb  (Assembler::notZero, DONE_LABEL);
1856        // update _owner from BasicLock to thread
1857        get_thread (scrReg);                    // beware: clobbers ICCs
1858        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1859        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1860 
1861        // If the CAS fails we can either retry or pass control to the slow-path.
1862        // We use the latter tactic.
1863        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1864        // If the CAS was successful ...
1865        //   Self has acquired the lock
1866        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1867        // Intentional fall-through into DONE_LABEL ...
1868     } else {
1869        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1870        movptr(boxReg, tmpReg);
1871 
1872        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1873        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1874           // prefetchw [eax + Offset(_owner)-2]
1875           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1876        }
1877 
1878        if ((EmitSync & 64) == 0) {
1879          // Optimistic form
1880          xorptr  (tmpReg, tmpReg);
1881        } else {
1882          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1883          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1884          testptr(tmpReg, tmpReg);                   // Locked ?
1885          jccb  (Assembler::notZero, DONE_LABEL);
1886        }
1887 
1888        // Appears unlocked - try to swing _owner from null to non-null.
1889        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1890        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1891        get_thread (scrReg);
1892        if (os::is_MP()) {
1893          lock();
1894        }
1895        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1896 
1897        // If the CAS fails we can either retry or pass control to the slow-path.
1898        // We use the latter tactic.
1899        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1900        // If the CAS was successful ...
1901        //   Self has acquired the lock
1902        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1903        // Intentional fall-through into DONE_LABEL ...
1904     }
1905 #else // _LP64
1906     // It's inflated
1907     movq(scrReg, tmpReg);
1908     xorq(tmpReg, tmpReg);
1909 
1910     if (os::is_MP()) {
1911       lock();
1912     }
1913     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1914     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1915     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1916     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1917     // Intentional fall-through into DONE_LABEL ...
1918     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1919 #endif // _LP64
1920 #if INCLUDE_RTM_OPT
1921     } // use_rtm()
1922 #endif
1923     // DONE_LABEL is a hot target - we'd really like to place it at the
1924     // start of cache line by padding with NOPs.
1925     // See the AMD and Intel software optimization manuals for the
1926     // most efficient "long" NOP encodings.
1927     // Unfortunately none of our alignment mechanisms suffice.
1928     bind(DONE_LABEL);
1929 
1930     // At DONE_LABEL the icc ZFlag is set as follows ...
1931     // Fast_Unlock uses the same protocol.
1932     // ZFlag == 1 -> Success
1933     // ZFlag == 0 -> Failure - force control through the slow-path
1934   }
1935 }
1936 
1937 // obj: object to unlock
1938 // box: box address (displaced header location), killed.  Must be EAX.
1939 // tmp: killed, cannot be obj nor box.
1940 //
1941 // Some commentary on balanced locking:
1942 //
1943 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1944 // Methods that don't have provably balanced locking are forced to run in the
1945 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1946 // The interpreter provides two properties:
1947 // I1:  At return-time the interpreter automatically and quietly unlocks any
1948 //      objects acquired the current activation (frame).  Recall that the
1949 //      interpreter maintains an on-stack list of locks currently held by
1950 //      a frame.
1951 // I2:  If a method attempts to unlock an object that is not held by the
1952 //      the frame the interpreter throws IMSX.
1953 //
1954 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1955 // B() doesn't have provably balanced locking so it runs in the interpreter.
1956 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1957 // is still locked by A().
1958 //
1959 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1960 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1961 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1962 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1963 // Arguably given that the spec legislates the JNI case as undefined our implementation
1964 // could reasonably *avoid* checking owner in Fast_Unlock().
1965 // In the interest of performance we elide m->Owner==Self check in unlock.
1966 // A perfectly viable alternative is to elide the owner check except when
1967 // Xcheck:jni is enabled.
1968 
1969 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1970   assert(boxReg == rax, "");
1971   assert_different_registers(objReg, boxReg, tmpReg);
1972 
1973   if (EmitSync & 4) {
1974     // Disable - inhibit all inlining.  Force control through the slow-path
1975     cmpptr (rsp, 0);
1976   } else {
1977     Label DONE_LABEL, Stacked, CheckSucc;
1978 
1979     // Critically, the biased locking test must have precedence over
1980     // and appear before the (box->dhw == 0) recursive stack-lock test.
1981     if (UseBiasedLocking && !UseOptoBiasInlining) {
1982        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1983     }
1984 
1985 #if INCLUDE_RTM_OPT
1986     if (UseRTMForStackLocks && use_rtm) {
1987       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1988       Label L_regular_unlock;
1989       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1990       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1991       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1992       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1993       xend();                                       // otherwise end...
1994       jmp(DONE_LABEL);                              // ... and we're done
1995       bind(L_regular_unlock);
1996     }
1997 #endif
1998 
1999     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2000     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2001     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2002     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2003     jccb  (Assembler::zero, Stacked);
2004 
2005     // It's inflated.
2006 #if INCLUDE_RTM_OPT
2007     if (use_rtm) {
2008       Label L_regular_inflated_unlock;
2009       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2010       movptr(boxReg, Address(tmpReg, owner_offset));
2011       testptr(boxReg, boxReg);
2012       jccb(Assembler::notZero, L_regular_inflated_unlock);
2013       xend();
2014       jmpb(DONE_LABEL);
2015       bind(L_regular_inflated_unlock);
2016     }
2017 #endif
2018 
2019     // Despite our balanced locking property we still check that m->_owner == Self
2020     // as java routines or native JNI code called by this thread might
2021     // have released the lock.
2022     // Refer to the comments in synchronizer.cpp for how we might encode extra
2023     // state in _succ so we can avoid fetching EntryList|cxq.
2024     //
2025     // I'd like to add more cases in fast_lock() and fast_unlock() --
2026     // such as recursive enter and exit -- but we have to be wary of
2027     // I$ bloat, T$ effects and BP$ effects.
2028     //
2029     // If there's no contention try a 1-0 exit.  That is, exit without
2030     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2031     // we detect and recover from the race that the 1-0 exit admits.
2032     //
2033     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2034     // before it STs null into _owner, releasing the lock.  Updates
2035     // to data protected by the critical section must be visible before
2036     // we drop the lock (and thus before any other thread could acquire
2037     // the lock and observe the fields protected by the lock).
2038     // IA32's memory-model is SPO, so STs are ordered with respect to
2039     // each other and there's no need for an explicit barrier (fence).
2040     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2041 #ifndef _LP64
2042     get_thread (boxReg);
2043     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2044       // prefetchw [ebx + Offset(_owner)-2]
2045       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2046     }
2047 
2048     // Note that we could employ various encoding schemes to reduce
2049     // the number of loads below (currently 4) to just 2 or 3.
2050     // Refer to the comments in synchronizer.cpp.
2051     // In practice the chain of fetches doesn't seem to impact performance, however.
2052     xorptr(boxReg, boxReg);
2053     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2054        // Attempt to reduce branch density - AMD's branch predictor.
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2056        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2057        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2058        jccb  (Assembler::notZero, DONE_LABEL);
2059        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2060        jmpb  (DONE_LABEL);
2061     } else {
2062        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2063        jccb  (Assembler::notZero, DONE_LABEL);
2064        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2065        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2066        jccb  (Assembler::notZero, CheckSucc);
2067        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2068        jmpb  (DONE_LABEL);
2069     }
2070 
2071     // The Following code fragment (EmitSync & 65536) improves the performance of
2072     // contended applications and contended synchronization microbenchmarks.
2073     // Unfortunately the emission of the code - even though not executed - causes regressions
2074     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2075     // with an equal number of never-executed NOPs results in the same regression.
2076     // We leave it off by default.
2077 
2078     if ((EmitSync & 65536) != 0) {
2079        Label LSuccess, LGoSlowPath ;
2080 
2081        bind  (CheckSucc);
2082 
2083        // Optional pre-test ... it's safe to elide this
2084        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2085        jccb(Assembler::zero, LGoSlowPath);
2086 
2087        // We have a classic Dekker-style idiom:
2088        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2089        // There are a number of ways to implement the barrier:
2090        // (1) lock:andl &m->_owner, 0
2091        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2092        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2093        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2094        // (2) If supported, an explicit MFENCE is appealing.
2095        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2096        //     particularly if the write-buffer is full as might be the case if
2097        //     if stores closely precede the fence or fence-equivalent instruction.
2098        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2099        //     as the situation has changed with Nehalem and Shanghai.
2100        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2101        //     The $lines underlying the top-of-stack should be in M-state.
2102        //     The locked add instruction is serializing, of course.
2103        // (4) Use xchg, which is serializing
2104        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2105        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2106        //     The integer condition codes will tell us if succ was 0.
2107        //     Since _succ and _owner should reside in the same $line and
2108        //     we just stored into _owner, it's likely that the $line
2109        //     remains in M-state for the lock:orl.
2110        //
2111        // We currently use (3), although it's likely that switching to (2)
2112        // is correct for the future.
2113 
2114        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2115        if (os::is_MP()) {
2116          lock(); addptr(Address(rsp, 0), 0);
2117        }
2118        // Ratify _succ remains non-null
2119        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2120        jccb  (Assembler::notZero, LSuccess);
2121 
2122        xorptr(boxReg, boxReg);                  // box is really EAX
2123        if (os::is_MP()) { lock(); }
2124        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2125        // There's no successor so we tried to regrab the lock with the
2126        // placeholder value. If that didn't work, then another thread
2127        // grabbed the lock so we're done (and exit was a success).
2128        jccb  (Assembler::notEqual, LSuccess);
2129        // Since we're low on registers we installed rsp as a placeholding in _owner.
2130        // Now install Self over rsp.  This is safe as we're transitioning from
2131        // non-null to non=null
2132        get_thread (boxReg);
2133        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2134        // Intentional fall-through into LGoSlowPath ...
2135 
2136        bind  (LGoSlowPath);
2137        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2138        jmpb  (DONE_LABEL);
2139 
2140        bind  (LSuccess);
2141        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2142        jmpb  (DONE_LABEL);
2143     }
2144 
2145     bind (Stacked);
2146     // It's not inflated and it's not recursively stack-locked and it's not biased.
2147     // It must be stack-locked.
2148     // Try to reset the header to displaced header.
2149     // The "box" value on the stack is stable, so we can reload
2150     // and be assured we observe the same value as above.
2151     movptr(tmpReg, Address(boxReg, 0));
2152     if (os::is_MP()) {
2153       lock();
2154     }
2155     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2156     // Intention fall-thru into DONE_LABEL
2157 
2158     // DONE_LABEL is a hot target - we'd really like to place it at the
2159     // start of cache line by padding with NOPs.
2160     // See the AMD and Intel software optimization manuals for the
2161     // most efficient "long" NOP encodings.
2162     // Unfortunately none of our alignment mechanisms suffice.
2163     if ((EmitSync & 65536) == 0) {
2164        bind (CheckSucc);
2165     }
2166 #else // _LP64
2167     // It's inflated
2168     if (EmitSync & 1024) {
2169       // Emit code to check that _owner == Self
2170       // We could fold the _owner test into subsequent code more efficiently
2171       // than using a stand-alone check, but since _owner checking is off by
2172       // default we don't bother. We also might consider predicating the
2173       // _owner==Self check on Xcheck:jni or running on a debug build.
2174       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2175       xorptr(boxReg, r15_thread);
2176     } else {
2177       xorptr(boxReg, boxReg);
2178     }
2179     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2180     jccb  (Assembler::notZero, DONE_LABEL);
2181     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2182     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2183     jccb  (Assembler::notZero, CheckSucc);
2184     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2185     jmpb  (DONE_LABEL);
2186 
2187     if ((EmitSync & 65536) == 0) {
2188       // Try to avoid passing control into the slow_path ...
2189       Label LSuccess, LGoSlowPath ;
2190       bind  (CheckSucc);
2191 
2192       // The following optional optimization can be elided if necessary
2193       // Effectively: if (succ == null) goto SlowPath
2194       // The code reduces the window for a race, however,
2195       // and thus benefits performance.
2196       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2197       jccb  (Assembler::zero, LGoSlowPath);
2198 
2199       xorptr(boxReg, boxReg);
2200       if ((EmitSync & 16) && os::is_MP()) {
2201         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2202       } else {
2203         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2204         if (os::is_MP()) {
2205           // Memory barrier/fence
2206           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2207           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2208           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2209           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2210           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2211           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2212           lock(); addl(Address(rsp, 0), 0);
2213         }
2214       }
2215       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2216       jccb  (Assembler::notZero, LSuccess);
2217 
2218       // Rare inopportune interleaving - race.
2219       // The successor vanished in the small window above.
2220       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2221       // We need to ensure progress and succession.
2222       // Try to reacquire the lock.
2223       // If that fails then the new owner is responsible for succession and this
2224       // thread needs to take no further action and can exit via the fast path (success).
2225       // If the re-acquire succeeds then pass control into the slow path.
2226       // As implemented, this latter mode is horrible because we generated more
2227       // coherence traffic on the lock *and* artifically extended the critical section
2228       // length while by virtue of passing control into the slow path.
2229 
2230       // box is really RAX -- the following CMPXCHG depends on that binding
2231       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2232       if (os::is_MP()) { lock(); }
2233       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2234       // There's no successor so we tried to regrab the lock.
2235       // If that didn't work, then another thread grabbed the
2236       // lock so we're done (and exit was a success).
2237       jccb  (Assembler::notEqual, LSuccess);
2238       // Intentional fall-through into slow-path
2239 
2240       bind  (LGoSlowPath);
2241       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2242       jmpb  (DONE_LABEL);
2243 
2244       bind  (LSuccess);
2245       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2246       jmpb  (DONE_LABEL);
2247     }
2248 
2249     bind  (Stacked);
2250     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2251     if (os::is_MP()) { lock(); }
2252     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2253 
2254     if (EmitSync & 65536) {
2255        bind (CheckSucc);
2256     }
2257 #endif
2258     bind(DONE_LABEL);
2259   }
2260 }
2261 #endif // COMPILER2
2262 
2263 void MacroAssembler::c2bool(Register x) {
2264   // implements x == 0 ? 0 : 1
2265   // note: must only look at least-significant byte of x
2266   //       since C-style booleans are stored in one byte
2267   //       only! (was bug)
2268   andl(x, 0xFF);
2269   setb(Assembler::notZero, x);
2270 }
2271 
2272 // Wouldn't need if AddressLiteral version had new name
2273 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2274   Assembler::call(L, rtype);
2275 }
2276 
2277 void MacroAssembler::call(Register entry) {
2278   Assembler::call(entry);
2279 }
2280 
2281 void MacroAssembler::call(AddressLiteral entry) {
2282   if (reachable(entry)) {
2283     Assembler::call_literal(entry.target(), entry.rspec());
2284   } else {
2285     lea(rscratch1, entry);
2286     Assembler::call(rscratch1);
2287   }
2288 }
2289 
2290 void MacroAssembler::ic_call(address entry, jint method_index) {
2291   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2292   movptr(rax, (intptr_t)Universe::non_oop_word());
2293   call(AddressLiteral(entry, rh));
2294 }
2295 
2296 // Implementation of call_VM versions
2297 
2298 void MacroAssembler::call_VM(Register oop_result,
2299                              address entry_point,
2300                              bool check_exceptions) {
2301   Label C, E;
2302   call(C, relocInfo::none);
2303   jmp(E);
2304 
2305   bind(C);
2306   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2307   ret(0);
2308 
2309   bind(E);
2310 }
2311 
2312 void MacroAssembler::call_VM(Register oop_result,
2313                              address entry_point,
2314                              Register arg_1,
2315                              bool check_exceptions) {
2316   Label C, E;
2317   call(C, relocInfo::none);
2318   jmp(E);
2319 
2320   bind(C);
2321   pass_arg1(this, arg_1);
2322   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2323   ret(0);
2324 
2325   bind(E);
2326 }
2327 
2328 void MacroAssembler::call_VM(Register oop_result,
2329                              address entry_point,
2330                              Register arg_1,
2331                              Register arg_2,
2332                              bool check_exceptions) {
2333   Label C, E;
2334   call(C, relocInfo::none);
2335   jmp(E);
2336 
2337   bind(C);
2338 
2339   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2340 
2341   pass_arg2(this, arg_2);
2342   pass_arg1(this, arg_1);
2343   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2344   ret(0);
2345 
2346   bind(E);
2347 }
2348 
2349 void MacroAssembler::call_VM(Register oop_result,
2350                              address entry_point,
2351                              Register arg_1,
2352                              Register arg_2,
2353                              Register arg_3,
2354                              bool check_exceptions) {
2355   Label C, E;
2356   call(C, relocInfo::none);
2357   jmp(E);
2358 
2359   bind(C);
2360 
2361   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2362   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2363   pass_arg3(this, arg_3);
2364 
2365   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2366   pass_arg2(this, arg_2);
2367 
2368   pass_arg1(this, arg_1);
2369   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2370   ret(0);
2371 
2372   bind(E);
2373 }
2374 
2375 void MacroAssembler::call_VM(Register oop_result,
2376                              Register last_java_sp,
2377                              address entry_point,
2378                              int number_of_arguments,
2379                              bool check_exceptions) {
2380   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2381   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2382 }
2383 
2384 void MacroAssembler::call_VM(Register oop_result,
2385                              Register last_java_sp,
2386                              address entry_point,
2387                              Register arg_1,
2388                              bool check_exceptions) {
2389   pass_arg1(this, arg_1);
2390   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2391 }
2392 
2393 void MacroAssembler::call_VM(Register oop_result,
2394                              Register last_java_sp,
2395                              address entry_point,
2396                              Register arg_1,
2397                              Register arg_2,
2398                              bool check_exceptions) {
2399 
2400   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2401   pass_arg2(this, arg_2);
2402   pass_arg1(this, arg_1);
2403   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2404 }
2405 
2406 void MacroAssembler::call_VM(Register oop_result,
2407                              Register last_java_sp,
2408                              address entry_point,
2409                              Register arg_1,
2410                              Register arg_2,
2411                              Register arg_3,
2412                              bool check_exceptions) {
2413   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2414   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2415   pass_arg3(this, arg_3);
2416   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2417   pass_arg2(this, arg_2);
2418   pass_arg1(this, arg_1);
2419   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2420 }
2421 
2422 void MacroAssembler::super_call_VM(Register oop_result,
2423                                    Register last_java_sp,
2424                                    address entry_point,
2425                                    int number_of_arguments,
2426                                    bool check_exceptions) {
2427   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2428   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2429 }
2430 
2431 void MacroAssembler::super_call_VM(Register oop_result,
2432                                    Register last_java_sp,
2433                                    address entry_point,
2434                                    Register arg_1,
2435                                    bool check_exceptions) {
2436   pass_arg1(this, arg_1);
2437   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2438 }
2439 
2440 void MacroAssembler::super_call_VM(Register oop_result,
2441                                    Register last_java_sp,
2442                                    address entry_point,
2443                                    Register arg_1,
2444                                    Register arg_2,
2445                                    bool check_exceptions) {
2446 
2447   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2448   pass_arg2(this, arg_2);
2449   pass_arg1(this, arg_1);
2450   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2451 }
2452 
2453 void MacroAssembler::super_call_VM(Register oop_result,
2454                                    Register last_java_sp,
2455                                    address entry_point,
2456                                    Register arg_1,
2457                                    Register arg_2,
2458                                    Register arg_3,
2459                                    bool check_exceptions) {
2460   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2461   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2462   pass_arg3(this, arg_3);
2463   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2464   pass_arg2(this, arg_2);
2465   pass_arg1(this, arg_1);
2466   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2467 }
2468 
2469 void MacroAssembler::call_VM_base(Register oop_result,
2470                                   Register java_thread,
2471                                   Register last_java_sp,
2472                                   address  entry_point,
2473                                   int      number_of_arguments,
2474                                   bool     check_exceptions) {
2475   // determine java_thread register
2476   if (!java_thread->is_valid()) {
2477 #ifdef _LP64
2478     java_thread = r15_thread;
2479 #else
2480     java_thread = rdi;
2481     get_thread(java_thread);
2482 #endif // LP64
2483   }
2484   // determine last_java_sp register
2485   if (!last_java_sp->is_valid()) {
2486     last_java_sp = rsp;
2487   }
2488   // debugging support
2489   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2490   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2491 #ifdef ASSERT
2492   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2493   // r12 is the heapbase.
2494   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2495 #endif // ASSERT
2496 
2497   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2498   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2499 
2500   // push java thread (becomes first argument of C function)
2501 
2502   NOT_LP64(push(java_thread); number_of_arguments++);
2503   LP64_ONLY(mov(c_rarg0, r15_thread));
2504 
2505   // set last Java frame before call
2506   assert(last_java_sp != rbp, "can't use ebp/rbp");
2507 
2508   // Only interpreter should have to set fp
2509   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2510 
2511   // do the call, remove parameters
2512   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2513 
2514   // restore the thread (cannot use the pushed argument since arguments
2515   // may be overwritten by C code generated by an optimizing compiler);
2516   // however can use the register value directly if it is callee saved.
2517   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2518     // rdi & rsi (also r15) are callee saved -> nothing to do
2519 #ifdef ASSERT
2520     guarantee(java_thread != rax, "change this code");
2521     push(rax);
2522     { Label L;
2523       get_thread(rax);
2524       cmpptr(java_thread, rax);
2525       jcc(Assembler::equal, L);
2526       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2527       bind(L);
2528     }
2529     pop(rax);
2530 #endif
2531   } else {
2532     get_thread(java_thread);
2533   }
2534   // reset last Java frame
2535   // Only interpreter should have to clear fp
2536   reset_last_Java_frame(java_thread, true);
2537 
2538    // C++ interp handles this in the interpreter
2539   check_and_handle_popframe(java_thread);
2540   check_and_handle_earlyret(java_thread);
2541 
2542   if (check_exceptions) {
2543     // check for pending exceptions (java_thread is set upon return)
2544     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2545 #ifndef _LP64
2546     jump_cc(Assembler::notEqual,
2547             RuntimeAddress(StubRoutines::forward_exception_entry()));
2548 #else
2549     // This used to conditionally jump to forward_exception however it is
2550     // possible if we relocate that the branch will not reach. So we must jump
2551     // around so we can always reach
2552 
2553     Label ok;
2554     jcc(Assembler::equal, ok);
2555     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2556     bind(ok);
2557 #endif // LP64
2558   }
2559 
2560   // get oop result if there is one and reset the value in the thread
2561   if (oop_result->is_valid()) {
2562     get_vm_result(oop_result, java_thread);
2563   }
2564 }
2565 
2566 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2567 
2568   // Calculate the value for last_Java_sp
2569   // somewhat subtle. call_VM does an intermediate call
2570   // which places a return address on the stack just under the
2571   // stack pointer as the user finsihed with it. This allows
2572   // use to retrieve last_Java_pc from last_Java_sp[-1].
2573   // On 32bit we then have to push additional args on the stack to accomplish
2574   // the actual requested call. On 64bit call_VM only can use register args
2575   // so the only extra space is the return address that call_VM created.
2576   // This hopefully explains the calculations here.
2577 
2578 #ifdef _LP64
2579   // We've pushed one address, correct last_Java_sp
2580   lea(rax, Address(rsp, wordSize));
2581 #else
2582   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2583 #endif // LP64
2584 
2585   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2586 
2587 }
2588 
2589 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2590 void MacroAssembler::call_VM_leaf0(address entry_point) {
2591   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2592 }
2593 
2594 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2595   call_VM_leaf_base(entry_point, number_of_arguments);
2596 }
2597 
2598 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2599   pass_arg0(this, arg_0);
2600   call_VM_leaf(entry_point, 1);
2601 }
2602 
2603 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2604 
2605   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2606   pass_arg1(this, arg_1);
2607   pass_arg0(this, arg_0);
2608   call_VM_leaf(entry_point, 2);
2609 }
2610 
2611 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2612   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2613   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2614   pass_arg2(this, arg_2);
2615   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2616   pass_arg1(this, arg_1);
2617   pass_arg0(this, arg_0);
2618   call_VM_leaf(entry_point, 3);
2619 }
2620 
2621 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2622   pass_arg0(this, arg_0);
2623   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2624 }
2625 
2626 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2627 
2628   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2629   pass_arg1(this, arg_1);
2630   pass_arg0(this, arg_0);
2631   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2632 }
2633 
2634 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2635   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2636   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2637   pass_arg2(this, arg_2);
2638   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2639   pass_arg1(this, arg_1);
2640   pass_arg0(this, arg_0);
2641   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2642 }
2643 
2644 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2645   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2646   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2647   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2648   pass_arg3(this, arg_3);
2649   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2650   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2651   pass_arg2(this, arg_2);
2652   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2653   pass_arg1(this, arg_1);
2654   pass_arg0(this, arg_0);
2655   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2656 }
2657 
2658 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2659   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2660   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2661   verify_oop(oop_result, "broken oop in call_VM_base");
2662 }
2663 
2664 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2665   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2666   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2667 }
2668 
2669 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2670 }
2671 
2672 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2673 }
2674 
2675 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2676   if (reachable(src1)) {
2677     cmpl(as_Address(src1), imm);
2678   } else {
2679     lea(rscratch1, src1);
2680     cmpl(Address(rscratch1, 0), imm);
2681   }
2682 }
2683 
2684 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2685   assert(!src2.is_lval(), "use cmpptr");
2686   if (reachable(src2)) {
2687     cmpl(src1, as_Address(src2));
2688   } else {
2689     lea(rscratch1, src2);
2690     cmpl(src1, Address(rscratch1, 0));
2691   }
2692 }
2693 
2694 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2695   Assembler::cmpl(src1, imm);
2696 }
2697 
2698 void MacroAssembler::cmp32(Register src1, Address src2) {
2699   Assembler::cmpl(src1, src2);
2700 }
2701 
2702 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2703   ucomisd(opr1, opr2);
2704 
2705   Label L;
2706   if (unordered_is_less) {
2707     movl(dst, -1);
2708     jcc(Assembler::parity, L);
2709     jcc(Assembler::below , L);
2710     movl(dst, 0);
2711     jcc(Assembler::equal , L);
2712     increment(dst);
2713   } else { // unordered is greater
2714     movl(dst, 1);
2715     jcc(Assembler::parity, L);
2716     jcc(Assembler::above , L);
2717     movl(dst, 0);
2718     jcc(Assembler::equal , L);
2719     decrementl(dst);
2720   }
2721   bind(L);
2722 }
2723 
2724 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2725   ucomiss(opr1, opr2);
2726 
2727   Label L;
2728   if (unordered_is_less) {
2729     movl(dst, -1);
2730     jcc(Assembler::parity, L);
2731     jcc(Assembler::below , L);
2732     movl(dst, 0);
2733     jcc(Assembler::equal , L);
2734     increment(dst);
2735   } else { // unordered is greater
2736     movl(dst, 1);
2737     jcc(Assembler::parity, L);
2738     jcc(Assembler::above , L);
2739     movl(dst, 0);
2740     jcc(Assembler::equal , L);
2741     decrementl(dst);
2742   }
2743   bind(L);
2744 }
2745 
2746 
2747 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2748   if (reachable(src1)) {
2749     cmpb(as_Address(src1), imm);
2750   } else {
2751     lea(rscratch1, src1);
2752     cmpb(Address(rscratch1, 0), imm);
2753   }
2754 }
2755 
2756 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2757 #ifdef _LP64
2758   if (src2.is_lval()) {
2759     movptr(rscratch1, src2);
2760     Assembler::cmpq(src1, rscratch1);
2761   } else if (reachable(src2)) {
2762     cmpq(src1, as_Address(src2));
2763   } else {
2764     lea(rscratch1, src2);
2765     Assembler::cmpq(src1, Address(rscratch1, 0));
2766   }
2767 #else
2768   if (src2.is_lval()) {
2769     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2770   } else {
2771     cmpl(src1, as_Address(src2));
2772   }
2773 #endif // _LP64
2774 }
2775 
2776 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2777   assert(src2.is_lval(), "not a mem-mem compare");
2778 #ifdef _LP64
2779   // moves src2's literal address
2780   movptr(rscratch1, src2);
2781   Assembler::cmpq(src1, rscratch1);
2782 #else
2783   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2784 #endif // _LP64
2785 }
2786 
2787 void MacroAssembler::cmpoop(Register src1, Register src2) {
2788   cmpptr(src1, src2);
2789 }
2790 
2791 void MacroAssembler::cmpoop(Register src1, Address src2) {
2792   cmpptr(src1, src2);
2793 }
2794 
2795 #ifdef _LP64
2796 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2797   movoop(rscratch1, src2);
2798   cmpptr(src1, rscratch1);
2799 }
2800 #endif
2801 
2802 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2803   if (reachable(adr)) {
2804     if (os::is_MP())
2805       lock();
2806     cmpxchgptr(reg, as_Address(adr));
2807   } else {
2808     lea(rscratch1, adr);
2809     if (os::is_MP())
2810       lock();
2811     cmpxchgptr(reg, Address(rscratch1, 0));
2812   }
2813 }
2814 
2815 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2816   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2817 }
2818 
2819 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2820   if (reachable(src)) {
2821     Assembler::comisd(dst, as_Address(src));
2822   } else {
2823     lea(rscratch1, src);
2824     Assembler::comisd(dst, Address(rscratch1, 0));
2825   }
2826 }
2827 
2828 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2829   if (reachable(src)) {
2830     Assembler::comiss(dst, as_Address(src));
2831   } else {
2832     lea(rscratch1, src);
2833     Assembler::comiss(dst, Address(rscratch1, 0));
2834   }
2835 }
2836 
2837 
2838 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2839   Condition negated_cond = negate_condition(cond);
2840   Label L;
2841   jcc(negated_cond, L);
2842   pushf(); // Preserve flags
2843   atomic_incl(counter_addr);
2844   popf();
2845   bind(L);
2846 }
2847 
2848 int MacroAssembler::corrected_idivl(Register reg) {
2849   // Full implementation of Java idiv and irem; checks for
2850   // special case as described in JVM spec., p.243 & p.271.
2851   // The function returns the (pc) offset of the idivl
2852   // instruction - may be needed for implicit exceptions.
2853   //
2854   //         normal case                           special case
2855   //
2856   // input : rax,: dividend                         min_int
2857   //         reg: divisor   (may not be rax,/rdx)   -1
2858   //
2859   // output: rax,: quotient  (= rax, idiv reg)       min_int
2860   //         rdx: remainder (= rax, irem reg)       0
2861   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2862   const int min_int = 0x80000000;
2863   Label normal_case, special_case;
2864 
2865   // check for special case
2866   cmpl(rax, min_int);
2867   jcc(Assembler::notEqual, normal_case);
2868   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2869   cmpl(reg, -1);
2870   jcc(Assembler::equal, special_case);
2871 
2872   // handle normal case
2873   bind(normal_case);
2874   cdql();
2875   int idivl_offset = offset();
2876   idivl(reg);
2877 
2878   // normal and special case exit
2879   bind(special_case);
2880 
2881   return idivl_offset;
2882 }
2883 
2884 
2885 
2886 void MacroAssembler::decrementl(Register reg, int value) {
2887   if (value == min_jint) {subl(reg, value) ; return; }
2888   if (value <  0) { incrementl(reg, -value); return; }
2889   if (value == 0) {                        ; return; }
2890   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2891   /* else */      { subl(reg, value)       ; return; }
2892 }
2893 
2894 void MacroAssembler::decrementl(Address dst, int value) {
2895   if (value == min_jint) {subl(dst, value) ; return; }
2896   if (value <  0) { incrementl(dst, -value); return; }
2897   if (value == 0) {                        ; return; }
2898   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2899   /* else */      { subl(dst, value)       ; return; }
2900 }
2901 
2902 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2903   assert (shift_value > 0, "illegal shift value");
2904   Label _is_positive;
2905   testl (reg, reg);
2906   jcc (Assembler::positive, _is_positive);
2907   int offset = (1 << shift_value) - 1 ;
2908 
2909   if (offset == 1) {
2910     incrementl(reg);
2911   } else {
2912     addl(reg, offset);
2913   }
2914 
2915   bind (_is_positive);
2916   sarl(reg, shift_value);
2917 }
2918 
2919 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2920   if (reachable(src)) {
2921     Assembler::divsd(dst, as_Address(src));
2922   } else {
2923     lea(rscratch1, src);
2924     Assembler::divsd(dst, Address(rscratch1, 0));
2925   }
2926 }
2927 
2928 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2929   if (reachable(src)) {
2930     Assembler::divss(dst, as_Address(src));
2931   } else {
2932     lea(rscratch1, src);
2933     Assembler::divss(dst, Address(rscratch1, 0));
2934   }
2935 }
2936 
2937 // !defined(COMPILER2) is because of stupid core builds
2938 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2939 void MacroAssembler::empty_FPU_stack() {
2940   if (VM_Version::supports_mmx()) {
2941     emms();
2942   } else {
2943     for (int i = 8; i-- > 0; ) ffree(i);
2944   }
2945 }
2946 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2947 
2948 
2949 // Defines obj, preserves var_size_in_bytes
2950 void MacroAssembler::eden_allocate(Register obj,
2951                                    Register var_size_in_bytes,
2952                                    int con_size_in_bytes,
2953                                    Register t1,
2954                                    Label& slow_case) {
2955   assert(obj == rax, "obj must be in rax, for cmpxchg");
2956   assert_different_registers(obj, var_size_in_bytes, t1);
2957   if (!Universe::heap()->supports_inline_contig_alloc()) {
2958     jmp(slow_case);
2959   } else {
2960     Register end = t1;
2961     Label retry;
2962     bind(retry);
2963     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2964     movptr(obj, heap_top);
2965     if (var_size_in_bytes == noreg) {
2966       lea(end, Address(obj, con_size_in_bytes));
2967     } else {
2968       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2969     }
2970     // if end < obj then we wrapped around => object too long => slow case
2971     cmpptr(end, obj);
2972     jcc(Assembler::below, slow_case);
2973     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2974     jcc(Assembler::above, slow_case);
2975     // Compare obj with the top addr, and if still equal, store the new top addr in
2976     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2977     // it otherwise. Use lock prefix for atomicity on MPs.
2978     locked_cmpxchgptr(end, heap_top);
2979     jcc(Assembler::notEqual, retry);
2980   }
2981 }
2982 
2983 void MacroAssembler::enter() {
2984   push(rbp);
2985   mov(rbp, rsp);
2986 }
2987 
2988 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2989 void MacroAssembler::fat_nop() {
2990   if (UseAddressNop) {
2991     addr_nop_5();
2992   } else {
2993     emit_int8(0x26); // es:
2994     emit_int8(0x2e); // cs:
2995     emit_int8(0x64); // fs:
2996     emit_int8(0x65); // gs:
2997     emit_int8((unsigned char)0x90);
2998   }
2999 }
3000 
3001 void MacroAssembler::fcmp(Register tmp) {
3002   fcmp(tmp, 1, true, true);
3003 }
3004 
3005 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3006   assert(!pop_right || pop_left, "usage error");
3007   if (VM_Version::supports_cmov()) {
3008     assert(tmp == noreg, "unneeded temp");
3009     if (pop_left) {
3010       fucomip(index);
3011     } else {
3012       fucomi(index);
3013     }
3014     if (pop_right) {
3015       fpop();
3016     }
3017   } else {
3018     assert(tmp != noreg, "need temp");
3019     if (pop_left) {
3020       if (pop_right) {
3021         fcompp();
3022       } else {
3023         fcomp(index);
3024       }
3025     } else {
3026       fcom(index);
3027     }
3028     // convert FPU condition into eflags condition via rax,
3029     save_rax(tmp);
3030     fwait(); fnstsw_ax();
3031     sahf();
3032     restore_rax(tmp);
3033   }
3034   // condition codes set as follows:
3035   //
3036   // CF (corresponds to C0) if x < y
3037   // PF (corresponds to C2) if unordered
3038   // ZF (corresponds to C3) if x = y
3039 }
3040 
3041 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3042   fcmp2int(dst, unordered_is_less, 1, true, true);
3043 }
3044 
3045 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3046   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3047   Label L;
3048   if (unordered_is_less) {
3049     movl(dst, -1);
3050     jcc(Assembler::parity, L);
3051     jcc(Assembler::below , L);
3052     movl(dst, 0);
3053     jcc(Assembler::equal , L);
3054     increment(dst);
3055   } else { // unordered is greater
3056     movl(dst, 1);
3057     jcc(Assembler::parity, L);
3058     jcc(Assembler::above , L);
3059     movl(dst, 0);
3060     jcc(Assembler::equal , L);
3061     decrementl(dst);
3062   }
3063   bind(L);
3064 }
3065 
3066 void MacroAssembler::fld_d(AddressLiteral src) {
3067   fld_d(as_Address(src));
3068 }
3069 
3070 void MacroAssembler::fld_s(AddressLiteral src) {
3071   fld_s(as_Address(src));
3072 }
3073 
3074 void MacroAssembler::fld_x(AddressLiteral src) {
3075   Assembler::fld_x(as_Address(src));
3076 }
3077 
3078 void MacroAssembler::fldcw(AddressLiteral src) {
3079   Assembler::fldcw(as_Address(src));
3080 }
3081 
3082 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3083   if (reachable(src)) {
3084     Assembler::mulpd(dst, as_Address(src));
3085   } else {
3086     lea(rscratch1, src);
3087     Assembler::mulpd(dst, Address(rscratch1, 0));
3088   }
3089 }
3090 
3091 void MacroAssembler::increase_precision() {
3092   subptr(rsp, BytesPerWord);
3093   fnstcw(Address(rsp, 0));
3094   movl(rax, Address(rsp, 0));
3095   orl(rax, 0x300);
3096   push(rax);
3097   fldcw(Address(rsp, 0));
3098   pop(rax);
3099 }
3100 
3101 void MacroAssembler::restore_precision() {
3102   fldcw(Address(rsp, 0));
3103   addptr(rsp, BytesPerWord);
3104 }
3105 
3106 void MacroAssembler::fpop() {
3107   ffree();
3108   fincstp();
3109 }
3110 
3111 void MacroAssembler::load_float(Address src) {
3112   if (UseSSE >= 1) {
3113     movflt(xmm0, src);
3114   } else {
3115     LP64_ONLY(ShouldNotReachHere());
3116     NOT_LP64(fld_s(src));
3117   }
3118 }
3119 
3120 void MacroAssembler::store_float(Address dst) {
3121   if (UseSSE >= 1) {
3122     movflt(dst, xmm0);
3123   } else {
3124     LP64_ONLY(ShouldNotReachHere());
3125     NOT_LP64(fstp_s(dst));
3126   }
3127 }
3128 
3129 void MacroAssembler::load_double(Address src) {
3130   if (UseSSE >= 2) {
3131     movdbl(xmm0, src);
3132   } else {
3133     LP64_ONLY(ShouldNotReachHere());
3134     NOT_LP64(fld_d(src));
3135   }
3136 }
3137 
3138 void MacroAssembler::store_double(Address dst) {
3139   if (UseSSE >= 2) {
3140     movdbl(dst, xmm0);
3141   } else {
3142     LP64_ONLY(ShouldNotReachHere());
3143     NOT_LP64(fstp_d(dst));
3144   }
3145 }
3146 
3147 void MacroAssembler::fremr(Register tmp) {
3148   save_rax(tmp);
3149   { Label L;
3150     bind(L);
3151     fprem();
3152     fwait(); fnstsw_ax();
3153 #ifdef _LP64
3154     testl(rax, 0x400);
3155     jcc(Assembler::notEqual, L);
3156 #else
3157     sahf();
3158     jcc(Assembler::parity, L);
3159 #endif // _LP64
3160   }
3161   restore_rax(tmp);
3162   // Result is in ST0.
3163   // Note: fxch & fpop to get rid of ST1
3164   // (otherwise FPU stack could overflow eventually)
3165   fxch(1);
3166   fpop();
3167 }
3168 
3169 // dst = c = a * b + c
3170 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3171   Assembler::vfmadd231sd(c, a, b);
3172   if (dst != c) {
3173     movdbl(dst, c);
3174   }
3175 }
3176 
3177 // dst = c = a * b + c
3178 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3179   Assembler::vfmadd231ss(c, a, b);
3180   if (dst != c) {
3181     movflt(dst, c);
3182   }
3183 }
3184 
3185 // dst = c = a * b + c
3186 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3187   Assembler::vfmadd231pd(c, a, b, vector_len);
3188   if (dst != c) {
3189     vmovdqu(dst, c);
3190   }
3191 }
3192 
3193 // dst = c = a * b + c
3194 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3195   Assembler::vfmadd231ps(c, a, b, vector_len);
3196   if (dst != c) {
3197     vmovdqu(dst, c);
3198   }
3199 }
3200 
3201 // dst = c = a * b + c
3202 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3203   Assembler::vfmadd231pd(c, a, b, vector_len);
3204   if (dst != c) {
3205     vmovdqu(dst, c);
3206   }
3207 }
3208 
3209 // dst = c = a * b + c
3210 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3211   Assembler::vfmadd231ps(c, a, b, vector_len);
3212   if (dst != c) {
3213     vmovdqu(dst, c);
3214   }
3215 }
3216 
3217 void MacroAssembler::incrementl(AddressLiteral dst) {
3218   if (reachable(dst)) {
3219     incrementl(as_Address(dst));
3220   } else {
3221     lea(rscratch1, dst);
3222     incrementl(Address(rscratch1, 0));
3223   }
3224 }
3225 
3226 void MacroAssembler::incrementl(ArrayAddress dst) {
3227   incrementl(as_Address(dst));
3228 }
3229 
3230 void MacroAssembler::incrementl(Register reg, int value) {
3231   if (value == min_jint) {addl(reg, value) ; return; }
3232   if (value <  0) { decrementl(reg, -value); return; }
3233   if (value == 0) {                        ; return; }
3234   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3235   /* else */      { addl(reg, value)       ; return; }
3236 }
3237 
3238 void MacroAssembler::incrementl(Address dst, int value) {
3239   if (value == min_jint) {addl(dst, value) ; return; }
3240   if (value <  0) { decrementl(dst, -value); return; }
3241   if (value == 0) {                        ; return; }
3242   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3243   /* else */      { addl(dst, value)       ; return; }
3244 }
3245 
3246 void MacroAssembler::jump(AddressLiteral dst) {
3247   if (reachable(dst)) {
3248     jmp_literal(dst.target(), dst.rspec());
3249   } else {
3250     lea(rscratch1, dst);
3251     jmp(rscratch1);
3252   }
3253 }
3254 
3255 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3256   if (reachable(dst)) {
3257     InstructionMark im(this);
3258     relocate(dst.reloc());
3259     const int short_size = 2;
3260     const int long_size = 6;
3261     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3262     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3263       // 0111 tttn #8-bit disp
3264       emit_int8(0x70 | cc);
3265       emit_int8((offs - short_size) & 0xFF);
3266     } else {
3267       // 0000 1111 1000 tttn #32-bit disp
3268       emit_int8(0x0F);
3269       emit_int8((unsigned char)(0x80 | cc));
3270       emit_int32(offs - long_size);
3271     }
3272   } else {
3273 #ifdef ASSERT
3274     warning("reversing conditional branch");
3275 #endif /* ASSERT */
3276     Label skip;
3277     jccb(reverse[cc], skip);
3278     lea(rscratch1, dst);
3279     Assembler::jmp(rscratch1);
3280     bind(skip);
3281   }
3282 }
3283 
3284 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3285   if (reachable(src)) {
3286     Assembler::ldmxcsr(as_Address(src));
3287   } else {
3288     lea(rscratch1, src);
3289     Assembler::ldmxcsr(Address(rscratch1, 0));
3290   }
3291 }
3292 
3293 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3294   int off;
3295   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3296     off = offset();
3297     movsbl(dst, src); // movsxb
3298   } else {
3299     off = load_unsigned_byte(dst, src);
3300     shll(dst, 24);
3301     sarl(dst, 24);
3302   }
3303   return off;
3304 }
3305 
3306 // Note: load_signed_short used to be called load_signed_word.
3307 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3308 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3309 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3310 int MacroAssembler::load_signed_short(Register dst, Address src) {
3311   int off;
3312   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3313     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3314     // version but this is what 64bit has always done. This seems to imply
3315     // that users are only using 32bits worth.
3316     off = offset();
3317     movswl(dst, src); // movsxw
3318   } else {
3319     off = load_unsigned_short(dst, src);
3320     shll(dst, 16);
3321     sarl(dst, 16);
3322   }
3323   return off;
3324 }
3325 
3326 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3327   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3328   // and "3.9 Partial Register Penalties", p. 22).
3329   int off;
3330   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3331     off = offset();
3332     movzbl(dst, src); // movzxb
3333   } else {
3334     xorl(dst, dst);
3335     off = offset();
3336     movb(dst, src);
3337   }
3338   return off;
3339 }
3340 
3341 // Note: load_unsigned_short used to be called load_unsigned_word.
3342 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3343   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3344   // and "3.9 Partial Register Penalties", p. 22).
3345   int off;
3346   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3347     off = offset();
3348     movzwl(dst, src); // movzxw
3349   } else {
3350     xorl(dst, dst);
3351     off = offset();
3352     movw(dst, src);
3353   }
3354   return off;
3355 }
3356 
3357 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3358   switch (size_in_bytes) {
3359 #ifndef _LP64
3360   case  8:
3361     assert(dst2 != noreg, "second dest register required");
3362     movl(dst,  src);
3363     movl(dst2, src.plus_disp(BytesPerInt));
3364     break;
3365 #else
3366   case  8:  movq(dst, src); break;
3367 #endif
3368   case  4:  movl(dst, src); break;
3369   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3370   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3371   default:  ShouldNotReachHere();
3372   }
3373 }
3374 
3375 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3376   switch (size_in_bytes) {
3377 #ifndef _LP64
3378   case  8:
3379     assert(src2 != noreg, "second source register required");
3380     movl(dst,                        src);
3381     movl(dst.plus_disp(BytesPerInt), src2);
3382     break;
3383 #else
3384   case  8:  movq(dst, src); break;
3385 #endif
3386   case  4:  movl(dst, src); break;
3387   case  2:  movw(dst, src); break;
3388   case  1:  movb(dst, src); break;
3389   default:  ShouldNotReachHere();
3390   }
3391 }
3392 
3393 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3394   if (reachable(dst)) {
3395     movl(as_Address(dst), src);
3396   } else {
3397     lea(rscratch1, dst);
3398     movl(Address(rscratch1, 0), src);
3399   }
3400 }
3401 
3402 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3403   if (reachable(src)) {
3404     movl(dst, as_Address(src));
3405   } else {
3406     lea(rscratch1, src);
3407     movl(dst, Address(rscratch1, 0));
3408   }
3409 }
3410 
3411 // C++ bool manipulation
3412 
3413 void MacroAssembler::movbool(Register dst, Address src) {
3414   if(sizeof(bool) == 1)
3415     movb(dst, src);
3416   else if(sizeof(bool) == 2)
3417     movw(dst, src);
3418   else if(sizeof(bool) == 4)
3419     movl(dst, src);
3420   else
3421     // unsupported
3422     ShouldNotReachHere();
3423 }
3424 
3425 void MacroAssembler::movbool(Address dst, bool boolconst) {
3426   if(sizeof(bool) == 1)
3427     movb(dst, (int) boolconst);
3428   else if(sizeof(bool) == 2)
3429     movw(dst, (int) boolconst);
3430   else if(sizeof(bool) == 4)
3431     movl(dst, (int) boolconst);
3432   else
3433     // unsupported
3434     ShouldNotReachHere();
3435 }
3436 
3437 void MacroAssembler::movbool(Address dst, Register src) {
3438   if(sizeof(bool) == 1)
3439     movb(dst, src);
3440   else if(sizeof(bool) == 2)
3441     movw(dst, src);
3442   else if(sizeof(bool) == 4)
3443     movl(dst, src);
3444   else
3445     // unsupported
3446     ShouldNotReachHere();
3447 }
3448 
3449 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3450   movb(as_Address(dst), src);
3451 }
3452 
3453 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3454   if (reachable(src)) {
3455     movdl(dst, as_Address(src));
3456   } else {
3457     lea(rscratch1, src);
3458     movdl(dst, Address(rscratch1, 0));
3459   }
3460 }
3461 
3462 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3463   if (reachable(src)) {
3464     movq(dst, as_Address(src));
3465   } else {
3466     lea(rscratch1, src);
3467     movq(dst, Address(rscratch1, 0));
3468   }
3469 }
3470 
3471 void MacroAssembler::setvectmask(Register dst, Register src) {
3472   Assembler::movl(dst, 1);
3473   Assembler::shlxl(dst, dst, src);
3474   Assembler::decl(dst);
3475   Assembler::kmovdl(k1, dst);
3476   Assembler::movl(dst, src);
3477 }
3478 
3479 void MacroAssembler::restorevectmask() {
3480   Assembler::knotwl(k1, k0);
3481 }
3482 
3483 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3484   if (reachable(src)) {
3485     if (UseXmmLoadAndClearUpper) {
3486       movsd (dst, as_Address(src));
3487     } else {
3488       movlpd(dst, as_Address(src));
3489     }
3490   } else {
3491     lea(rscratch1, src);
3492     if (UseXmmLoadAndClearUpper) {
3493       movsd (dst, Address(rscratch1, 0));
3494     } else {
3495       movlpd(dst, Address(rscratch1, 0));
3496     }
3497   }
3498 }
3499 
3500 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3501   if (reachable(src)) {
3502     movss(dst, as_Address(src));
3503   } else {
3504     lea(rscratch1, src);
3505     movss(dst, Address(rscratch1, 0));
3506   }
3507 }
3508 
3509 void MacroAssembler::movptr(Register dst, Register src) {
3510   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3511 }
3512 
3513 void MacroAssembler::movptr(Register dst, Address src) {
3514   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3515 }
3516 
3517 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3518 void MacroAssembler::movptr(Register dst, intptr_t src) {
3519   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3520 }
3521 
3522 void MacroAssembler::movptr(Address dst, Register src) {
3523   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3524 }
3525 
3526 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3527   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3528     Assembler::vextractf32x4(dst, src, 0);
3529   } else {
3530     Assembler::movdqu(dst, src);
3531   }
3532 }
3533 
3534 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3535   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3536     Assembler::vinsertf32x4(dst, dst, src, 0);
3537   } else {
3538     Assembler::movdqu(dst, src);
3539   }
3540 }
3541 
3542 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3543   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3544     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3545   } else {
3546     Assembler::movdqu(dst, src);
3547   }
3548 }
3549 
3550 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3551   if (reachable(src)) {
3552     movdqu(dst, as_Address(src));
3553   } else {
3554     lea(scratchReg, src);
3555     movdqu(dst, Address(scratchReg, 0));
3556   }
3557 }
3558 
3559 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3560   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3561     vextractf64x4_low(dst, src);
3562   } else {
3563     Assembler::vmovdqu(dst, src);
3564   }
3565 }
3566 
3567 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3568   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3569     vinsertf64x4_low(dst, src);
3570   } else {
3571     Assembler::vmovdqu(dst, src);
3572   }
3573 }
3574 
3575 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3576   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3577     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3578   }
3579   else {
3580     Assembler::vmovdqu(dst, src);
3581   }
3582 }
3583 
3584 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3585   if (reachable(src)) {
3586     vmovdqu(dst, as_Address(src));
3587   }
3588   else {
3589     lea(rscratch1, src);
3590     vmovdqu(dst, Address(rscratch1, 0));
3591   }
3592 }
3593 
3594 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3595   if (reachable(src)) {
3596     Assembler::movdqa(dst, as_Address(src));
3597   } else {
3598     lea(rscratch1, src);
3599     Assembler::movdqa(dst, Address(rscratch1, 0));
3600   }
3601 }
3602 
3603 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3604   if (reachable(src)) {
3605     Assembler::movsd(dst, as_Address(src));
3606   } else {
3607     lea(rscratch1, src);
3608     Assembler::movsd(dst, Address(rscratch1, 0));
3609   }
3610 }
3611 
3612 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3613   if (reachable(src)) {
3614     Assembler::movss(dst, as_Address(src));
3615   } else {
3616     lea(rscratch1, src);
3617     Assembler::movss(dst, Address(rscratch1, 0));
3618   }
3619 }
3620 
3621 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3622   if (reachable(src)) {
3623     Assembler::mulsd(dst, as_Address(src));
3624   } else {
3625     lea(rscratch1, src);
3626     Assembler::mulsd(dst, Address(rscratch1, 0));
3627   }
3628 }
3629 
3630 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3631   if (reachable(src)) {
3632     Assembler::mulss(dst, as_Address(src));
3633   } else {
3634     lea(rscratch1, src);
3635     Assembler::mulss(dst, Address(rscratch1, 0));
3636   }
3637 }
3638 
3639 void MacroAssembler::null_check(Register reg, int offset) {
3640   if (needs_explicit_null_check(offset)) {
3641     // provoke OS NULL exception if reg = NULL by
3642     // accessing M[reg] w/o changing any (non-CC) registers
3643     // NOTE: cmpl is plenty here to provoke a segv
3644     cmpptr(rax, Address(reg, 0));
3645     // Note: should probably use testl(rax, Address(reg, 0));
3646     //       may be shorter code (however, this version of
3647     //       testl needs to be implemented first)
3648   } else {
3649     // nothing to do, (later) access of M[reg + offset]
3650     // will provoke OS NULL exception if reg = NULL
3651   }
3652 }
3653 
3654 void MacroAssembler::os_breakpoint() {
3655   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3656   // (e.g., MSVC can't call ps() otherwise)
3657   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3658 }
3659 
3660 void MacroAssembler::unimplemented(const char* what) {
3661   const char* buf = NULL;
3662   {
3663     ResourceMark rm;
3664     stringStream ss;
3665     ss.print("unimplemented: %s", what);
3666     buf = code_string(ss.as_string());
3667   }
3668   stop(buf);
3669 }
3670 
3671 #ifdef _LP64
3672 #define XSTATE_BV 0x200
3673 #endif
3674 
3675 void MacroAssembler::pop_CPU_state() {
3676   pop_FPU_state();
3677   pop_IU_state();
3678 }
3679 
3680 void MacroAssembler::pop_FPU_state() {
3681 #ifndef _LP64
3682   frstor(Address(rsp, 0));
3683 #else
3684   fxrstor(Address(rsp, 0));
3685 #endif
3686   addptr(rsp, FPUStateSizeInWords * wordSize);
3687 }
3688 
3689 void MacroAssembler::pop_IU_state() {
3690   popa();
3691   LP64_ONLY(addq(rsp, 8));
3692   popf();
3693 }
3694 
3695 // Save Integer and Float state
3696 // Warning: Stack must be 16 byte aligned (64bit)
3697 void MacroAssembler::push_CPU_state() {
3698   push_IU_state();
3699   push_FPU_state();
3700 }
3701 
3702 void MacroAssembler::push_FPU_state() {
3703   subptr(rsp, FPUStateSizeInWords * wordSize);
3704 #ifndef _LP64
3705   fnsave(Address(rsp, 0));
3706   fwait();
3707 #else
3708   fxsave(Address(rsp, 0));
3709 #endif // LP64
3710 }
3711 
3712 void MacroAssembler::push_IU_state() {
3713   // Push flags first because pusha kills them
3714   pushf();
3715   // Make sure rsp stays 16-byte aligned
3716   LP64_ONLY(subq(rsp, 8));
3717   pusha();
3718 }
3719 
3720 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3721   if (!java_thread->is_valid()) {
3722     java_thread = rdi;
3723     get_thread(java_thread);
3724   }
3725   // we must set sp to zero to clear frame
3726   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3727   if (clear_fp) {
3728     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3729   }
3730 
3731   // Always clear the pc because it could have been set by make_walkable()
3732   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3733 
3734   vzeroupper();
3735 }
3736 
3737 void MacroAssembler::restore_rax(Register tmp) {
3738   if (tmp == noreg) pop(rax);
3739   else if (tmp != rax) mov(rax, tmp);
3740 }
3741 
3742 void MacroAssembler::round_to(Register reg, int modulus) {
3743   addptr(reg, modulus - 1);
3744   andptr(reg, -modulus);
3745 }
3746 
3747 void MacroAssembler::save_rax(Register tmp) {
3748   if (tmp == noreg) push(rax);
3749   else if (tmp != rax) mov(tmp, rax);
3750 }
3751 
3752 // Write serialization page so VM thread can do a pseudo remote membar.
3753 // We use the current thread pointer to calculate a thread specific
3754 // offset to write to within the page. This minimizes bus traffic
3755 // due to cache line collision.
3756 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3757   movl(tmp, thread);
3758   shrl(tmp, os::get_serialize_page_shift_count());
3759   andl(tmp, (os::vm_page_size() - sizeof(int)));
3760 
3761   Address index(noreg, tmp, Address::times_1);
3762   ExternalAddress page(os::get_memory_serialize_page());
3763 
3764   // Size of store must match masking code above
3765   movl(as_Address(ArrayAddress(page, index)), tmp);
3766 }
3767 
3768 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3769   if (SafepointMechanism::uses_thread_local_poll()) {
3770 #ifdef _LP64
3771     assert(thread_reg == r15_thread, "should be");
3772 #else
3773     if (thread_reg == noreg) {
3774       thread_reg = temp_reg;
3775       get_thread(thread_reg);
3776     }
3777 #endif
3778     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3779     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3780   } else {
3781     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3782         SafepointSynchronize::_not_synchronized);
3783     jcc(Assembler::notEqual, slow_path);
3784   }
3785 }
3786 
3787 // Calls to C land
3788 //
3789 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3790 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3791 // has to be reset to 0. This is required to allow proper stack traversal.
3792 void MacroAssembler::set_last_Java_frame(Register java_thread,
3793                                          Register last_java_sp,
3794                                          Register last_java_fp,
3795                                          address  last_java_pc) {
3796   vzeroupper();
3797   // determine java_thread register
3798   if (!java_thread->is_valid()) {
3799     java_thread = rdi;
3800     get_thread(java_thread);
3801   }
3802   // determine last_java_sp register
3803   if (!last_java_sp->is_valid()) {
3804     last_java_sp = rsp;
3805   }
3806 
3807   // last_java_fp is optional
3808 
3809   if (last_java_fp->is_valid()) {
3810     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3811   }
3812 
3813   // last_java_pc is optional
3814 
3815   if (last_java_pc != NULL) {
3816     lea(Address(java_thread,
3817                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3818         InternalAddress(last_java_pc));
3819 
3820   }
3821   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3822 }
3823 
3824 void MacroAssembler::shlptr(Register dst, int imm8) {
3825   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3826 }
3827 
3828 void MacroAssembler::shrptr(Register dst, int imm8) {
3829   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3830 }
3831 
3832 void MacroAssembler::sign_extend_byte(Register reg) {
3833   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3834     movsbl(reg, reg); // movsxb
3835   } else {
3836     shll(reg, 24);
3837     sarl(reg, 24);
3838   }
3839 }
3840 
3841 void MacroAssembler::sign_extend_short(Register reg) {
3842   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3843     movswl(reg, reg); // movsxw
3844   } else {
3845     shll(reg, 16);
3846     sarl(reg, 16);
3847   }
3848 }
3849 
3850 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3851   assert(reachable(src), "Address should be reachable");
3852   testl(dst, as_Address(src));
3853 }
3854 
3855 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3856   int dst_enc = dst->encoding();
3857   int src_enc = src->encoding();
3858   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3859     Assembler::pcmpeqb(dst, src);
3860   } else if ((dst_enc < 16) && (src_enc < 16)) {
3861     Assembler::pcmpeqb(dst, src);
3862   } else if (src_enc < 16) {
3863     subptr(rsp, 64);
3864     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3865     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3866     Assembler::pcmpeqb(xmm0, src);
3867     movdqu(dst, xmm0);
3868     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3869     addptr(rsp, 64);
3870   } else if (dst_enc < 16) {
3871     subptr(rsp, 64);
3872     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3873     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3874     Assembler::pcmpeqb(dst, xmm0);
3875     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3876     addptr(rsp, 64);
3877   } else {
3878     subptr(rsp, 64);
3879     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3880     subptr(rsp, 64);
3881     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3882     movdqu(xmm0, src);
3883     movdqu(xmm1, dst);
3884     Assembler::pcmpeqb(xmm1, xmm0);
3885     movdqu(dst, xmm1);
3886     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3887     addptr(rsp, 64);
3888     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3889     addptr(rsp, 64);
3890   }
3891 }
3892 
3893 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3894   int dst_enc = dst->encoding();
3895   int src_enc = src->encoding();
3896   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3897     Assembler::pcmpeqw(dst, src);
3898   } else if ((dst_enc < 16) && (src_enc < 16)) {
3899     Assembler::pcmpeqw(dst, src);
3900   } else if (src_enc < 16) {
3901     subptr(rsp, 64);
3902     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3903     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3904     Assembler::pcmpeqw(xmm0, src);
3905     movdqu(dst, xmm0);
3906     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3907     addptr(rsp, 64);
3908   } else if (dst_enc < 16) {
3909     subptr(rsp, 64);
3910     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3911     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3912     Assembler::pcmpeqw(dst, xmm0);
3913     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3914     addptr(rsp, 64);
3915   } else {
3916     subptr(rsp, 64);
3917     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3918     subptr(rsp, 64);
3919     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3920     movdqu(xmm0, src);
3921     movdqu(xmm1, dst);
3922     Assembler::pcmpeqw(xmm1, xmm0);
3923     movdqu(dst, xmm1);
3924     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3925     addptr(rsp, 64);
3926     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3927     addptr(rsp, 64);
3928   }
3929 }
3930 
3931 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3932   int dst_enc = dst->encoding();
3933   if (dst_enc < 16) {
3934     Assembler::pcmpestri(dst, src, imm8);
3935   } else {
3936     subptr(rsp, 64);
3937     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3938     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3939     Assembler::pcmpestri(xmm0, src, imm8);
3940     movdqu(dst, xmm0);
3941     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3942     addptr(rsp, 64);
3943   }
3944 }
3945 
3946 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3947   int dst_enc = dst->encoding();
3948   int src_enc = src->encoding();
3949   if ((dst_enc < 16) && (src_enc < 16)) {
3950     Assembler::pcmpestri(dst, src, imm8);
3951   } else if (src_enc < 16) {
3952     subptr(rsp, 64);
3953     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3954     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3955     Assembler::pcmpestri(xmm0, src, imm8);
3956     movdqu(dst, xmm0);
3957     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3958     addptr(rsp, 64);
3959   } else if (dst_enc < 16) {
3960     subptr(rsp, 64);
3961     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3962     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3963     Assembler::pcmpestri(dst, xmm0, imm8);
3964     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3965     addptr(rsp, 64);
3966   } else {
3967     subptr(rsp, 64);
3968     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3969     subptr(rsp, 64);
3970     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3971     movdqu(xmm0, src);
3972     movdqu(xmm1, dst);
3973     Assembler::pcmpestri(xmm1, xmm0, imm8);
3974     movdqu(dst, xmm1);
3975     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3976     addptr(rsp, 64);
3977     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3978     addptr(rsp, 64);
3979   }
3980 }
3981 
3982 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3983   int dst_enc = dst->encoding();
3984   int src_enc = src->encoding();
3985   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3986     Assembler::pmovzxbw(dst, src);
3987   } else if ((dst_enc < 16) && (src_enc < 16)) {
3988     Assembler::pmovzxbw(dst, src);
3989   } else if (src_enc < 16) {
3990     subptr(rsp, 64);
3991     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3992     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3993     Assembler::pmovzxbw(xmm0, src);
3994     movdqu(dst, xmm0);
3995     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3996     addptr(rsp, 64);
3997   } else if (dst_enc < 16) {
3998     subptr(rsp, 64);
3999     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4000     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4001     Assembler::pmovzxbw(dst, xmm0);
4002     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4003     addptr(rsp, 64);
4004   } else {
4005     subptr(rsp, 64);
4006     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4007     subptr(rsp, 64);
4008     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4009     movdqu(xmm0, src);
4010     movdqu(xmm1, dst);
4011     Assembler::pmovzxbw(xmm1, xmm0);
4012     movdqu(dst, xmm1);
4013     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4014     addptr(rsp, 64);
4015     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4016     addptr(rsp, 64);
4017   }
4018 }
4019 
4020 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4021   int dst_enc = dst->encoding();
4022   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4023     Assembler::pmovzxbw(dst, src);
4024   } else if (dst_enc < 16) {
4025     Assembler::pmovzxbw(dst, src);
4026   } else {
4027     subptr(rsp, 64);
4028     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4029     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4030     Assembler::pmovzxbw(xmm0, src);
4031     movdqu(dst, xmm0);
4032     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4033     addptr(rsp, 64);
4034   }
4035 }
4036 
4037 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4038   int src_enc = src->encoding();
4039   if (src_enc < 16) {
4040     Assembler::pmovmskb(dst, src);
4041   } else {
4042     subptr(rsp, 64);
4043     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4044     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4045     Assembler::pmovmskb(dst, xmm0);
4046     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4047     addptr(rsp, 64);
4048   }
4049 }
4050 
4051 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4052   int dst_enc = dst->encoding();
4053   int src_enc = src->encoding();
4054   if ((dst_enc < 16) && (src_enc < 16)) {
4055     Assembler::ptest(dst, src);
4056   } else if (src_enc < 16) {
4057     subptr(rsp, 64);
4058     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4059     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4060     Assembler::ptest(xmm0, src);
4061     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4062     addptr(rsp, 64);
4063   } else if (dst_enc < 16) {
4064     subptr(rsp, 64);
4065     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4066     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4067     Assembler::ptest(dst, xmm0);
4068     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4069     addptr(rsp, 64);
4070   } else {
4071     subptr(rsp, 64);
4072     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4073     subptr(rsp, 64);
4074     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4075     movdqu(xmm0, src);
4076     movdqu(xmm1, dst);
4077     Assembler::ptest(xmm1, xmm0);
4078     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4079     addptr(rsp, 64);
4080     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4081     addptr(rsp, 64);
4082   }
4083 }
4084 
4085 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4086   if (reachable(src)) {
4087     Assembler::sqrtsd(dst, as_Address(src));
4088   } else {
4089     lea(rscratch1, src);
4090     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4091   }
4092 }
4093 
4094 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4095   if (reachable(src)) {
4096     Assembler::sqrtss(dst, as_Address(src));
4097   } else {
4098     lea(rscratch1, src);
4099     Assembler::sqrtss(dst, Address(rscratch1, 0));
4100   }
4101 }
4102 
4103 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4104   if (reachable(src)) {
4105     Assembler::subsd(dst, as_Address(src));
4106   } else {
4107     lea(rscratch1, src);
4108     Assembler::subsd(dst, Address(rscratch1, 0));
4109   }
4110 }
4111 
4112 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4113   if (reachable(src)) {
4114     Assembler::subss(dst, as_Address(src));
4115   } else {
4116     lea(rscratch1, src);
4117     Assembler::subss(dst, Address(rscratch1, 0));
4118   }
4119 }
4120 
4121 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4122   if (reachable(src)) {
4123     Assembler::ucomisd(dst, as_Address(src));
4124   } else {
4125     lea(rscratch1, src);
4126     Assembler::ucomisd(dst, Address(rscratch1, 0));
4127   }
4128 }
4129 
4130 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4131   if (reachable(src)) {
4132     Assembler::ucomiss(dst, as_Address(src));
4133   } else {
4134     lea(rscratch1, src);
4135     Assembler::ucomiss(dst, Address(rscratch1, 0));
4136   }
4137 }
4138 
4139 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4140   // Used in sign-bit flipping with aligned address.
4141   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4142   if (reachable(src)) {
4143     Assembler::xorpd(dst, as_Address(src));
4144   } else {
4145     lea(rscratch1, src);
4146     Assembler::xorpd(dst, Address(rscratch1, 0));
4147   }
4148 }
4149 
4150 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4151   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4152     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4153   }
4154   else {
4155     Assembler::xorpd(dst, src);
4156   }
4157 }
4158 
4159 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4160   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4161     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4162   } else {
4163     Assembler::xorps(dst, src);
4164   }
4165 }
4166 
4167 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4168   // Used in sign-bit flipping with aligned address.
4169   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4170   if (reachable(src)) {
4171     Assembler::xorps(dst, as_Address(src));
4172   } else {
4173     lea(rscratch1, src);
4174     Assembler::xorps(dst, Address(rscratch1, 0));
4175   }
4176 }
4177 
4178 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4179   // Used in sign-bit flipping with aligned address.
4180   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4181   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4182   if (reachable(src)) {
4183     Assembler::pshufb(dst, as_Address(src));
4184   } else {
4185     lea(rscratch1, src);
4186     Assembler::pshufb(dst, Address(rscratch1, 0));
4187   }
4188 }
4189 
4190 // AVX 3-operands instructions
4191 
4192 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4193   if (reachable(src)) {
4194     vaddsd(dst, nds, as_Address(src));
4195   } else {
4196     lea(rscratch1, src);
4197     vaddsd(dst, nds, Address(rscratch1, 0));
4198   }
4199 }
4200 
4201 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4202   if (reachable(src)) {
4203     vaddss(dst, nds, as_Address(src));
4204   } else {
4205     lea(rscratch1, src);
4206     vaddss(dst, nds, Address(rscratch1, 0));
4207   }
4208 }
4209 
4210 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4211   int dst_enc = dst->encoding();
4212   int nds_enc = nds->encoding();
4213   int src_enc = src->encoding();
4214   if ((dst_enc < 16) && (nds_enc < 16)) {
4215     vandps(dst, nds, negate_field, vector_len);
4216   } else if ((src_enc < 16) && (dst_enc < 16)) {
4217     evmovdqul(src, nds, Assembler::AVX_512bit);
4218     vandps(dst, src, negate_field, vector_len);
4219   } else if (src_enc < 16) {
4220     evmovdqul(src, nds, Assembler::AVX_512bit);
4221     vandps(src, src, negate_field, vector_len);
4222     evmovdqul(dst, src, Assembler::AVX_512bit);
4223   } else if (dst_enc < 16) {
4224     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4225     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4226     vandps(dst, xmm0, negate_field, vector_len);
4227     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4228   } else {
4229     if (src_enc != dst_enc) {
4230       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4231       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4232       vandps(xmm0, xmm0, negate_field, vector_len);
4233       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4234       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4235     } else {
4236       subptr(rsp, 64);
4237       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4238       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4239       vandps(xmm0, xmm0, negate_field, vector_len);
4240       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4241       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4242       addptr(rsp, 64);
4243     }
4244   }
4245 }
4246 
4247 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4248   int dst_enc = dst->encoding();
4249   int nds_enc = nds->encoding();
4250   int src_enc = src->encoding();
4251   if ((dst_enc < 16) && (nds_enc < 16)) {
4252     vandpd(dst, nds, negate_field, vector_len);
4253   } else if ((src_enc < 16) && (dst_enc < 16)) {
4254     evmovdqul(src, nds, Assembler::AVX_512bit);
4255     vandpd(dst, src, negate_field, vector_len);
4256   } else if (src_enc < 16) {
4257     evmovdqul(src, nds, Assembler::AVX_512bit);
4258     vandpd(src, src, negate_field, vector_len);
4259     evmovdqul(dst, src, Assembler::AVX_512bit);
4260   } else if (dst_enc < 16) {
4261     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4262     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4263     vandpd(dst, xmm0, negate_field, vector_len);
4264     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4265   } else {
4266     if (src_enc != dst_enc) {
4267       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4268       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4269       vandpd(xmm0, xmm0, negate_field, vector_len);
4270       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4271       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4272     } else {
4273       subptr(rsp, 64);
4274       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4275       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4276       vandpd(xmm0, xmm0, negate_field, vector_len);
4277       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4278       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4279       addptr(rsp, 64);
4280     }
4281   }
4282 }
4283 
4284 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4285   int dst_enc = dst->encoding();
4286   int nds_enc = nds->encoding();
4287   int src_enc = src->encoding();
4288   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4289     Assembler::vpaddb(dst, nds, src, vector_len);
4290   } else if ((dst_enc < 16) && (src_enc < 16)) {
4291     Assembler::vpaddb(dst, dst, src, vector_len);
4292   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4293     // use nds as scratch for src
4294     evmovdqul(nds, src, Assembler::AVX_512bit);
4295     Assembler::vpaddb(dst, dst, nds, vector_len);
4296   } else if ((src_enc < 16) && (nds_enc < 16)) {
4297     // use nds as scratch for dst
4298     evmovdqul(nds, dst, Assembler::AVX_512bit);
4299     Assembler::vpaddb(nds, nds, src, vector_len);
4300     evmovdqul(dst, nds, Assembler::AVX_512bit);
4301   } else if (dst_enc < 16) {
4302     // use nds as scatch for xmm0 to hold src
4303     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4304     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4305     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4306     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4307   } else {
4308     // worse case scenario, all regs are in the upper bank
4309     subptr(rsp, 64);
4310     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4311     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4312     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4313     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4314     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4315     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4316     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4317     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4318     addptr(rsp, 64);
4319   }
4320 }
4321 
4322 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4323   int dst_enc = dst->encoding();
4324   int nds_enc = nds->encoding();
4325   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4326     Assembler::vpaddb(dst, nds, src, vector_len);
4327   } else if (dst_enc < 16) {
4328     Assembler::vpaddb(dst, dst, src, vector_len);
4329   } else if (nds_enc < 16) {
4330     // implies dst_enc in upper bank with src as scratch
4331     evmovdqul(nds, dst, Assembler::AVX_512bit);
4332     Assembler::vpaddb(nds, nds, src, vector_len);
4333     evmovdqul(dst, nds, Assembler::AVX_512bit);
4334   } else {
4335     // worse case scenario, all regs in upper bank
4336     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4337     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4338     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4339     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4340   }
4341 }
4342 
4343 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4344   int dst_enc = dst->encoding();
4345   int nds_enc = nds->encoding();
4346   int src_enc = src->encoding();
4347   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4348     Assembler::vpaddw(dst, nds, src, vector_len);
4349   } else if ((dst_enc < 16) && (src_enc < 16)) {
4350     Assembler::vpaddw(dst, dst, src, vector_len);
4351   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4352     // use nds as scratch for src
4353     evmovdqul(nds, src, Assembler::AVX_512bit);
4354     Assembler::vpaddw(dst, dst, nds, vector_len);
4355   } else if ((src_enc < 16) && (nds_enc < 16)) {
4356     // use nds as scratch for dst
4357     evmovdqul(nds, dst, Assembler::AVX_512bit);
4358     Assembler::vpaddw(nds, nds, src, vector_len);
4359     evmovdqul(dst, nds, Assembler::AVX_512bit);
4360   } else if (dst_enc < 16) {
4361     // use nds as scatch for xmm0 to hold src
4362     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4363     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4364     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4365     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4366   } else {
4367     // worse case scenario, all regs are in the upper bank
4368     subptr(rsp, 64);
4369     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4370     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4371     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4372     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4373     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4374     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4375     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4376     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4377     addptr(rsp, 64);
4378   }
4379 }
4380 
4381 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4382   int dst_enc = dst->encoding();
4383   int nds_enc = nds->encoding();
4384   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4385     Assembler::vpaddw(dst, nds, src, vector_len);
4386   } else if (dst_enc < 16) {
4387     Assembler::vpaddw(dst, dst, src, vector_len);
4388   } else if (nds_enc < 16) {
4389     // implies dst_enc in upper bank with src as scratch
4390     evmovdqul(nds, dst, Assembler::AVX_512bit);
4391     Assembler::vpaddw(nds, nds, src, vector_len);
4392     evmovdqul(dst, nds, Assembler::AVX_512bit);
4393   } else {
4394     // worse case scenario, all regs in upper bank
4395     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4396     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4397     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4398     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4399   }
4400 }
4401 
4402 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4403   if (reachable(src)) {
4404     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4405   } else {
4406     lea(rscratch1, src);
4407     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4408   }
4409 }
4410 
4411 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4412   int dst_enc = dst->encoding();
4413   int src_enc = src->encoding();
4414   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4415     Assembler::vpbroadcastw(dst, src);
4416   } else if ((dst_enc < 16) && (src_enc < 16)) {
4417     Assembler::vpbroadcastw(dst, src);
4418   } else if (src_enc < 16) {
4419     subptr(rsp, 64);
4420     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4421     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4422     Assembler::vpbroadcastw(xmm0, src);
4423     movdqu(dst, xmm0);
4424     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4425     addptr(rsp, 64);
4426   } else if (dst_enc < 16) {
4427     subptr(rsp, 64);
4428     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4429     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4430     Assembler::vpbroadcastw(dst, xmm0);
4431     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4432     addptr(rsp, 64);
4433   } else {
4434     subptr(rsp, 64);
4435     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4436     subptr(rsp, 64);
4437     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4438     movdqu(xmm0, src);
4439     movdqu(xmm1, dst);
4440     Assembler::vpbroadcastw(xmm1, xmm0);
4441     movdqu(dst, xmm1);
4442     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4443     addptr(rsp, 64);
4444     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4445     addptr(rsp, 64);
4446   }
4447 }
4448 
4449 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4450   int dst_enc = dst->encoding();
4451   int nds_enc = nds->encoding();
4452   int src_enc = src->encoding();
4453   assert(dst_enc == nds_enc, "");
4454   if ((dst_enc < 16) && (src_enc < 16)) {
4455     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4456   } else if (src_enc < 16) {
4457     subptr(rsp, 64);
4458     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4459     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4460     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4461     movdqu(dst, xmm0);
4462     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4463     addptr(rsp, 64);
4464   } else if (dst_enc < 16) {
4465     subptr(rsp, 64);
4466     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4467     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4468     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4469     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4470     addptr(rsp, 64);
4471   } else {
4472     subptr(rsp, 64);
4473     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4474     subptr(rsp, 64);
4475     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4476     movdqu(xmm0, src);
4477     movdqu(xmm1, dst);
4478     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4479     movdqu(dst, xmm1);
4480     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4481     addptr(rsp, 64);
4482     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4483     addptr(rsp, 64);
4484   }
4485 }
4486 
4487 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4488   int dst_enc = dst->encoding();
4489   int nds_enc = nds->encoding();
4490   int src_enc = src->encoding();
4491   assert(dst_enc == nds_enc, "");
4492   if ((dst_enc < 16) && (src_enc < 16)) {
4493     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4494   } else if (src_enc < 16) {
4495     subptr(rsp, 64);
4496     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4497     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4498     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4499     movdqu(dst, xmm0);
4500     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4501     addptr(rsp, 64);
4502   } else if (dst_enc < 16) {
4503     subptr(rsp, 64);
4504     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4505     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4506     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4507     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4508     addptr(rsp, 64);
4509   } else {
4510     subptr(rsp, 64);
4511     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4512     subptr(rsp, 64);
4513     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4514     movdqu(xmm0, src);
4515     movdqu(xmm1, dst);
4516     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4517     movdqu(dst, xmm1);
4518     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4519     addptr(rsp, 64);
4520     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4521     addptr(rsp, 64);
4522   }
4523 }
4524 
4525 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4526   int dst_enc = dst->encoding();
4527   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4528     Assembler::vpmovzxbw(dst, src, vector_len);
4529   } else if (dst_enc < 16) {
4530     Assembler::vpmovzxbw(dst, src, vector_len);
4531   } else {
4532     subptr(rsp, 64);
4533     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4534     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4535     Assembler::vpmovzxbw(xmm0, src, vector_len);
4536     movdqu(dst, xmm0);
4537     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4538     addptr(rsp, 64);
4539   }
4540 }
4541 
4542 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4543   int src_enc = src->encoding();
4544   if (src_enc < 16) {
4545     Assembler::vpmovmskb(dst, src);
4546   } else {
4547     subptr(rsp, 64);
4548     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4549     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4550     Assembler::vpmovmskb(dst, xmm0);
4551     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4552     addptr(rsp, 64);
4553   }
4554 }
4555 
4556 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4557   int dst_enc = dst->encoding();
4558   int nds_enc = nds->encoding();
4559   int src_enc = src->encoding();
4560   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4561     Assembler::vpmullw(dst, nds, src, vector_len);
4562   } else if ((dst_enc < 16) && (src_enc < 16)) {
4563     Assembler::vpmullw(dst, dst, src, vector_len);
4564   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4565     // use nds as scratch for src
4566     evmovdqul(nds, src, Assembler::AVX_512bit);
4567     Assembler::vpmullw(dst, dst, nds, vector_len);
4568   } else if ((src_enc < 16) && (nds_enc < 16)) {
4569     // use nds as scratch for dst
4570     evmovdqul(nds, dst, Assembler::AVX_512bit);
4571     Assembler::vpmullw(nds, nds, src, vector_len);
4572     evmovdqul(dst, nds, Assembler::AVX_512bit);
4573   } else if (dst_enc < 16) {
4574     // use nds as scatch for xmm0 to hold src
4575     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4576     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4577     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4578     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4579   } else {
4580     // worse case scenario, all regs are in the upper bank
4581     subptr(rsp, 64);
4582     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4583     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4584     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4585     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4586     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4587     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4588     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4589     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4590     addptr(rsp, 64);
4591   }
4592 }
4593 
4594 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4595   int dst_enc = dst->encoding();
4596   int nds_enc = nds->encoding();
4597   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4598     Assembler::vpmullw(dst, nds, src, vector_len);
4599   } else if (dst_enc < 16) {
4600     Assembler::vpmullw(dst, dst, src, vector_len);
4601   } else if (nds_enc < 16) {
4602     // implies dst_enc in upper bank with src as scratch
4603     evmovdqul(nds, dst, Assembler::AVX_512bit);
4604     Assembler::vpmullw(nds, nds, src, vector_len);
4605     evmovdqul(dst, nds, Assembler::AVX_512bit);
4606   } else {
4607     // worse case scenario, all regs in upper bank
4608     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4609     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4610     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4611     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4612   }
4613 }
4614 
4615 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4616   int dst_enc = dst->encoding();
4617   int nds_enc = nds->encoding();
4618   int src_enc = src->encoding();
4619   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4620     Assembler::vpsubb(dst, nds, src, vector_len);
4621   } else if ((dst_enc < 16) && (src_enc < 16)) {
4622     Assembler::vpsubb(dst, dst, src, vector_len);
4623   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4624     // use nds as scratch for src
4625     evmovdqul(nds, src, Assembler::AVX_512bit);
4626     Assembler::vpsubb(dst, dst, nds, vector_len);
4627   } else if ((src_enc < 16) && (nds_enc < 16)) {
4628     // use nds as scratch for dst
4629     evmovdqul(nds, dst, Assembler::AVX_512bit);
4630     Assembler::vpsubb(nds, nds, src, vector_len);
4631     evmovdqul(dst, nds, Assembler::AVX_512bit);
4632   } else if (dst_enc < 16) {
4633     // use nds as scatch for xmm0 to hold src
4634     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4635     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4636     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4637     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4638   } else {
4639     // worse case scenario, all regs are in the upper bank
4640     subptr(rsp, 64);
4641     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4642     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4643     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4644     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4645     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4646     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4647     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4648     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4649     addptr(rsp, 64);
4650   }
4651 }
4652 
4653 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4654   int dst_enc = dst->encoding();
4655   int nds_enc = nds->encoding();
4656   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4657     Assembler::vpsubb(dst, nds, src, vector_len);
4658   } else if (dst_enc < 16) {
4659     Assembler::vpsubb(dst, dst, src, vector_len);
4660   } else if (nds_enc < 16) {
4661     // implies dst_enc in upper bank with src as scratch
4662     evmovdqul(nds, dst, Assembler::AVX_512bit);
4663     Assembler::vpsubb(nds, nds, src, vector_len);
4664     evmovdqul(dst, nds, Assembler::AVX_512bit);
4665   } else {
4666     // worse case scenario, all regs in upper bank
4667     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4668     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4669     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4670     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4671   }
4672 }
4673 
4674 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4675   int dst_enc = dst->encoding();
4676   int nds_enc = nds->encoding();
4677   int src_enc = src->encoding();
4678   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4679     Assembler::vpsubw(dst, nds, src, vector_len);
4680   } else if ((dst_enc < 16) && (src_enc < 16)) {
4681     Assembler::vpsubw(dst, dst, src, vector_len);
4682   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4683     // use nds as scratch for src
4684     evmovdqul(nds, src, Assembler::AVX_512bit);
4685     Assembler::vpsubw(dst, dst, nds, vector_len);
4686   } else if ((src_enc < 16) && (nds_enc < 16)) {
4687     // use nds as scratch for dst
4688     evmovdqul(nds, dst, Assembler::AVX_512bit);
4689     Assembler::vpsubw(nds, nds, src, vector_len);
4690     evmovdqul(dst, nds, Assembler::AVX_512bit);
4691   } else if (dst_enc < 16) {
4692     // use nds as scatch for xmm0 to hold src
4693     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4694     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4695     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4696     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4697   } else {
4698     // worse case scenario, all regs are in the upper bank
4699     subptr(rsp, 64);
4700     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4701     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4702     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4703     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4704     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4705     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4706     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4707     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4708     addptr(rsp, 64);
4709   }
4710 }
4711 
4712 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4713   int dst_enc = dst->encoding();
4714   int nds_enc = nds->encoding();
4715   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4716     Assembler::vpsubw(dst, nds, src, vector_len);
4717   } else if (dst_enc < 16) {
4718     Assembler::vpsubw(dst, dst, src, vector_len);
4719   } else if (nds_enc < 16) {
4720     // implies dst_enc in upper bank with src as scratch
4721     evmovdqul(nds, dst, Assembler::AVX_512bit);
4722     Assembler::vpsubw(nds, nds, src, vector_len);
4723     evmovdqul(dst, nds, Assembler::AVX_512bit);
4724   } else {
4725     // worse case scenario, all regs in upper bank
4726     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4727     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4728     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4729     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4730   }
4731 }
4732 
4733 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4734   int dst_enc = dst->encoding();
4735   int nds_enc = nds->encoding();
4736   int shift_enc = shift->encoding();
4737   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4738     Assembler::vpsraw(dst, nds, shift, vector_len);
4739   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4740     Assembler::vpsraw(dst, dst, shift, vector_len);
4741   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4742     // use nds_enc as scratch with shift
4743     evmovdqul(nds, shift, Assembler::AVX_512bit);
4744     Assembler::vpsraw(dst, dst, nds, vector_len);
4745   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4746     // use nds as scratch with dst
4747     evmovdqul(nds, dst, Assembler::AVX_512bit);
4748     Assembler::vpsraw(nds, nds, shift, vector_len);
4749     evmovdqul(dst, nds, Assembler::AVX_512bit);
4750   } else if (dst_enc < 16) {
4751     // use nds to save a copy of xmm0 and hold shift
4752     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4753     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4754     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4755     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4756   } else if (nds_enc < 16) {
4757     // use nds as dest as temps
4758     evmovdqul(nds, dst, Assembler::AVX_512bit);
4759     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4760     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4761     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4762     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4763     evmovdqul(dst, nds, Assembler::AVX_512bit);
4764   } else {
4765     // worse case scenario, all regs are in the upper bank
4766     subptr(rsp, 64);
4767     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4768     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4769     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4770     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4771     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4772     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
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::vpsraw(XMMRegister dst, XMMRegister nds, int shift, 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::vpsraw(dst, nds, shift, vector_len);
4785   } else if (dst_enc < 16) {
4786     Assembler::vpsraw(dst, dst, shift, vector_len);
4787   } else if (nds_enc < 16) {
4788     // use nds as scratch
4789     evmovdqul(nds, dst, Assembler::AVX_512bit);
4790     Assembler::vpsraw(nds, nds, shift, vector_len);
4791     evmovdqul(dst, nds, Assembler::AVX_512bit);
4792   } else {
4793     // use nds as scratch for xmm0
4794     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4795     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4796     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4797     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4798   }
4799 }
4800 
4801 void MacroAssembler::vpsrlw(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::vpsrlw(dst, nds, shift, vector_len);
4807   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4808     Assembler::vpsrlw(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::vpsrlw(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::vpsrlw(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::vpsrlw(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::vpsrlw(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::vpsrlw(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::vpsrlw(dst, nds, shift, vector_len);
4853   } else if (dst_enc < 16) {
4854     Assembler::vpsrlw(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::vpsrlw(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::vpsrlw(xmm0, xmm0, shift, vector_len);
4865     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4866   }
4867 }
4868 
4869 void MacroAssembler::vpsllw(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::vpsllw(dst, nds, shift, vector_len);
4875   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4876     Assembler::vpsllw(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::vpsllw(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::vpsllw(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::vpsllw(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::vpsllw(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::vpsllw(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::vpsllw(dst, nds, shift, vector_len);
4921   } else if (dst_enc < 16) {
4922     Assembler::vpsllw(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::vpsllw(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::vpsllw(xmm0, xmm0, shift, vector_len);
4933     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4934   }
4935 }
4936 
4937 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4938   int dst_enc = dst->encoding();
4939   int src_enc = src->encoding();
4940   if ((dst_enc < 16) && (src_enc < 16)) {
4941     Assembler::vptest(dst, src);
4942   } else if (src_enc < 16) {
4943     subptr(rsp, 64);
4944     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4945     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4946     Assembler::vptest(xmm0, src);
4947     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4948     addptr(rsp, 64);
4949   } else if (dst_enc < 16) {
4950     subptr(rsp, 64);
4951     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4952     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4953     Assembler::vptest(dst, xmm0);
4954     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4955     addptr(rsp, 64);
4956   } else {
4957     subptr(rsp, 64);
4958     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4959     subptr(rsp, 64);
4960     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4961     movdqu(xmm0, src);
4962     movdqu(xmm1, dst);
4963     Assembler::vptest(xmm1, xmm0);
4964     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4965     addptr(rsp, 64);
4966     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4967     addptr(rsp, 64);
4968   }
4969 }
4970 
4971 // This instruction exists within macros, ergo we cannot control its input
4972 // when emitted through those patterns.
4973 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4974   if (VM_Version::supports_avx512nobw()) {
4975     int dst_enc = dst->encoding();
4976     int src_enc = src->encoding();
4977     if (dst_enc == src_enc) {
4978       if (dst_enc < 16) {
4979         Assembler::punpcklbw(dst, src);
4980       } else {
4981         subptr(rsp, 64);
4982         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4983         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4984         Assembler::punpcklbw(xmm0, xmm0);
4985         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4986         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4987         addptr(rsp, 64);
4988       }
4989     } else {
4990       if ((src_enc < 16) && (dst_enc < 16)) {
4991         Assembler::punpcklbw(dst, src);
4992       } else if (src_enc < 16) {
4993         subptr(rsp, 64);
4994         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4995         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4996         Assembler::punpcklbw(xmm0, src);
4997         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4998         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4999         addptr(rsp, 64);
5000       } else if (dst_enc < 16) {
5001         subptr(rsp, 64);
5002         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5003         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5004         Assembler::punpcklbw(dst, xmm0);
5005         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5006         addptr(rsp, 64);
5007       } else {
5008         subptr(rsp, 64);
5009         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5010         subptr(rsp, 64);
5011         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5012         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5013         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5014         Assembler::punpcklbw(xmm0, xmm1);
5015         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5016         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5017         addptr(rsp, 64);
5018         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5019         addptr(rsp, 64);
5020       }
5021     }
5022   } else {
5023     Assembler::punpcklbw(dst, src);
5024   }
5025 }
5026 
5027 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5028   if (VM_Version::supports_avx512vl()) {
5029     Assembler::pshufd(dst, src, mode);
5030   } else {
5031     int dst_enc = dst->encoding();
5032     if (dst_enc < 16) {
5033       Assembler::pshufd(dst, src, mode);
5034     } else {
5035       subptr(rsp, 64);
5036       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5037       Assembler::pshufd(xmm0, src, mode);
5038       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5039       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5040       addptr(rsp, 64);
5041     }
5042   }
5043 }
5044 
5045 // This instruction exists within macros, ergo we cannot control its input
5046 // when emitted through those patterns.
5047 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5048   if (VM_Version::supports_avx512nobw()) {
5049     int dst_enc = dst->encoding();
5050     int src_enc = src->encoding();
5051     if (dst_enc == src_enc) {
5052       if (dst_enc < 16) {
5053         Assembler::pshuflw(dst, src, mode);
5054       } else {
5055         subptr(rsp, 64);
5056         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5057         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5058         Assembler::pshuflw(xmm0, xmm0, mode);
5059         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5060         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5061         addptr(rsp, 64);
5062       }
5063     } else {
5064       if ((src_enc < 16) && (dst_enc < 16)) {
5065         Assembler::pshuflw(dst, src, mode);
5066       } else if (src_enc < 16) {
5067         subptr(rsp, 64);
5068         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5069         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5070         Assembler::pshuflw(xmm0, src, mode);
5071         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5072         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5073         addptr(rsp, 64);
5074       } else if (dst_enc < 16) {
5075         subptr(rsp, 64);
5076         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5078         Assembler::pshuflw(dst, xmm0, mode);
5079         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5080         addptr(rsp, 64);
5081       } else {
5082         subptr(rsp, 64);
5083         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5084         subptr(rsp, 64);
5085         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5086         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5087         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5088         Assembler::pshuflw(xmm0, xmm1, mode);
5089         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5090         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5091         addptr(rsp, 64);
5092         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5093         addptr(rsp, 64);
5094       }
5095     }
5096   } else {
5097     Assembler::pshuflw(dst, src, mode);
5098   }
5099 }
5100 
5101 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5102   if (reachable(src)) {
5103     vandpd(dst, nds, as_Address(src), vector_len);
5104   } else {
5105     lea(rscratch1, src);
5106     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5107   }
5108 }
5109 
5110 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5111   if (reachable(src)) {
5112     vandps(dst, nds, as_Address(src), vector_len);
5113   } else {
5114     lea(rscratch1, src);
5115     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5116   }
5117 }
5118 
5119 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5120   if (reachable(src)) {
5121     vdivsd(dst, nds, as_Address(src));
5122   } else {
5123     lea(rscratch1, src);
5124     vdivsd(dst, nds, Address(rscratch1, 0));
5125   }
5126 }
5127 
5128 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5129   if (reachable(src)) {
5130     vdivss(dst, nds, as_Address(src));
5131   } else {
5132     lea(rscratch1, src);
5133     vdivss(dst, nds, Address(rscratch1, 0));
5134   }
5135 }
5136 
5137 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5138   if (reachable(src)) {
5139     vmulsd(dst, nds, as_Address(src));
5140   } else {
5141     lea(rscratch1, src);
5142     vmulsd(dst, nds, Address(rscratch1, 0));
5143   }
5144 }
5145 
5146 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5147   if (reachable(src)) {
5148     vmulss(dst, nds, as_Address(src));
5149   } else {
5150     lea(rscratch1, src);
5151     vmulss(dst, nds, Address(rscratch1, 0));
5152   }
5153 }
5154 
5155 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5156   if (reachable(src)) {
5157     vsubsd(dst, nds, as_Address(src));
5158   } else {
5159     lea(rscratch1, src);
5160     vsubsd(dst, nds, Address(rscratch1, 0));
5161   }
5162 }
5163 
5164 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5165   if (reachable(src)) {
5166     vsubss(dst, nds, as_Address(src));
5167   } else {
5168     lea(rscratch1, src);
5169     vsubss(dst, nds, Address(rscratch1, 0));
5170   }
5171 }
5172 
5173 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5174   int nds_enc = nds->encoding();
5175   int dst_enc = dst->encoding();
5176   bool dst_upper_bank = (dst_enc > 15);
5177   bool nds_upper_bank = (nds_enc > 15);
5178   if (VM_Version::supports_avx512novl() &&
5179       (nds_upper_bank || dst_upper_bank)) {
5180     if (dst_upper_bank) {
5181       subptr(rsp, 64);
5182       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5183       movflt(xmm0, nds);
5184       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5185       movflt(dst, xmm0);
5186       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5187       addptr(rsp, 64);
5188     } else {
5189       movflt(dst, nds);
5190       vxorps(dst, dst, src, Assembler::AVX_128bit);
5191     }
5192   } else {
5193     vxorps(dst, nds, src, Assembler::AVX_128bit);
5194   }
5195 }
5196 
5197 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5198   int nds_enc = nds->encoding();
5199   int dst_enc = dst->encoding();
5200   bool dst_upper_bank = (dst_enc > 15);
5201   bool nds_upper_bank = (nds_enc > 15);
5202   if (VM_Version::supports_avx512novl() &&
5203       (nds_upper_bank || dst_upper_bank)) {
5204     if (dst_upper_bank) {
5205       subptr(rsp, 64);
5206       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5207       movdbl(xmm0, nds);
5208       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5209       movdbl(dst, xmm0);
5210       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5211       addptr(rsp, 64);
5212     } else {
5213       movdbl(dst, nds);
5214       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5215     }
5216   } else {
5217     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5218   }
5219 }
5220 
5221 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5222   if (reachable(src)) {
5223     vxorpd(dst, nds, as_Address(src), vector_len);
5224   } else {
5225     lea(rscratch1, src);
5226     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5227   }
5228 }
5229 
5230 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5231   if (reachable(src)) {
5232     vxorps(dst, nds, as_Address(src), vector_len);
5233   } else {
5234     lea(rscratch1, src);
5235     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5236   }
5237 }
5238 
5239 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5240   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5241   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5242   // The inverted mask is sign-extended
5243   andptr(possibly_jweak, inverted_jweak_mask);
5244 }
5245 
5246 void MacroAssembler::resolve_jobject(Register value,
5247                                      Register thread,
5248                                      Register tmp) {
5249   assert_different_registers(value, thread, tmp);
5250   Label done, not_weak;
5251   testptr(value, value);
5252   jcc(Assembler::zero, done);                // Use NULL as-is.
5253   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5254   jcc(Assembler::zero, not_weak);
5255   // Resolve jweak.
5256   access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
5257                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
5258   verify_oop(value);
5259   jmp(done);
5260   bind(not_weak);
5261   // Resolve (untagged) jobject.
5262   access_load_at(T_OBJECT, IN_ROOT | IN_CONCURRENT_ROOT,
5263                  value, Address(value, 0), tmp, thread);
5264   verify_oop(value);
5265   bind(done);
5266 }
5267 
5268 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5269   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5270 }
5271 
5272 // Force generation of a 4 byte immediate value even if it fits into 8bit
5273 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5274   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5275 }
5276 
5277 void MacroAssembler::subptr(Register dst, Register src) {
5278   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5279 }
5280 
5281 // C++ bool manipulation
5282 void MacroAssembler::testbool(Register dst) {
5283   if(sizeof(bool) == 1)
5284     testb(dst, 0xff);
5285   else if(sizeof(bool) == 2) {
5286     // testw implementation needed for two byte bools
5287     ShouldNotReachHere();
5288   } else if(sizeof(bool) == 4)
5289     testl(dst, dst);
5290   else
5291     // unsupported
5292     ShouldNotReachHere();
5293 }
5294 
5295 void MacroAssembler::testptr(Register dst, Register src) {
5296   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5297 }
5298 
5299 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5300 void MacroAssembler::tlab_allocate(Register obj,
5301                                    Register var_size_in_bytes,
5302                                    int con_size_in_bytes,
5303                                    Register t1,
5304                                    Register t2,
5305                                    Label& slow_case) {
5306   assert_different_registers(obj, t1, t2);
5307   assert_different_registers(obj, var_size_in_bytes, t1);
5308   Register end = t2;
5309   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5310 
5311   verify_tlab();
5312 
5313   NOT_LP64(get_thread(thread));
5314 
5315   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5316   if (var_size_in_bytes == noreg) {
5317     lea(end, Address(obj, con_size_in_bytes));
5318   } else {
5319     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5320   }
5321   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5322   jcc(Assembler::above, slow_case);
5323 
5324   // update the tlab top pointer
5325   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5326 
5327   // recover var_size_in_bytes if necessary
5328   if (var_size_in_bytes == end) {
5329     subptr(var_size_in_bytes, obj);
5330   }
5331   verify_tlab();
5332 }
5333 
5334 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5335 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5336   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5337   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5338   Label done;
5339 
5340   testptr(length_in_bytes, length_in_bytes);
5341   jcc(Assembler::zero, done);
5342 
5343   // initialize topmost word, divide index by 2, check if odd and test if zero
5344   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5345 #ifdef ASSERT
5346   {
5347     Label L;
5348     testptr(length_in_bytes, BytesPerWord - 1);
5349     jcc(Assembler::zero, L);
5350     stop("length must be a multiple of BytesPerWord");
5351     bind(L);
5352   }
5353 #endif
5354   Register index = length_in_bytes;
5355   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5356   if (UseIncDec) {
5357     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5358   } else {
5359     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5360     shrptr(index, 1);
5361   }
5362 #ifndef _LP64
5363   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5364   {
5365     Label even;
5366     // note: if index was a multiple of 8, then it cannot
5367     //       be 0 now otherwise it must have been 0 before
5368     //       => if it is even, we don't need to check for 0 again
5369     jcc(Assembler::carryClear, even);
5370     // clear topmost word (no jump would be needed if conditional assignment worked here)
5371     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5372     // index could be 0 now, must check again
5373     jcc(Assembler::zero, done);
5374     bind(even);
5375   }
5376 #endif // !_LP64
5377   // initialize remaining object fields: index is a multiple of 2 now
5378   {
5379     Label loop;
5380     bind(loop);
5381     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5382     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5383     decrement(index);
5384     jcc(Assembler::notZero, loop);
5385   }
5386 
5387   bind(done);
5388 }
5389 
5390 void MacroAssembler::incr_allocated_bytes(Register thread,
5391                                           Register var_size_in_bytes,
5392                                           int con_size_in_bytes,
5393                                           Register t1) {
5394   if (!thread->is_valid()) {
5395 #ifdef _LP64
5396     thread = r15_thread;
5397 #else
5398     assert(t1->is_valid(), "need temp reg");
5399     thread = t1;
5400     get_thread(thread);
5401 #endif
5402   }
5403 
5404 #ifdef _LP64
5405   if (var_size_in_bytes->is_valid()) {
5406     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5407   } else {
5408     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5409   }
5410 #else
5411   if (var_size_in_bytes->is_valid()) {
5412     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5413   } else {
5414     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5415   }
5416   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5417 #endif
5418 }
5419 
5420 // Look up the method for a megamorphic invokeinterface call.
5421 // The target method is determined by <intf_klass, itable_index>.
5422 // The receiver klass is in recv_klass.
5423 // On success, the result will be in method_result, and execution falls through.
5424 // On failure, execution transfers to the given label.
5425 void MacroAssembler::lookup_interface_method(Register recv_klass,
5426                                              Register intf_klass,
5427                                              RegisterOrConstant itable_index,
5428                                              Register method_result,
5429                                              Register scan_temp,
5430                                              Label& L_no_such_interface,
5431                                              bool return_method) {
5432   assert_different_registers(recv_klass, intf_klass, scan_temp);
5433   assert_different_registers(method_result, intf_klass, scan_temp);
5434   assert(recv_klass != method_result || !return_method,
5435          "recv_klass can be destroyed when method isn't needed");
5436 
5437   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5438          "caller must use same register for non-constant itable index as for method");
5439 
5440   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5441   int vtable_base = in_bytes(Klass::vtable_start_offset());
5442   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5443   int scan_step   = itableOffsetEntry::size() * wordSize;
5444   int vte_size    = vtableEntry::size_in_bytes();
5445   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5446   assert(vte_size == wordSize, "else adjust times_vte_scale");
5447 
5448   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5449 
5450   // %%% Could store the aligned, prescaled offset in the klassoop.
5451   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5452 
5453   if (return_method) {
5454     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5455     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5456     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5457   }
5458 
5459   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5460   //   if (scan->interface() == intf) {
5461   //     result = (klass + scan->offset() + itable_index);
5462   //   }
5463   // }
5464   Label search, found_method;
5465 
5466   for (int peel = 1; peel >= 0; peel--) {
5467     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5468     cmpptr(intf_klass, method_result);
5469 
5470     if (peel) {
5471       jccb(Assembler::equal, found_method);
5472     } else {
5473       jccb(Assembler::notEqual, search);
5474       // (invert the test to fall through to found_method...)
5475     }
5476 
5477     if (!peel)  break;
5478 
5479     bind(search);
5480 
5481     // Check that the previous entry is non-null.  A null entry means that
5482     // the receiver class doesn't implement the interface, and wasn't the
5483     // same as when the caller was compiled.
5484     testptr(method_result, method_result);
5485     jcc(Assembler::zero, L_no_such_interface);
5486     addptr(scan_temp, scan_step);
5487   }
5488 
5489   bind(found_method);
5490 
5491   if (return_method) {
5492     // Got a hit.
5493     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5494     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5495   }
5496 }
5497 
5498 
5499 // virtual method calling
5500 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5501                                            RegisterOrConstant vtable_index,
5502                                            Register method_result) {
5503   const int base = in_bytes(Klass::vtable_start_offset());
5504   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5505   Address vtable_entry_addr(recv_klass,
5506                             vtable_index, Address::times_ptr,
5507                             base + vtableEntry::method_offset_in_bytes());
5508   movptr(method_result, vtable_entry_addr);
5509 }
5510 
5511 
5512 void MacroAssembler::check_klass_subtype(Register sub_klass,
5513                            Register super_klass,
5514                            Register temp_reg,
5515                            Label& L_success) {
5516   Label L_failure;
5517   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5518   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5519   bind(L_failure);
5520 }
5521 
5522 
5523 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5524                                                    Register super_klass,
5525                                                    Register temp_reg,
5526                                                    Label* L_success,
5527                                                    Label* L_failure,
5528                                                    Label* L_slow_path,
5529                                         RegisterOrConstant super_check_offset) {
5530   assert_different_registers(sub_klass, super_klass, temp_reg);
5531   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5532   if (super_check_offset.is_register()) {
5533     assert_different_registers(sub_klass, super_klass,
5534                                super_check_offset.as_register());
5535   } else if (must_load_sco) {
5536     assert(temp_reg != noreg, "supply either a temp or a register offset");
5537   }
5538 
5539   Label L_fallthrough;
5540   int label_nulls = 0;
5541   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5542   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5543   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5544   assert(label_nulls <= 1, "at most one NULL in the batch");
5545 
5546   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5547   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5548   Address super_check_offset_addr(super_klass, sco_offset);
5549 
5550   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5551   // range of a jccb.  If this routine grows larger, reconsider at
5552   // least some of these.
5553 #define local_jcc(assembler_cond, label)                                \
5554   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5555   else                             jcc( assembler_cond, label) /*omit semi*/
5556 
5557   // Hacked jmp, which may only be used just before L_fallthrough.
5558 #define final_jmp(label)                                                \
5559   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5560   else                            jmp(label)                /*omit semi*/
5561 
5562   // If the pointers are equal, we are done (e.g., String[] elements).
5563   // This self-check enables sharing of secondary supertype arrays among
5564   // non-primary types such as array-of-interface.  Otherwise, each such
5565   // type would need its own customized SSA.
5566   // We move this check to the front of the fast path because many
5567   // type checks are in fact trivially successful in this manner,
5568   // so we get a nicely predicted branch right at the start of the check.
5569   cmpptr(sub_klass, super_klass);
5570   local_jcc(Assembler::equal, *L_success);
5571 
5572   // Check the supertype display:
5573   if (must_load_sco) {
5574     // Positive movl does right thing on LP64.
5575     movl(temp_reg, super_check_offset_addr);
5576     super_check_offset = RegisterOrConstant(temp_reg);
5577   }
5578   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5579   cmpptr(super_klass, super_check_addr); // load displayed supertype
5580 
5581   // This check has worked decisively for primary supers.
5582   // Secondary supers are sought in the super_cache ('super_cache_addr').
5583   // (Secondary supers are interfaces and very deeply nested subtypes.)
5584   // This works in the same check above because of a tricky aliasing
5585   // between the super_cache and the primary super display elements.
5586   // (The 'super_check_addr' can address either, as the case requires.)
5587   // Note that the cache is updated below if it does not help us find
5588   // what we need immediately.
5589   // So if it was a primary super, we can just fail immediately.
5590   // Otherwise, it's the slow path for us (no success at this point).
5591 
5592   if (super_check_offset.is_register()) {
5593     local_jcc(Assembler::equal, *L_success);
5594     cmpl(super_check_offset.as_register(), sc_offset);
5595     if (L_failure == &L_fallthrough) {
5596       local_jcc(Assembler::equal, *L_slow_path);
5597     } else {
5598       local_jcc(Assembler::notEqual, *L_failure);
5599       final_jmp(*L_slow_path);
5600     }
5601   } else if (super_check_offset.as_constant() == sc_offset) {
5602     // Need a slow path; fast failure is impossible.
5603     if (L_slow_path == &L_fallthrough) {
5604       local_jcc(Assembler::equal, *L_success);
5605     } else {
5606       local_jcc(Assembler::notEqual, *L_slow_path);
5607       final_jmp(*L_success);
5608     }
5609   } else {
5610     // No slow path; it's a fast decision.
5611     if (L_failure == &L_fallthrough) {
5612       local_jcc(Assembler::equal, *L_success);
5613     } else {
5614       local_jcc(Assembler::notEqual, *L_failure);
5615       final_jmp(*L_success);
5616     }
5617   }
5618 
5619   bind(L_fallthrough);
5620 
5621 #undef local_jcc
5622 #undef final_jmp
5623 }
5624 
5625 
5626 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5627                                                    Register super_klass,
5628                                                    Register temp_reg,
5629                                                    Register temp2_reg,
5630                                                    Label* L_success,
5631                                                    Label* L_failure,
5632                                                    bool set_cond_codes) {
5633   assert_different_registers(sub_klass, super_klass, temp_reg);
5634   if (temp2_reg != noreg)
5635     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5636 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5637 
5638   Label L_fallthrough;
5639   int label_nulls = 0;
5640   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5641   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5642   assert(label_nulls <= 1, "at most one NULL in the batch");
5643 
5644   // a couple of useful fields in sub_klass:
5645   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5646   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5647   Address secondary_supers_addr(sub_klass, ss_offset);
5648   Address super_cache_addr(     sub_klass, sc_offset);
5649 
5650   // Do a linear scan of the secondary super-klass chain.
5651   // This code is rarely used, so simplicity is a virtue here.
5652   // The repne_scan instruction uses fixed registers, which we must spill.
5653   // Don't worry too much about pre-existing connections with the input regs.
5654 
5655   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5656   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5657 
5658   // Get super_klass value into rax (even if it was in rdi or rcx).
5659   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5660   if (super_klass != rax || UseCompressedOops) {
5661     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5662     mov(rax, super_klass);
5663   }
5664   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5665   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5666 
5667 #ifndef PRODUCT
5668   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5669   ExternalAddress pst_counter_addr((address) pst_counter);
5670   NOT_LP64(  incrementl(pst_counter_addr) );
5671   LP64_ONLY( lea(rcx, pst_counter_addr) );
5672   LP64_ONLY( incrementl(Address(rcx, 0)) );
5673 #endif //PRODUCT
5674 
5675   // We will consult the secondary-super array.
5676   movptr(rdi, secondary_supers_addr);
5677   // Load the array length.  (Positive movl does right thing on LP64.)
5678   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5679   // Skip to start of data.
5680   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5681 
5682   // Scan RCX words at [RDI] for an occurrence of RAX.
5683   // Set NZ/Z based on last compare.
5684   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5685   // not change flags (only scas instruction which is repeated sets flags).
5686   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5687 
5688     testptr(rax,rax); // Set Z = 0
5689     repne_scan();
5690 
5691   // Unspill the temp. registers:
5692   if (pushed_rdi)  pop(rdi);
5693   if (pushed_rcx)  pop(rcx);
5694   if (pushed_rax)  pop(rax);
5695 
5696   if (set_cond_codes) {
5697     // Special hack for the AD files:  rdi is guaranteed non-zero.
5698     assert(!pushed_rdi, "rdi must be left non-NULL");
5699     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5700   }
5701 
5702   if (L_failure == &L_fallthrough)
5703         jccb(Assembler::notEqual, *L_failure);
5704   else  jcc(Assembler::notEqual, *L_failure);
5705 
5706   // Success.  Cache the super we found and proceed in triumph.
5707   movptr(super_cache_addr, super_klass);
5708 
5709   if (L_success != &L_fallthrough) {
5710     jmp(*L_success);
5711   }
5712 
5713 #undef IS_A_TEMP
5714 
5715   bind(L_fallthrough);
5716 }
5717 
5718 
5719 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5720   if (VM_Version::supports_cmov()) {
5721     cmovl(cc, dst, src);
5722   } else {
5723     Label L;
5724     jccb(negate_condition(cc), L);
5725     movl(dst, src);
5726     bind(L);
5727   }
5728 }
5729 
5730 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5731   if (VM_Version::supports_cmov()) {
5732     cmovl(cc, dst, src);
5733   } else {
5734     Label L;
5735     jccb(negate_condition(cc), L);
5736     movl(dst, src);
5737     bind(L);
5738   }
5739 }
5740 
5741 void MacroAssembler::verify_oop(Register reg, const char* s) {
5742   if (!VerifyOops) return;
5743 
5744   // Pass register number to verify_oop_subroutine
5745   const char* b = NULL;
5746   {
5747     ResourceMark rm;
5748     stringStream ss;
5749     ss.print("verify_oop: %s: %s", reg->name(), s);
5750     b = code_string(ss.as_string());
5751   }
5752   BLOCK_COMMENT("verify_oop {");
5753 #ifdef _LP64
5754   push(rscratch1);                    // save r10, trashed by movptr()
5755 #endif
5756   push(rax);                          // save rax,
5757   push(reg);                          // pass register argument
5758   ExternalAddress buffer((address) b);
5759   // avoid using pushptr, as it modifies scratch registers
5760   // and our contract is not to modify anything
5761   movptr(rax, buffer.addr());
5762   push(rax);
5763   // call indirectly to solve generation ordering problem
5764   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5765   call(rax);
5766   // Caller pops the arguments (oop, message) and restores rax, r10
5767   BLOCK_COMMENT("} verify_oop");
5768 }
5769 
5770 
5771 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5772                                                       Register tmp,
5773                                                       int offset) {
5774   intptr_t value = *delayed_value_addr;
5775   if (value != 0)
5776     return RegisterOrConstant(value + offset);
5777 
5778   // load indirectly to solve generation ordering problem
5779   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5780 
5781 #ifdef ASSERT
5782   { Label L;
5783     testptr(tmp, tmp);
5784     if (WizardMode) {
5785       const char* buf = NULL;
5786       {
5787         ResourceMark rm;
5788         stringStream ss;
5789         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5790         buf = code_string(ss.as_string());
5791       }
5792       jcc(Assembler::notZero, L);
5793       STOP(buf);
5794     } else {
5795       jccb(Assembler::notZero, L);
5796       hlt();
5797     }
5798     bind(L);
5799   }
5800 #endif
5801 
5802   if (offset != 0)
5803     addptr(tmp, offset);
5804 
5805   return RegisterOrConstant(tmp);
5806 }
5807 
5808 
5809 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5810                                          int extra_slot_offset) {
5811   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5812   int stackElementSize = Interpreter::stackElementSize;
5813   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5814 #ifdef ASSERT
5815   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5816   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5817 #endif
5818   Register             scale_reg    = noreg;
5819   Address::ScaleFactor scale_factor = Address::no_scale;
5820   if (arg_slot.is_constant()) {
5821     offset += arg_slot.as_constant() * stackElementSize;
5822   } else {
5823     scale_reg    = arg_slot.as_register();
5824     scale_factor = Address::times(stackElementSize);
5825   }
5826   offset += wordSize;           // return PC is on stack
5827   return Address(rsp, scale_reg, scale_factor, offset);
5828 }
5829 
5830 
5831 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5832   if (!VerifyOops) return;
5833 
5834   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5835   // Pass register number to verify_oop_subroutine
5836   const char* b = NULL;
5837   {
5838     ResourceMark rm;
5839     stringStream ss;
5840     ss.print("verify_oop_addr: %s", s);
5841     b = code_string(ss.as_string());
5842   }
5843 #ifdef _LP64
5844   push(rscratch1);                    // save r10, trashed by movptr()
5845 #endif
5846   push(rax);                          // save rax,
5847   // addr may contain rsp so we will have to adjust it based on the push
5848   // we just did (and on 64 bit we do two pushes)
5849   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5850   // stores rax into addr which is backwards of what was intended.
5851   if (addr.uses(rsp)) {
5852     lea(rax, addr);
5853     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5854   } else {
5855     pushptr(addr);
5856   }
5857 
5858   ExternalAddress buffer((address) b);
5859   // pass msg argument
5860   // avoid using pushptr, as it modifies scratch registers
5861   // and our contract is not to modify anything
5862   movptr(rax, buffer.addr());
5863   push(rax);
5864 
5865   // call indirectly to solve generation ordering problem
5866   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5867   call(rax);
5868   // Caller pops the arguments (addr, message) and restores rax, r10.
5869 }
5870 
5871 void MacroAssembler::verify_tlab() {
5872 #ifdef ASSERT
5873   if (UseTLAB && VerifyOops) {
5874     Label next, ok;
5875     Register t1 = rsi;
5876     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5877 
5878     push(t1);
5879     NOT_LP64(push(thread_reg));
5880     NOT_LP64(get_thread(thread_reg));
5881 
5882     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5883     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5884     jcc(Assembler::aboveEqual, next);
5885     STOP("assert(top >= start)");
5886     should_not_reach_here();
5887 
5888     bind(next);
5889     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5890     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5891     jcc(Assembler::aboveEqual, ok);
5892     STOP("assert(top <= end)");
5893     should_not_reach_here();
5894 
5895     bind(ok);
5896     NOT_LP64(pop(thread_reg));
5897     pop(t1);
5898   }
5899 #endif
5900 }
5901 
5902 class ControlWord {
5903  public:
5904   int32_t _value;
5905 
5906   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5907   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5908   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5909   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5910   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5911   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5912   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5913   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5914 
5915   void print() const {
5916     // rounding control
5917     const char* rc;
5918     switch (rounding_control()) {
5919       case 0: rc = "round near"; break;
5920       case 1: rc = "round down"; break;
5921       case 2: rc = "round up  "; break;
5922       case 3: rc = "chop      "; break;
5923     };
5924     // precision control
5925     const char* pc;
5926     switch (precision_control()) {
5927       case 0: pc = "24 bits "; break;
5928       case 1: pc = "reserved"; break;
5929       case 2: pc = "53 bits "; break;
5930       case 3: pc = "64 bits "; break;
5931     };
5932     // flags
5933     char f[9];
5934     f[0] = ' ';
5935     f[1] = ' ';
5936     f[2] = (precision   ()) ? 'P' : 'p';
5937     f[3] = (underflow   ()) ? 'U' : 'u';
5938     f[4] = (overflow    ()) ? 'O' : 'o';
5939     f[5] = (zero_divide ()) ? 'Z' : 'z';
5940     f[6] = (denormalized()) ? 'D' : 'd';
5941     f[7] = (invalid     ()) ? 'I' : 'i';
5942     f[8] = '\x0';
5943     // output
5944     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5945   }
5946 
5947 };
5948 
5949 class StatusWord {
5950  public:
5951   int32_t _value;
5952 
5953   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5954   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5955   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5956   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5957   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5958   int  top() const                     { return  (_value >> 11) & 7      ; }
5959   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5960   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5961   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5962   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5963   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5964   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5965   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5966   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5967 
5968   void print() const {
5969     // condition codes
5970     char c[5];
5971     c[0] = (C3()) ? '3' : '-';
5972     c[1] = (C2()) ? '2' : '-';
5973     c[2] = (C1()) ? '1' : '-';
5974     c[3] = (C0()) ? '0' : '-';
5975     c[4] = '\x0';
5976     // flags
5977     char f[9];
5978     f[0] = (error_status()) ? 'E' : '-';
5979     f[1] = (stack_fault ()) ? 'S' : '-';
5980     f[2] = (precision   ()) ? 'P' : '-';
5981     f[3] = (underflow   ()) ? 'U' : '-';
5982     f[4] = (overflow    ()) ? 'O' : '-';
5983     f[5] = (zero_divide ()) ? 'Z' : '-';
5984     f[6] = (denormalized()) ? 'D' : '-';
5985     f[7] = (invalid     ()) ? 'I' : '-';
5986     f[8] = '\x0';
5987     // output
5988     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
5989   }
5990 
5991 };
5992 
5993 class TagWord {
5994  public:
5995   int32_t _value;
5996 
5997   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
5998 
5999   void print() const {
6000     printf("%04x", _value & 0xFFFF);
6001   }
6002 
6003 };
6004 
6005 class FPU_Register {
6006  public:
6007   int32_t _m0;
6008   int32_t _m1;
6009   int16_t _ex;
6010 
6011   bool is_indefinite() const           {
6012     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6013   }
6014 
6015   void print() const {
6016     char  sign = (_ex < 0) ? '-' : '+';
6017     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6018     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6019   };
6020 
6021 };
6022 
6023 class FPU_State {
6024  public:
6025   enum {
6026     register_size       = 10,
6027     number_of_registers =  8,
6028     register_mask       =  7
6029   };
6030 
6031   ControlWord  _control_word;
6032   StatusWord   _status_word;
6033   TagWord      _tag_word;
6034   int32_t      _error_offset;
6035   int32_t      _error_selector;
6036   int32_t      _data_offset;
6037   int32_t      _data_selector;
6038   int8_t       _register[register_size * number_of_registers];
6039 
6040   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6041   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6042 
6043   const char* tag_as_string(int tag) const {
6044     switch (tag) {
6045       case 0: return "valid";
6046       case 1: return "zero";
6047       case 2: return "special";
6048       case 3: return "empty";
6049     }
6050     ShouldNotReachHere();
6051     return NULL;
6052   }
6053 
6054   void print() const {
6055     // print computation registers
6056     { int t = _status_word.top();
6057       for (int i = 0; i < number_of_registers; i++) {
6058         int j = (i - t) & register_mask;
6059         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6060         st(j)->print();
6061         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6062       }
6063     }
6064     printf("\n");
6065     // print control registers
6066     printf("ctrl = "); _control_word.print(); printf("\n");
6067     printf("stat = "); _status_word .print(); printf("\n");
6068     printf("tags = "); _tag_word    .print(); printf("\n");
6069   }
6070 
6071 };
6072 
6073 class Flag_Register {
6074  public:
6075   int32_t _value;
6076 
6077   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6078   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6079   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6080   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6081   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6082   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6083   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6084 
6085   void print() const {
6086     // flags
6087     char f[8];
6088     f[0] = (overflow       ()) ? 'O' : '-';
6089     f[1] = (direction      ()) ? 'D' : '-';
6090     f[2] = (sign           ()) ? 'S' : '-';
6091     f[3] = (zero           ()) ? 'Z' : '-';
6092     f[4] = (auxiliary_carry()) ? 'A' : '-';
6093     f[5] = (parity         ()) ? 'P' : '-';
6094     f[6] = (carry          ()) ? 'C' : '-';
6095     f[7] = '\x0';
6096     // output
6097     printf("%08x  flags = %s", _value, f);
6098   }
6099 
6100 };
6101 
6102 class IU_Register {
6103  public:
6104   int32_t _value;
6105 
6106   void print() const {
6107     printf("%08x  %11d", _value, _value);
6108   }
6109 
6110 };
6111 
6112 class IU_State {
6113  public:
6114   Flag_Register _eflags;
6115   IU_Register   _rdi;
6116   IU_Register   _rsi;
6117   IU_Register   _rbp;
6118   IU_Register   _rsp;
6119   IU_Register   _rbx;
6120   IU_Register   _rdx;
6121   IU_Register   _rcx;
6122   IU_Register   _rax;
6123 
6124   void print() const {
6125     // computation registers
6126     printf("rax,  = "); _rax.print(); printf("\n");
6127     printf("rbx,  = "); _rbx.print(); printf("\n");
6128     printf("rcx  = "); _rcx.print(); printf("\n");
6129     printf("rdx  = "); _rdx.print(); printf("\n");
6130     printf("rdi  = "); _rdi.print(); printf("\n");
6131     printf("rsi  = "); _rsi.print(); printf("\n");
6132     printf("rbp,  = "); _rbp.print(); printf("\n");
6133     printf("rsp  = "); _rsp.print(); printf("\n");
6134     printf("\n");
6135     // control registers
6136     printf("flgs = "); _eflags.print(); printf("\n");
6137   }
6138 };
6139 
6140 
6141 class CPU_State {
6142  public:
6143   FPU_State _fpu_state;
6144   IU_State  _iu_state;
6145 
6146   void print() const {
6147     printf("--------------------------------------------------\n");
6148     _iu_state .print();
6149     printf("\n");
6150     _fpu_state.print();
6151     printf("--------------------------------------------------\n");
6152   }
6153 
6154 };
6155 
6156 
6157 static void _print_CPU_state(CPU_State* state) {
6158   state->print();
6159 };
6160 
6161 
6162 void MacroAssembler::print_CPU_state() {
6163   push_CPU_state();
6164   push(rsp);                // pass CPU state
6165   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6166   addptr(rsp, wordSize);       // discard argument
6167   pop_CPU_state();
6168 }
6169 
6170 
6171 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6172   static int counter = 0;
6173   FPU_State* fs = &state->_fpu_state;
6174   counter++;
6175   // For leaf calls, only verify that the top few elements remain empty.
6176   // We only need 1 empty at the top for C2 code.
6177   if( stack_depth < 0 ) {
6178     if( fs->tag_for_st(7) != 3 ) {
6179       printf("FPR7 not empty\n");
6180       state->print();
6181       assert(false, "error");
6182       return false;
6183     }
6184     return true;                // All other stack states do not matter
6185   }
6186 
6187   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6188          "bad FPU control word");
6189 
6190   // compute stack depth
6191   int i = 0;
6192   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6193   int d = i;
6194   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6195   // verify findings
6196   if (i != FPU_State::number_of_registers) {
6197     // stack not contiguous
6198     printf("%s: stack not contiguous at ST%d\n", s, i);
6199     state->print();
6200     assert(false, "error");
6201     return false;
6202   }
6203   // check if computed stack depth corresponds to expected stack depth
6204   if (stack_depth < 0) {
6205     // expected stack depth is -stack_depth or less
6206     if (d > -stack_depth) {
6207       // too many elements on the stack
6208       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6209       state->print();
6210       assert(false, "error");
6211       return false;
6212     }
6213   } else {
6214     // expected stack depth is stack_depth
6215     if (d != stack_depth) {
6216       // wrong stack depth
6217       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6218       state->print();
6219       assert(false, "error");
6220       return false;
6221     }
6222   }
6223   // everything is cool
6224   return true;
6225 }
6226 
6227 
6228 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6229   if (!VerifyFPU) return;
6230   push_CPU_state();
6231   push(rsp);                // pass CPU state
6232   ExternalAddress msg((address) s);
6233   // pass message string s
6234   pushptr(msg.addr());
6235   push(stack_depth);        // pass stack depth
6236   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6237   addptr(rsp, 3 * wordSize);   // discard arguments
6238   // check for error
6239   { Label L;
6240     testl(rax, rax);
6241     jcc(Assembler::notZero, L);
6242     int3();                  // break if error condition
6243     bind(L);
6244   }
6245   pop_CPU_state();
6246 }
6247 
6248 void MacroAssembler::restore_cpu_control_state_after_jni() {
6249   // Either restore the MXCSR register after returning from the JNI Call
6250   // or verify that it wasn't changed (with -Xcheck:jni flag).
6251   if (VM_Version::supports_sse()) {
6252     if (RestoreMXCSROnJNICalls) {
6253       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6254     } else if (CheckJNICalls) {
6255       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6256     }
6257   }
6258   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6259   vzeroupper();
6260   // Reset k1 to 0xffff.
6261   if (VM_Version::supports_evex()) {
6262     push(rcx);
6263     movl(rcx, 0xffff);
6264     kmovwl(k1, rcx);
6265     pop(rcx);
6266   }
6267 
6268 #ifndef _LP64
6269   // Either restore the x87 floating pointer control word after returning
6270   // from the JNI call or verify that it wasn't changed.
6271   if (CheckJNICalls) {
6272     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6273   }
6274 #endif // _LP64
6275 }
6276 
6277 // ((OopHandle)result).resolve();
6278 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
6279   // Only 64 bit platforms support GCs that require a tmp register
6280   // Only IN_HEAP loads require a thread_tmp register
6281   // OopHandle::resolve is an indirection like jobject.
6282   access_load_at(T_OBJECT, IN_ROOT | IN_CONCURRENT_ROOT,
6283                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
6284 }
6285 
6286 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
6287   // get mirror
6288   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6289   movptr(mirror, Address(method, Method::const_offset()));
6290   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6291   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6292   movptr(mirror, Address(mirror, mirror_offset));
6293   resolve_oop_handle(mirror, tmp);
6294 }
6295 
6296 void MacroAssembler::load_klass(Register dst, Register src) {
6297 #ifdef _LP64
6298   if (UseCompressedClassPointers) {
6299     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6300     decode_klass_not_null(dst);
6301   } else
6302 #endif
6303     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6304 }
6305 
6306 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6307   load_klass(dst, src);
6308   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6309 }
6310 
6311 void MacroAssembler::store_klass(Register dst, Register src) {
6312 #ifdef _LP64
6313   if (UseCompressedClassPointers) {
6314     encode_klass_not_null(src);
6315     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6316   } else
6317 #endif
6318     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6319 }
6320 
6321 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6322                                     Register tmp1, Register thread_tmp) {
6323   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6324   bool as_raw = (decorators & AS_RAW) != 0;
6325   if (as_raw) {
6326     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6327   } else {
6328     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6329   }
6330 }
6331 
6332 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6333                                      Register tmp1, Register tmp2) {
6334   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6335   bool as_raw = (decorators & AS_RAW) != 0;
6336   if (as_raw) {
6337     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6338   } else {
6339     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6340   }
6341 }
6342 
6343 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6344                                    Register thread_tmp, DecoratorSet decorators) {
6345   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6346 }
6347 
6348 // Doesn't do verfication, generates fixed size code
6349 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6350                                             Register thread_tmp, DecoratorSet decorators) {
6351   access_load_at(T_OBJECT, IN_HEAP | OOP_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6352 }
6353 
6354 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6355                                     Register tmp2, DecoratorSet decorators) {
6356   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6357 }
6358 
6359 // Used for storing NULLs.
6360 void MacroAssembler::store_heap_oop_null(Address dst) {
6361   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6362 }
6363 
6364 #ifdef _LP64
6365 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6366   if (UseCompressedClassPointers) {
6367     // Store to klass gap in destination
6368     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6369   }
6370 }
6371 
6372 #ifdef ASSERT
6373 void MacroAssembler::verify_heapbase(const char* msg) {
6374   assert (UseCompressedOops, "should be compressed");
6375   assert (Universe::heap() != NULL, "java heap should be initialized");
6376   if (CheckCompressedOops) {
6377     Label ok;
6378     push(rscratch1); // cmpptr trashes rscratch1
6379     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6380     jcc(Assembler::equal, ok);
6381     STOP(msg);
6382     bind(ok);
6383     pop(rscratch1);
6384   }
6385 }
6386 #endif
6387 
6388 // Algorithm must match oop.inline.hpp encode_heap_oop.
6389 void MacroAssembler::encode_heap_oop(Register r) {
6390 #ifdef ASSERT
6391   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6392 #endif
6393   verify_oop(r, "broken oop in encode_heap_oop");
6394   if (Universe::narrow_oop_base() == NULL) {
6395     if (Universe::narrow_oop_shift() != 0) {
6396       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6397       shrq(r, LogMinObjAlignmentInBytes);
6398     }
6399     return;
6400   }
6401   testq(r, r);
6402   cmovq(Assembler::equal, r, r12_heapbase);
6403   subq(r, r12_heapbase);
6404   shrq(r, LogMinObjAlignmentInBytes);
6405 }
6406 
6407 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6408 #ifdef ASSERT
6409   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6410   if (CheckCompressedOops) {
6411     Label ok;
6412     testq(r, r);
6413     jcc(Assembler::notEqual, ok);
6414     STOP("null oop passed to encode_heap_oop_not_null");
6415     bind(ok);
6416   }
6417 #endif
6418   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6419   if (Universe::narrow_oop_base() != NULL) {
6420     subq(r, r12_heapbase);
6421   }
6422   if (Universe::narrow_oop_shift() != 0) {
6423     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6424     shrq(r, LogMinObjAlignmentInBytes);
6425   }
6426 }
6427 
6428 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6429 #ifdef ASSERT
6430   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6431   if (CheckCompressedOops) {
6432     Label ok;
6433     testq(src, src);
6434     jcc(Assembler::notEqual, ok);
6435     STOP("null oop passed to encode_heap_oop_not_null2");
6436     bind(ok);
6437   }
6438 #endif
6439   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6440   if (dst != src) {
6441     movq(dst, src);
6442   }
6443   if (Universe::narrow_oop_base() != NULL) {
6444     subq(dst, r12_heapbase);
6445   }
6446   if (Universe::narrow_oop_shift() != 0) {
6447     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6448     shrq(dst, LogMinObjAlignmentInBytes);
6449   }
6450 }
6451 
6452 void  MacroAssembler::decode_heap_oop(Register r) {
6453 #ifdef ASSERT
6454   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6455 #endif
6456   if (Universe::narrow_oop_base() == NULL) {
6457     if (Universe::narrow_oop_shift() != 0) {
6458       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6459       shlq(r, LogMinObjAlignmentInBytes);
6460     }
6461   } else {
6462     Label done;
6463     shlq(r, LogMinObjAlignmentInBytes);
6464     jccb(Assembler::equal, done);
6465     addq(r, r12_heapbase);
6466     bind(done);
6467   }
6468   verify_oop(r, "broken oop in decode_heap_oop");
6469 }
6470 
6471 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6472   // Note: it will change flags
6473   assert (UseCompressedOops, "should only be used for compressed headers");
6474   assert (Universe::heap() != NULL, "java heap should be initialized");
6475   // Cannot assert, unverified entry point counts instructions (see .ad file)
6476   // vtableStubs also counts instructions in pd_code_size_limit.
6477   // Also do not verify_oop as this is called by verify_oop.
6478   if (Universe::narrow_oop_shift() != 0) {
6479     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6480     shlq(r, LogMinObjAlignmentInBytes);
6481     if (Universe::narrow_oop_base() != NULL) {
6482       addq(r, r12_heapbase);
6483     }
6484   } else {
6485     assert (Universe::narrow_oop_base() == NULL, "sanity");
6486   }
6487 }
6488 
6489 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6490   // Note: it will change flags
6491   assert (UseCompressedOops, "should only be used for compressed headers");
6492   assert (Universe::heap() != NULL, "java heap should be initialized");
6493   // Cannot assert, unverified entry point counts instructions (see .ad file)
6494   // vtableStubs also counts instructions in pd_code_size_limit.
6495   // Also do not verify_oop as this is called by verify_oop.
6496   if (Universe::narrow_oop_shift() != 0) {
6497     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6498     if (LogMinObjAlignmentInBytes == Address::times_8) {
6499       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6500     } else {
6501       if (dst != src) {
6502         movq(dst, src);
6503       }
6504       shlq(dst, LogMinObjAlignmentInBytes);
6505       if (Universe::narrow_oop_base() != NULL) {
6506         addq(dst, r12_heapbase);
6507       }
6508     }
6509   } else {
6510     assert (Universe::narrow_oop_base() == NULL, "sanity");
6511     if (dst != src) {
6512       movq(dst, src);
6513     }
6514   }
6515 }
6516 
6517 void MacroAssembler::encode_klass_not_null(Register r) {
6518   if (Universe::narrow_klass_base() != NULL) {
6519     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6520     assert(r != r12_heapbase, "Encoding a klass in r12");
6521     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6522     subq(r, r12_heapbase);
6523   }
6524   if (Universe::narrow_klass_shift() != 0) {
6525     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6526     shrq(r, LogKlassAlignmentInBytes);
6527   }
6528   if (Universe::narrow_klass_base() != NULL) {
6529     reinit_heapbase();
6530   }
6531 }
6532 
6533 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6534   if (dst == src) {
6535     encode_klass_not_null(src);
6536   } else {
6537     if (Universe::narrow_klass_base() != NULL) {
6538       mov64(dst, (int64_t)Universe::narrow_klass_base());
6539       negq(dst);
6540       addq(dst, src);
6541     } else {
6542       movptr(dst, src);
6543     }
6544     if (Universe::narrow_klass_shift() != 0) {
6545       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6546       shrq(dst, LogKlassAlignmentInBytes);
6547     }
6548   }
6549 }
6550 
6551 // Function instr_size_for_decode_klass_not_null() counts the instructions
6552 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6553 // when (Universe::heap() != NULL).  Hence, if the instructions they
6554 // generate change, then this method needs to be updated.
6555 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6556   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6557   if (Universe::narrow_klass_base() != NULL) {
6558     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6559     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6560   } else {
6561     // longest load decode klass function, mov64, leaq
6562     return 16;
6563   }
6564 }
6565 
6566 // !!! If the instructions that get generated here change then function
6567 // instr_size_for_decode_klass_not_null() needs to get updated.
6568 void  MacroAssembler::decode_klass_not_null(Register r) {
6569   // Note: it will change flags
6570   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6571   assert(r != r12_heapbase, "Decoding a klass in r12");
6572   // Cannot assert, unverified entry point counts instructions (see .ad file)
6573   // vtableStubs also counts instructions in pd_code_size_limit.
6574   // Also do not verify_oop as this is called by verify_oop.
6575   if (Universe::narrow_klass_shift() != 0) {
6576     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6577     shlq(r, LogKlassAlignmentInBytes);
6578   }
6579   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6580   if (Universe::narrow_klass_base() != NULL) {
6581     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6582     addq(r, r12_heapbase);
6583     reinit_heapbase();
6584   }
6585 }
6586 
6587 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6588   // Note: it will change flags
6589   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6590   if (dst == src) {
6591     decode_klass_not_null(dst);
6592   } else {
6593     // Cannot assert, unverified entry point counts instructions (see .ad file)
6594     // vtableStubs also counts instructions in pd_code_size_limit.
6595     // Also do not verify_oop as this is called by verify_oop.
6596     mov64(dst, (int64_t)Universe::narrow_klass_base());
6597     if (Universe::narrow_klass_shift() != 0) {
6598       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6599       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6600       leaq(dst, Address(dst, src, Address::times_8, 0));
6601     } else {
6602       addq(dst, src);
6603     }
6604   }
6605 }
6606 
6607 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6608   assert (UseCompressedOops, "should only be used for compressed headers");
6609   assert (Universe::heap() != NULL, "java heap should be initialized");
6610   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6611   int oop_index = oop_recorder()->find_index(obj);
6612   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6613   mov_narrow_oop(dst, oop_index, rspec);
6614 }
6615 
6616 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6617   assert (UseCompressedOops, "should only be used for compressed headers");
6618   assert (Universe::heap() != NULL, "java heap should be initialized");
6619   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6620   int oop_index = oop_recorder()->find_index(obj);
6621   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6622   mov_narrow_oop(dst, oop_index, rspec);
6623 }
6624 
6625 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6626   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6627   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6628   int klass_index = oop_recorder()->find_index(k);
6629   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6630   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6631 }
6632 
6633 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6634   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6635   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6636   int klass_index = oop_recorder()->find_index(k);
6637   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6638   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6639 }
6640 
6641 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6642   assert (UseCompressedOops, "should only be used for compressed headers");
6643   assert (Universe::heap() != NULL, "java heap should be initialized");
6644   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6645   int oop_index = oop_recorder()->find_index(obj);
6646   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6647   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6648 }
6649 
6650 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6651   assert (UseCompressedOops, "should only be used for compressed headers");
6652   assert (Universe::heap() != NULL, "java heap should be initialized");
6653   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6654   int oop_index = oop_recorder()->find_index(obj);
6655   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6656   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6657 }
6658 
6659 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6660   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6661   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6662   int klass_index = oop_recorder()->find_index(k);
6663   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6664   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6665 }
6666 
6667 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6668   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6669   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6670   int klass_index = oop_recorder()->find_index(k);
6671   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6672   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6673 }
6674 
6675 void MacroAssembler::reinit_heapbase() {
6676   if (UseCompressedOops || UseCompressedClassPointers) {
6677     if (Universe::heap() != NULL) {
6678       if (Universe::narrow_oop_base() == NULL) {
6679         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6680       } else {
6681         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6682       }
6683     } else {
6684       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6685     }
6686   }
6687 }
6688 
6689 #endif // _LP64
6690 
6691 // C2 compiled method's prolog code.
6692 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6693 
6694   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6695   // NativeJump::patch_verified_entry will be able to patch out the entry
6696   // code safely. The push to verify stack depth is ok at 5 bytes,
6697   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6698   // stack bang then we must use the 6 byte frame allocation even if
6699   // we have no frame. :-(
6700   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6701 
6702   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6703   // Remove word for return addr
6704   framesize -= wordSize;
6705   stack_bang_size -= wordSize;
6706 
6707   // Calls to C2R adapters often do not accept exceptional returns.
6708   // We require that their callers must bang for them.  But be careful, because
6709   // some VM calls (such as call site linkage) can use several kilobytes of
6710   // stack.  But the stack safety zone should account for that.
6711   // See bugs 4446381, 4468289, 4497237.
6712   if (stack_bang_size > 0) {
6713     generate_stack_overflow_check(stack_bang_size);
6714 
6715     // We always push rbp, so that on return to interpreter rbp, will be
6716     // restored correctly and we can correct the stack.
6717     push(rbp);
6718     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6719     if (PreserveFramePointer) {
6720       mov(rbp, rsp);
6721     }
6722     // Remove word for ebp
6723     framesize -= wordSize;
6724 
6725     // Create frame
6726     if (framesize) {
6727       subptr(rsp, framesize);
6728     }
6729   } else {
6730     // Create frame (force generation of a 4 byte immediate value)
6731     subptr_imm32(rsp, framesize);
6732 
6733     // Save RBP register now.
6734     framesize -= wordSize;
6735     movptr(Address(rsp, framesize), rbp);
6736     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6737     if (PreserveFramePointer) {
6738       movptr(rbp, rsp);
6739       if (framesize > 0) {
6740         addptr(rbp, framesize);
6741       }
6742     }
6743   }
6744 
6745   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6746     framesize -= wordSize;
6747     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6748   }
6749 
6750 #ifndef _LP64
6751   // If method sets FPU control word do it now
6752   if (fp_mode_24b) {
6753     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6754   }
6755   if (UseSSE >= 2 && VerifyFPU) {
6756     verify_FPU(0, "FPU stack must be clean on entry");
6757   }
6758 #endif
6759 
6760 #ifdef ASSERT
6761   if (VerifyStackAtCalls) {
6762     Label L;
6763     push(rax);
6764     mov(rax, rsp);
6765     andptr(rax, StackAlignmentInBytes-1);
6766     cmpptr(rax, StackAlignmentInBytes-wordSize);
6767     pop(rax);
6768     jcc(Assembler::equal, L);
6769     STOP("Stack is not properly aligned!");
6770     bind(L);
6771   }
6772 #endif
6773 
6774 }
6775 
6776 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6777   // cnt - number of qwords (8-byte words).
6778   // base - start address, qword aligned.
6779   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6780   assert(base==rdi, "base register must be edi for rep stos");
6781   assert(tmp==rax,   "tmp register must be eax for rep stos");
6782   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6783   assert(InitArrayShortSize % BytesPerLong == 0,
6784     "InitArrayShortSize should be the multiple of BytesPerLong");
6785 
6786   Label DONE;
6787 
6788   xorptr(tmp, tmp);
6789 
6790   if (!is_large) {
6791     Label LOOP, LONG;
6792     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6793     jccb(Assembler::greater, LONG);
6794 
6795     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6796 
6797     decrement(cnt);
6798     jccb(Assembler::negative, DONE); // Zero length
6799 
6800     // Use individual pointer-sized stores for small counts:
6801     BIND(LOOP);
6802     movptr(Address(base, cnt, Address::times_ptr), tmp);
6803     decrement(cnt);
6804     jccb(Assembler::greaterEqual, LOOP);
6805     jmpb(DONE);
6806 
6807     BIND(LONG);
6808   }
6809 
6810   // Use longer rep-prefixed ops for non-small counts:
6811   if (UseFastStosb) {
6812     shlptr(cnt, 3); // convert to number of bytes
6813     rep_stosb();
6814   } else {
6815     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6816     rep_stos();
6817   }
6818 
6819   BIND(DONE);
6820 }
6821 
6822 #ifdef COMPILER2
6823 
6824 // IndexOf for constant substrings with size >= 8 chars
6825 // which don't need to be loaded through stack.
6826 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6827                                       Register cnt1, Register cnt2,
6828                                       int int_cnt2,  Register result,
6829                                       XMMRegister vec, Register tmp,
6830                                       int ae) {
6831   ShortBranchVerifier sbv(this);
6832   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6833   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6834 
6835   // This method uses the pcmpestri instruction with bound registers
6836   //   inputs:
6837   //     xmm - substring
6838   //     rax - substring length (elements count)
6839   //     mem - scanned string
6840   //     rdx - string length (elements count)
6841   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6842   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6843   //   outputs:
6844   //     rcx - matched index in string
6845   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6846   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6847   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6848   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6849   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6850 
6851   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6852         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6853         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6854 
6855   // Note, inline_string_indexOf() generates checks:
6856   // if (substr.count > string.count) return -1;
6857   // if (substr.count == 0) return 0;
6858   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6859 
6860   // Load substring.
6861   if (ae == StrIntrinsicNode::UL) {
6862     pmovzxbw(vec, Address(str2, 0));
6863   } else {
6864     movdqu(vec, Address(str2, 0));
6865   }
6866   movl(cnt2, int_cnt2);
6867   movptr(result, str1); // string addr
6868 
6869   if (int_cnt2 > stride) {
6870     jmpb(SCAN_TO_SUBSTR);
6871 
6872     // Reload substr for rescan, this code
6873     // is executed only for large substrings (> 8 chars)
6874     bind(RELOAD_SUBSTR);
6875     if (ae == StrIntrinsicNode::UL) {
6876       pmovzxbw(vec, Address(str2, 0));
6877     } else {
6878       movdqu(vec, Address(str2, 0));
6879     }
6880     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6881 
6882     bind(RELOAD_STR);
6883     // We came here after the beginning of the substring was
6884     // matched but the rest of it was not so we need to search
6885     // again. Start from the next element after the previous match.
6886 
6887     // cnt2 is number of substring reminding elements and
6888     // cnt1 is number of string reminding elements when cmp failed.
6889     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6890     subl(cnt1, cnt2);
6891     addl(cnt1, int_cnt2);
6892     movl(cnt2, int_cnt2); // Now restore cnt2
6893 
6894     decrementl(cnt1);     // Shift to next element
6895     cmpl(cnt1, cnt2);
6896     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6897 
6898     addptr(result, (1<<scale1));
6899 
6900   } // (int_cnt2 > 8)
6901 
6902   // Scan string for start of substr in 16-byte vectors
6903   bind(SCAN_TO_SUBSTR);
6904   pcmpestri(vec, Address(result, 0), mode);
6905   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6906   subl(cnt1, stride);
6907   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6908   cmpl(cnt1, cnt2);
6909   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6910   addptr(result, 16);
6911   jmpb(SCAN_TO_SUBSTR);
6912 
6913   // Found a potential substr
6914   bind(FOUND_CANDIDATE);
6915   // Matched whole vector if first element matched (tmp(rcx) == 0).
6916   if (int_cnt2 == stride) {
6917     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6918   } else { // int_cnt2 > 8
6919     jccb(Assembler::overflow, FOUND_SUBSTR);
6920   }
6921   // After pcmpestri tmp(rcx) contains matched element index
6922   // Compute start addr of substr
6923   lea(result, Address(result, tmp, scale1));
6924 
6925   // Make sure string is still long enough
6926   subl(cnt1, tmp);
6927   cmpl(cnt1, cnt2);
6928   if (int_cnt2 == stride) {
6929     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6930   } else { // int_cnt2 > 8
6931     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6932   }
6933   // Left less then substring.
6934 
6935   bind(RET_NOT_FOUND);
6936   movl(result, -1);
6937   jmp(EXIT);
6938 
6939   if (int_cnt2 > stride) {
6940     // This code is optimized for the case when whole substring
6941     // is matched if its head is matched.
6942     bind(MATCH_SUBSTR_HEAD);
6943     pcmpestri(vec, Address(result, 0), mode);
6944     // Reload only string if does not match
6945     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6946 
6947     Label CONT_SCAN_SUBSTR;
6948     // Compare the rest of substring (> 8 chars).
6949     bind(FOUND_SUBSTR);
6950     // First 8 chars are already matched.
6951     negptr(cnt2);
6952     addptr(cnt2, stride);
6953 
6954     bind(SCAN_SUBSTR);
6955     subl(cnt1, stride);
6956     cmpl(cnt2, -stride); // Do not read beyond substring
6957     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6958     // Back-up strings to avoid reading beyond substring:
6959     // cnt1 = cnt1 - cnt2 + 8
6960     addl(cnt1, cnt2); // cnt2 is negative
6961     addl(cnt1, stride);
6962     movl(cnt2, stride); negptr(cnt2);
6963     bind(CONT_SCAN_SUBSTR);
6964     if (int_cnt2 < (int)G) {
6965       int tail_off1 = int_cnt2<<scale1;
6966       int tail_off2 = int_cnt2<<scale2;
6967       if (ae == StrIntrinsicNode::UL) {
6968         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6969       } else {
6970         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6971       }
6972       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6973     } else {
6974       // calculate index in register to avoid integer overflow (int_cnt2*2)
6975       movl(tmp, int_cnt2);
6976       addptr(tmp, cnt2);
6977       if (ae == StrIntrinsicNode::UL) {
6978         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6979       } else {
6980         movdqu(vec, Address(str2, tmp, scale2, 0));
6981       }
6982       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6983     }
6984     // Need to reload strings pointers if not matched whole vector
6985     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6986     addptr(cnt2, stride);
6987     jcc(Assembler::negative, SCAN_SUBSTR);
6988     // Fall through if found full substring
6989 
6990   } // (int_cnt2 > 8)
6991 
6992   bind(RET_FOUND);
6993   // Found result if we matched full small substring.
6994   // Compute substr offset
6995   subptr(result, str1);
6996   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6997     shrl(result, 1); // index
6998   }
6999   bind(EXIT);
7000 
7001 } // string_indexofC8
7002 
7003 // Small strings are loaded through stack if they cross page boundary.
7004 void MacroAssembler::string_indexof(Register str1, Register str2,
7005                                     Register cnt1, Register cnt2,
7006                                     int int_cnt2,  Register result,
7007                                     XMMRegister vec, Register tmp,
7008                                     int ae) {
7009   ShortBranchVerifier sbv(this);
7010   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7011   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7012 
7013   //
7014   // int_cnt2 is length of small (< 8 chars) constant substring
7015   // or (-1) for non constant substring in which case its length
7016   // is in cnt2 register.
7017   //
7018   // Note, inline_string_indexOf() generates checks:
7019   // if (substr.count > string.count) return -1;
7020   // if (substr.count == 0) return 0;
7021   //
7022   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7023   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7024   // This method uses the pcmpestri instruction with bound registers
7025   //   inputs:
7026   //     xmm - substring
7027   //     rax - substring length (elements count)
7028   //     mem - scanned string
7029   //     rdx - string length (elements count)
7030   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7031   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7032   //   outputs:
7033   //     rcx - matched index in string
7034   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7035   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7036   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7037   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7038 
7039   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7040         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7041         FOUND_CANDIDATE;
7042 
7043   { //========================================================
7044     // We don't know where these strings are located
7045     // and we can't read beyond them. Load them through stack.
7046     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7047 
7048     movptr(tmp, rsp); // save old SP
7049 
7050     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7051       if (int_cnt2 == (1>>scale2)) { // One byte
7052         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7053         load_unsigned_byte(result, Address(str2, 0));
7054         movdl(vec, result); // move 32 bits
7055       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7056         // Not enough header space in 32-bit VM: 12+3 = 15.
7057         movl(result, Address(str2, -1));
7058         shrl(result, 8);
7059         movdl(vec, result); // move 32 bits
7060       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7061         load_unsigned_short(result, Address(str2, 0));
7062         movdl(vec, result); // move 32 bits
7063       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7064         movdl(vec, Address(str2, 0)); // move 32 bits
7065       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7066         movq(vec, Address(str2, 0));  // move 64 bits
7067       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7068         // Array header size is 12 bytes in 32-bit VM
7069         // + 6 bytes for 3 chars == 18 bytes,
7070         // enough space to load vec and shift.
7071         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7072         if (ae == StrIntrinsicNode::UL) {
7073           int tail_off = int_cnt2-8;
7074           pmovzxbw(vec, Address(str2, tail_off));
7075           psrldq(vec, -2*tail_off);
7076         }
7077         else {
7078           int tail_off = int_cnt2*(1<<scale2);
7079           movdqu(vec, Address(str2, tail_off-16));
7080           psrldq(vec, 16-tail_off);
7081         }
7082       }
7083     } else { // not constant substring
7084       cmpl(cnt2, stride);
7085       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7086 
7087       // We can read beyond string if srt+16 does not cross page boundary
7088       // since heaps are aligned and mapped by pages.
7089       assert(os::vm_page_size() < (int)G, "default page should be small");
7090       movl(result, str2); // We need only low 32 bits
7091       andl(result, (os::vm_page_size()-1));
7092       cmpl(result, (os::vm_page_size()-16));
7093       jccb(Assembler::belowEqual, CHECK_STR);
7094 
7095       // Move small strings to stack to allow load 16 bytes into vec.
7096       subptr(rsp, 16);
7097       int stk_offset = wordSize-(1<<scale2);
7098       push(cnt2);
7099 
7100       bind(COPY_SUBSTR);
7101       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7102         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7103         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7104       } else if (ae == StrIntrinsicNode::UU) {
7105         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7106         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7107       }
7108       decrement(cnt2);
7109       jccb(Assembler::notZero, COPY_SUBSTR);
7110 
7111       pop(cnt2);
7112       movptr(str2, rsp);  // New substring address
7113     } // non constant
7114 
7115     bind(CHECK_STR);
7116     cmpl(cnt1, stride);
7117     jccb(Assembler::aboveEqual, BIG_STRINGS);
7118 
7119     // Check cross page boundary.
7120     movl(result, str1); // We need only low 32 bits
7121     andl(result, (os::vm_page_size()-1));
7122     cmpl(result, (os::vm_page_size()-16));
7123     jccb(Assembler::belowEqual, BIG_STRINGS);
7124 
7125     subptr(rsp, 16);
7126     int stk_offset = -(1<<scale1);
7127     if (int_cnt2 < 0) { // not constant
7128       push(cnt2);
7129       stk_offset += wordSize;
7130     }
7131     movl(cnt2, cnt1);
7132 
7133     bind(COPY_STR);
7134     if (ae == StrIntrinsicNode::LL) {
7135       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7136       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7137     } else {
7138       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7139       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7140     }
7141     decrement(cnt2);
7142     jccb(Assembler::notZero, COPY_STR);
7143 
7144     if (int_cnt2 < 0) { // not constant
7145       pop(cnt2);
7146     }
7147     movptr(str1, rsp);  // New string address
7148 
7149     bind(BIG_STRINGS);
7150     // Load substring.
7151     if (int_cnt2 < 0) { // -1
7152       if (ae == StrIntrinsicNode::UL) {
7153         pmovzxbw(vec, Address(str2, 0));
7154       } else {
7155         movdqu(vec, Address(str2, 0));
7156       }
7157       push(cnt2);       // substr count
7158       push(str2);       // substr addr
7159       push(str1);       // string addr
7160     } else {
7161       // Small (< 8 chars) constant substrings are loaded already.
7162       movl(cnt2, int_cnt2);
7163     }
7164     push(tmp);  // original SP
7165 
7166   } // Finished loading
7167 
7168   //========================================================
7169   // Start search
7170   //
7171 
7172   movptr(result, str1); // string addr
7173 
7174   if (int_cnt2  < 0) {  // Only for non constant substring
7175     jmpb(SCAN_TO_SUBSTR);
7176 
7177     // SP saved at sp+0
7178     // String saved at sp+1*wordSize
7179     // Substr saved at sp+2*wordSize
7180     // Substr count saved at sp+3*wordSize
7181 
7182     // Reload substr for rescan, this code
7183     // is executed only for large substrings (> 8 chars)
7184     bind(RELOAD_SUBSTR);
7185     movptr(str2, Address(rsp, 2*wordSize));
7186     movl(cnt2, Address(rsp, 3*wordSize));
7187     if (ae == StrIntrinsicNode::UL) {
7188       pmovzxbw(vec, Address(str2, 0));
7189     } else {
7190       movdqu(vec, Address(str2, 0));
7191     }
7192     // We came here after the beginning of the substring was
7193     // matched but the rest of it was not so we need to search
7194     // again. Start from the next element after the previous match.
7195     subptr(str1, result); // Restore counter
7196     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7197       shrl(str1, 1);
7198     }
7199     addl(cnt1, str1);
7200     decrementl(cnt1);   // Shift to next element
7201     cmpl(cnt1, cnt2);
7202     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7203 
7204     addptr(result, (1<<scale1));
7205   } // non constant
7206 
7207   // Scan string for start of substr in 16-byte vectors
7208   bind(SCAN_TO_SUBSTR);
7209   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7210   pcmpestri(vec, Address(result, 0), mode);
7211   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7212   subl(cnt1, stride);
7213   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7214   cmpl(cnt1, cnt2);
7215   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7216   addptr(result, 16);
7217 
7218   bind(ADJUST_STR);
7219   cmpl(cnt1, stride); // Do not read beyond string
7220   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7221   // Back-up string to avoid reading beyond string.
7222   lea(result, Address(result, cnt1, scale1, -16));
7223   movl(cnt1, stride);
7224   jmpb(SCAN_TO_SUBSTR);
7225 
7226   // Found a potential substr
7227   bind(FOUND_CANDIDATE);
7228   // After pcmpestri tmp(rcx) contains matched element index
7229 
7230   // Make sure string is still long enough
7231   subl(cnt1, tmp);
7232   cmpl(cnt1, cnt2);
7233   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7234   // Left less then substring.
7235 
7236   bind(RET_NOT_FOUND);
7237   movl(result, -1);
7238   jmpb(CLEANUP);
7239 
7240   bind(FOUND_SUBSTR);
7241   // Compute start addr of substr
7242   lea(result, Address(result, tmp, scale1));
7243   if (int_cnt2 > 0) { // Constant substring
7244     // Repeat search for small substring (< 8 chars)
7245     // from new point without reloading substring.
7246     // Have to check that we don't read beyond string.
7247     cmpl(tmp, stride-int_cnt2);
7248     jccb(Assembler::greater, ADJUST_STR);
7249     // Fall through if matched whole substring.
7250   } else { // non constant
7251     assert(int_cnt2 == -1, "should be != 0");
7252 
7253     addl(tmp, cnt2);
7254     // Found result if we matched whole substring.
7255     cmpl(tmp, stride);
7256     jccb(Assembler::lessEqual, RET_FOUND);
7257 
7258     // Repeat search for small substring (<= 8 chars)
7259     // from new point 'str1' without reloading substring.
7260     cmpl(cnt2, stride);
7261     // Have to check that we don't read beyond string.
7262     jccb(Assembler::lessEqual, ADJUST_STR);
7263 
7264     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7265     // Compare the rest of substring (> 8 chars).
7266     movptr(str1, result);
7267 
7268     cmpl(tmp, cnt2);
7269     // First 8 chars are already matched.
7270     jccb(Assembler::equal, CHECK_NEXT);
7271 
7272     bind(SCAN_SUBSTR);
7273     pcmpestri(vec, Address(str1, 0), mode);
7274     // Need to reload strings pointers if not matched whole vector
7275     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7276 
7277     bind(CHECK_NEXT);
7278     subl(cnt2, stride);
7279     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7280     addptr(str1, 16);
7281     if (ae == StrIntrinsicNode::UL) {
7282       addptr(str2, 8);
7283     } else {
7284       addptr(str2, 16);
7285     }
7286     subl(cnt1, stride);
7287     cmpl(cnt2, stride); // Do not read beyond substring
7288     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7289     // Back-up strings to avoid reading beyond substring.
7290 
7291     if (ae == StrIntrinsicNode::UL) {
7292       lea(str2, Address(str2, cnt2, scale2, -8));
7293       lea(str1, Address(str1, cnt2, scale1, -16));
7294     } else {
7295       lea(str2, Address(str2, cnt2, scale2, -16));
7296       lea(str1, Address(str1, cnt2, scale1, -16));
7297     }
7298     subl(cnt1, cnt2);
7299     movl(cnt2, stride);
7300     addl(cnt1, stride);
7301     bind(CONT_SCAN_SUBSTR);
7302     if (ae == StrIntrinsicNode::UL) {
7303       pmovzxbw(vec, Address(str2, 0));
7304     } else {
7305       movdqu(vec, Address(str2, 0));
7306     }
7307     jmp(SCAN_SUBSTR);
7308 
7309     bind(RET_FOUND_LONG);
7310     movptr(str1, Address(rsp, wordSize));
7311   } // non constant
7312 
7313   bind(RET_FOUND);
7314   // Compute substr offset
7315   subptr(result, str1);
7316   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7317     shrl(result, 1); // index
7318   }
7319   bind(CLEANUP);
7320   pop(rsp); // restore SP
7321 
7322 } // string_indexof
7323 
7324 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7325                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7326   ShortBranchVerifier sbv(this);
7327   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7328 
7329   int stride = 8;
7330 
7331   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7332         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7333         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7334         FOUND_SEQ_CHAR, DONE_LABEL;
7335 
7336   movptr(result, str1);
7337   if (UseAVX >= 2) {
7338     cmpl(cnt1, stride);
7339     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7340     cmpl(cnt1, 2*stride);
7341     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7342     movdl(vec1, ch);
7343     vpbroadcastw(vec1, vec1);
7344     vpxor(vec2, vec2);
7345     movl(tmp, cnt1);
7346     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7347     andl(cnt1,0x0000000F);  //tail count (in chars)
7348 
7349     bind(SCAN_TO_16_CHAR_LOOP);
7350     vmovdqu(vec3, Address(result, 0));
7351     vpcmpeqw(vec3, vec3, vec1, 1);
7352     vptest(vec2, vec3);
7353     jcc(Assembler::carryClear, FOUND_CHAR);
7354     addptr(result, 32);
7355     subl(tmp, 2*stride);
7356     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7357     jmp(SCAN_TO_8_CHAR);
7358     bind(SCAN_TO_8_CHAR_INIT);
7359     movdl(vec1, ch);
7360     pshuflw(vec1, vec1, 0x00);
7361     pshufd(vec1, vec1, 0);
7362     pxor(vec2, vec2);
7363   }
7364   bind(SCAN_TO_8_CHAR);
7365   cmpl(cnt1, stride);
7366   if (UseAVX >= 2) {
7367     jcc(Assembler::less, SCAN_TO_CHAR);
7368   } else {
7369     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7370     movdl(vec1, ch);
7371     pshuflw(vec1, vec1, 0x00);
7372     pshufd(vec1, vec1, 0);
7373     pxor(vec2, vec2);
7374   }
7375   movl(tmp, cnt1);
7376   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7377   andl(cnt1,0x00000007);  //tail count (in chars)
7378 
7379   bind(SCAN_TO_8_CHAR_LOOP);
7380   movdqu(vec3, Address(result, 0));
7381   pcmpeqw(vec3, vec1);
7382   ptest(vec2, vec3);
7383   jcc(Assembler::carryClear, FOUND_CHAR);
7384   addptr(result, 16);
7385   subl(tmp, stride);
7386   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7387   bind(SCAN_TO_CHAR);
7388   testl(cnt1, cnt1);
7389   jcc(Assembler::zero, RET_NOT_FOUND);
7390   bind(SCAN_TO_CHAR_LOOP);
7391   load_unsigned_short(tmp, Address(result, 0));
7392   cmpl(ch, tmp);
7393   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7394   addptr(result, 2);
7395   subl(cnt1, 1);
7396   jccb(Assembler::zero, RET_NOT_FOUND);
7397   jmp(SCAN_TO_CHAR_LOOP);
7398 
7399   bind(RET_NOT_FOUND);
7400   movl(result, -1);
7401   jmpb(DONE_LABEL);
7402 
7403   bind(FOUND_CHAR);
7404   if (UseAVX >= 2) {
7405     vpmovmskb(tmp, vec3);
7406   } else {
7407     pmovmskb(tmp, vec3);
7408   }
7409   bsfl(ch, tmp);
7410   addl(result, ch);
7411 
7412   bind(FOUND_SEQ_CHAR);
7413   subptr(result, str1);
7414   shrl(result, 1);
7415 
7416   bind(DONE_LABEL);
7417 } // string_indexof_char
7418 
7419 // helper function for string_compare
7420 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7421                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7422                                         Address::ScaleFactor scale2, Register index, int ae) {
7423   if (ae == StrIntrinsicNode::LL) {
7424     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7425     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7426   } else if (ae == StrIntrinsicNode::UU) {
7427     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7428     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7429   } else {
7430     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7431     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7432   }
7433 }
7434 
7435 // Compare strings, used for char[] and byte[].
7436 void MacroAssembler::string_compare(Register str1, Register str2,
7437                                     Register cnt1, Register cnt2, Register result,
7438                                     XMMRegister vec1, int ae) {
7439   ShortBranchVerifier sbv(this);
7440   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7441   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7442   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7443   int stride2x2 = 0x40;
7444   Address::ScaleFactor scale = Address::no_scale;
7445   Address::ScaleFactor scale1 = Address::no_scale;
7446   Address::ScaleFactor scale2 = Address::no_scale;
7447 
7448   if (ae != StrIntrinsicNode::LL) {
7449     stride2x2 = 0x20;
7450   }
7451 
7452   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7453     shrl(cnt2, 1);
7454   }
7455   // Compute the minimum of the string lengths and the
7456   // difference of the string lengths (stack).
7457   // Do the conditional move stuff
7458   movl(result, cnt1);
7459   subl(cnt1, cnt2);
7460   push(cnt1);
7461   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7462 
7463   // Is the minimum length zero?
7464   testl(cnt2, cnt2);
7465   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7466   if (ae == StrIntrinsicNode::LL) {
7467     // Load first bytes
7468     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7469     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7470   } else if (ae == StrIntrinsicNode::UU) {
7471     // Load first characters
7472     load_unsigned_short(result, Address(str1, 0));
7473     load_unsigned_short(cnt1, Address(str2, 0));
7474   } else {
7475     load_unsigned_byte(result, Address(str1, 0));
7476     load_unsigned_short(cnt1, Address(str2, 0));
7477   }
7478   subl(result, cnt1);
7479   jcc(Assembler::notZero,  POP_LABEL);
7480 
7481   if (ae == StrIntrinsicNode::UU) {
7482     // Divide length by 2 to get number of chars
7483     shrl(cnt2, 1);
7484   }
7485   cmpl(cnt2, 1);
7486   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7487 
7488   // Check if the strings start at the same location and setup scale and stride
7489   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7490     cmpptr(str1, str2);
7491     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7492     if (ae == StrIntrinsicNode::LL) {
7493       scale = Address::times_1;
7494       stride = 16;
7495     } else {
7496       scale = Address::times_2;
7497       stride = 8;
7498     }
7499   } else {
7500     scale1 = Address::times_1;
7501     scale2 = Address::times_2;
7502     // scale not used
7503     stride = 8;
7504   }
7505 
7506   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7507     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7508     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7509     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7510     Label COMPARE_TAIL_LONG;
7511     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7512 
7513     int pcmpmask = 0x19;
7514     if (ae == StrIntrinsicNode::LL) {
7515       pcmpmask &= ~0x01;
7516     }
7517 
7518     // Setup to compare 16-chars (32-bytes) vectors,
7519     // start from first character again because it has aligned address.
7520     if (ae == StrIntrinsicNode::LL) {
7521       stride2 = 32;
7522     } else {
7523       stride2 = 16;
7524     }
7525     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7526       adr_stride = stride << scale;
7527     } else {
7528       adr_stride1 = 8;  //stride << scale1;
7529       adr_stride2 = 16; //stride << scale2;
7530     }
7531 
7532     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7533     // rax and rdx are used by pcmpestri as elements counters
7534     movl(result, cnt2);
7535     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7536     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7537 
7538     // fast path : compare first 2 8-char vectors.
7539     bind(COMPARE_16_CHARS);
7540     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7541       movdqu(vec1, Address(str1, 0));
7542     } else {
7543       pmovzxbw(vec1, Address(str1, 0));
7544     }
7545     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7546     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7547 
7548     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7549       movdqu(vec1, Address(str1, adr_stride));
7550       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7551     } else {
7552       pmovzxbw(vec1, Address(str1, adr_stride1));
7553       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7554     }
7555     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7556     addl(cnt1, stride);
7557 
7558     // Compare the characters at index in cnt1
7559     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7560     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7561     subl(result, cnt2);
7562     jmp(POP_LABEL);
7563 
7564     // Setup the registers to start vector comparison loop
7565     bind(COMPARE_WIDE_VECTORS);
7566     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7567       lea(str1, Address(str1, result, scale));
7568       lea(str2, Address(str2, result, scale));
7569     } else {
7570       lea(str1, Address(str1, result, scale1));
7571       lea(str2, Address(str2, result, scale2));
7572     }
7573     subl(result, stride2);
7574     subl(cnt2, stride2);
7575     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7576     negptr(result);
7577 
7578     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7579     bind(COMPARE_WIDE_VECTORS_LOOP);
7580 
7581 #ifdef _LP64
7582     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7583       cmpl(cnt2, stride2x2);
7584       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7585       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7586       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7587 
7588       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7589       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7590         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7591         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7592       } else {
7593         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7594         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7595       }
7596       kortestql(k7, k7);
7597       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7598       addptr(result, stride2x2);  // update since we already compared at this addr
7599       subl(cnt2, stride2x2);      // and sub the size too
7600       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7601 
7602       vpxor(vec1, vec1);
7603       jmpb(COMPARE_WIDE_TAIL);
7604     }//if (VM_Version::supports_avx512vlbw())
7605 #endif // _LP64
7606 
7607 
7608     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7609     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7610       vmovdqu(vec1, Address(str1, result, scale));
7611       vpxor(vec1, Address(str2, result, scale));
7612     } else {
7613       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7614       vpxor(vec1, Address(str2, result, scale2));
7615     }
7616     vptest(vec1, vec1);
7617     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7618     addptr(result, stride2);
7619     subl(cnt2, stride2);
7620     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7621     // clean upper bits of YMM registers
7622     vpxor(vec1, vec1);
7623 
7624     // compare wide vectors tail
7625     bind(COMPARE_WIDE_TAIL);
7626     testptr(result, result);
7627     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7628 
7629     movl(result, stride2);
7630     movl(cnt2, result);
7631     negptr(result);
7632     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7633 
7634     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7635     bind(VECTOR_NOT_EQUAL);
7636     // clean upper bits of YMM registers
7637     vpxor(vec1, vec1);
7638     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7639       lea(str1, Address(str1, result, scale));
7640       lea(str2, Address(str2, result, scale));
7641     } else {
7642       lea(str1, Address(str1, result, scale1));
7643       lea(str2, Address(str2, result, scale2));
7644     }
7645     jmp(COMPARE_16_CHARS);
7646 
7647     // Compare tail chars, length between 1 to 15 chars
7648     bind(COMPARE_TAIL_LONG);
7649     movl(cnt2, result);
7650     cmpl(cnt2, stride);
7651     jcc(Assembler::less, COMPARE_SMALL_STR);
7652 
7653     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7654       movdqu(vec1, Address(str1, 0));
7655     } else {
7656       pmovzxbw(vec1, Address(str1, 0));
7657     }
7658     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7659     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7660     subptr(cnt2, stride);
7661     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7662     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7663       lea(str1, Address(str1, result, scale));
7664       lea(str2, Address(str2, result, scale));
7665     } else {
7666       lea(str1, Address(str1, result, scale1));
7667       lea(str2, Address(str2, result, scale2));
7668     }
7669     negptr(cnt2);
7670     jmpb(WHILE_HEAD_LABEL);
7671 
7672     bind(COMPARE_SMALL_STR);
7673   } else if (UseSSE42Intrinsics) {
7674     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7675     int pcmpmask = 0x19;
7676     // Setup to compare 8-char (16-byte) vectors,
7677     // start from first character again because it has aligned address.
7678     movl(result, cnt2);
7679     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7680     if (ae == StrIntrinsicNode::LL) {
7681       pcmpmask &= ~0x01;
7682     }
7683     jcc(Assembler::zero, COMPARE_TAIL);
7684     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7685       lea(str1, Address(str1, result, scale));
7686       lea(str2, Address(str2, result, scale));
7687     } else {
7688       lea(str1, Address(str1, result, scale1));
7689       lea(str2, Address(str2, result, scale2));
7690     }
7691     negptr(result);
7692 
7693     // pcmpestri
7694     //   inputs:
7695     //     vec1- substring
7696     //     rax - negative string length (elements count)
7697     //     mem - scanned string
7698     //     rdx - string length (elements count)
7699     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7700     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7701     //   outputs:
7702     //     rcx - first mismatched element index
7703     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7704 
7705     bind(COMPARE_WIDE_VECTORS);
7706     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7707       movdqu(vec1, Address(str1, result, scale));
7708       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7709     } else {
7710       pmovzxbw(vec1, Address(str1, result, scale1));
7711       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7712     }
7713     // After pcmpestri cnt1(rcx) contains mismatched element index
7714 
7715     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7716     addptr(result, stride);
7717     subptr(cnt2, stride);
7718     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7719 
7720     // compare wide vectors tail
7721     testptr(result, result);
7722     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7723 
7724     movl(cnt2, stride);
7725     movl(result, stride);
7726     negptr(result);
7727     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7728       movdqu(vec1, Address(str1, result, scale));
7729       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7730     } else {
7731       pmovzxbw(vec1, Address(str1, result, scale1));
7732       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7733     }
7734     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7735 
7736     // Mismatched characters in the vectors
7737     bind(VECTOR_NOT_EQUAL);
7738     addptr(cnt1, result);
7739     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7740     subl(result, cnt2);
7741     jmpb(POP_LABEL);
7742 
7743     bind(COMPARE_TAIL); // limit is zero
7744     movl(cnt2, result);
7745     // Fallthru to tail compare
7746   }
7747   // Shift str2 and str1 to the end of the arrays, negate min
7748   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7749     lea(str1, Address(str1, cnt2, scale));
7750     lea(str2, Address(str2, cnt2, scale));
7751   } else {
7752     lea(str1, Address(str1, cnt2, scale1));
7753     lea(str2, Address(str2, cnt2, scale2));
7754   }
7755   decrementl(cnt2);  // first character was compared already
7756   negptr(cnt2);
7757 
7758   // Compare the rest of the elements
7759   bind(WHILE_HEAD_LABEL);
7760   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7761   subl(result, cnt1);
7762   jccb(Assembler::notZero, POP_LABEL);
7763   increment(cnt2);
7764   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7765 
7766   // Strings are equal up to min length.  Return the length difference.
7767   bind(LENGTH_DIFF_LABEL);
7768   pop(result);
7769   if (ae == StrIntrinsicNode::UU) {
7770     // Divide diff by 2 to get number of chars
7771     sarl(result, 1);
7772   }
7773   jmpb(DONE_LABEL);
7774 
7775 #ifdef _LP64
7776   if (VM_Version::supports_avx512vlbw()) {
7777 
7778     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7779 
7780     kmovql(cnt1, k7);
7781     notq(cnt1);
7782     bsfq(cnt2, cnt1);
7783     if (ae != StrIntrinsicNode::LL) {
7784       // Divide diff by 2 to get number of chars
7785       sarl(cnt2, 1);
7786     }
7787     addq(result, cnt2);
7788     if (ae == StrIntrinsicNode::LL) {
7789       load_unsigned_byte(cnt1, Address(str2, result));
7790       load_unsigned_byte(result, Address(str1, result));
7791     } else if (ae == StrIntrinsicNode::UU) {
7792       load_unsigned_short(cnt1, Address(str2, result, scale));
7793       load_unsigned_short(result, Address(str1, result, scale));
7794     } else {
7795       load_unsigned_short(cnt1, Address(str2, result, scale2));
7796       load_unsigned_byte(result, Address(str1, result, scale1));
7797     }
7798     subl(result, cnt1);
7799     jmpb(POP_LABEL);
7800   }//if (VM_Version::supports_avx512vlbw())
7801 #endif // _LP64
7802 
7803   // Discard the stored length difference
7804   bind(POP_LABEL);
7805   pop(cnt1);
7806 
7807   // That's it
7808   bind(DONE_LABEL);
7809   if(ae == StrIntrinsicNode::UL) {
7810     negl(result);
7811   }
7812 
7813 }
7814 
7815 // Search for Non-ASCII character (Negative byte value) in a byte array,
7816 // return true if it has any and false otherwise.
7817 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7818 //   @HotSpotIntrinsicCandidate
7819 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7820 //     for (int i = off; i < off + len; i++) {
7821 //       if (ba[i] < 0) {
7822 //         return true;
7823 //       }
7824 //     }
7825 //     return false;
7826 //   }
7827 void MacroAssembler::has_negatives(Register ary1, Register len,
7828   Register result, Register tmp1,
7829   XMMRegister vec1, XMMRegister vec2) {
7830   // rsi: byte array
7831   // rcx: len
7832   // rax: result
7833   ShortBranchVerifier sbv(this);
7834   assert_different_registers(ary1, len, result, tmp1);
7835   assert_different_registers(vec1, vec2);
7836   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7837 
7838   // len == 0
7839   testl(len, len);
7840   jcc(Assembler::zero, FALSE_LABEL);
7841 
7842   if ((UseAVX > 2) && // AVX512
7843     VM_Version::supports_avx512vlbw() &&
7844     VM_Version::supports_bmi2()) {
7845 
7846     set_vector_masking();  // opening of the stub context for programming mask registers
7847 
7848     Label test_64_loop, test_tail;
7849     Register tmp3_aliased = len;
7850 
7851     movl(tmp1, len);
7852     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7853 
7854     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7855     andl(len, ~(64 - 1));    // vector count (in chars)
7856     jccb(Assembler::zero, test_tail);
7857 
7858     lea(ary1, Address(ary1, len, Address::times_1));
7859     negptr(len);
7860 
7861     bind(test_64_loop);
7862     // Check whether our 64 elements of size byte contain negatives
7863     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7864     kortestql(k2, k2);
7865     jcc(Assembler::notZero, TRUE_LABEL);
7866 
7867     addptr(len, 64);
7868     jccb(Assembler::notZero, test_64_loop);
7869 
7870 
7871     bind(test_tail);
7872     // bail out when there is nothing to be done
7873     testl(tmp1, -1);
7874     jcc(Assembler::zero, FALSE_LABEL);
7875 
7876     // Save k1
7877     kmovql(k3, k1);
7878 
7879     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7880 #ifdef _LP64
7881     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7882     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7883     notq(tmp3_aliased);
7884     kmovql(k1, tmp3_aliased);
7885 #else
7886     Label k_init;
7887     jmp(k_init);
7888 
7889     // We could not read 64-bits from a general purpose register thus we move
7890     // data required to compose 64 1's to the instruction stream
7891     // We emit 64 byte wide series of elements from 0..63 which later on would
7892     // be used as a compare targets with tail count contained in tmp1 register.
7893     // Result would be a k1 register having tmp1 consecutive number or 1
7894     // counting from least significant bit.
7895     address tmp = pc();
7896     emit_int64(0x0706050403020100);
7897     emit_int64(0x0F0E0D0C0B0A0908);
7898     emit_int64(0x1716151413121110);
7899     emit_int64(0x1F1E1D1C1B1A1918);
7900     emit_int64(0x2726252423222120);
7901     emit_int64(0x2F2E2D2C2B2A2928);
7902     emit_int64(0x3736353433323130);
7903     emit_int64(0x3F3E3D3C3B3A3938);
7904 
7905     bind(k_init);
7906     lea(len, InternalAddress(tmp));
7907     // create mask to test for negative byte inside a vector
7908     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7909     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7910 
7911 #endif
7912     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7913     ktestq(k2, k1);
7914     // Restore k1
7915     kmovql(k1, k3);
7916     jcc(Assembler::notZero, TRUE_LABEL);
7917 
7918     jmp(FALSE_LABEL);
7919 
7920     clear_vector_masking();   // closing of the stub context for programming mask registers
7921   } else {
7922     movl(result, len); // copy
7923 
7924     if (UseAVX == 2 && UseSSE >= 2) {
7925       // With AVX2, use 32-byte vector compare
7926       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7927 
7928       // Compare 32-byte vectors
7929       andl(result, 0x0000001f);  //   tail count (in bytes)
7930       andl(len, 0xffffffe0);   // vector count (in bytes)
7931       jccb(Assembler::zero, COMPARE_TAIL);
7932 
7933       lea(ary1, Address(ary1, len, Address::times_1));
7934       negptr(len);
7935 
7936       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7937       movdl(vec2, tmp1);
7938       vpbroadcastd(vec2, vec2);
7939 
7940       bind(COMPARE_WIDE_VECTORS);
7941       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7942       vptest(vec1, vec2);
7943       jccb(Assembler::notZero, TRUE_LABEL);
7944       addptr(len, 32);
7945       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7946 
7947       testl(result, result);
7948       jccb(Assembler::zero, FALSE_LABEL);
7949 
7950       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7951       vptest(vec1, vec2);
7952       jccb(Assembler::notZero, TRUE_LABEL);
7953       jmpb(FALSE_LABEL);
7954 
7955       bind(COMPARE_TAIL); // len is zero
7956       movl(len, result);
7957       // Fallthru to tail compare
7958     } else if (UseSSE42Intrinsics) {
7959       // With SSE4.2, use double quad vector compare
7960       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7961 
7962       // Compare 16-byte vectors
7963       andl(result, 0x0000000f);  //   tail count (in bytes)
7964       andl(len, 0xfffffff0);   // vector count (in bytes)
7965       jccb(Assembler::zero, COMPARE_TAIL);
7966 
7967       lea(ary1, Address(ary1, len, Address::times_1));
7968       negptr(len);
7969 
7970       movl(tmp1, 0x80808080);
7971       movdl(vec2, tmp1);
7972       pshufd(vec2, vec2, 0);
7973 
7974       bind(COMPARE_WIDE_VECTORS);
7975       movdqu(vec1, Address(ary1, len, Address::times_1));
7976       ptest(vec1, vec2);
7977       jccb(Assembler::notZero, TRUE_LABEL);
7978       addptr(len, 16);
7979       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7980 
7981       testl(result, result);
7982       jccb(Assembler::zero, FALSE_LABEL);
7983 
7984       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7985       ptest(vec1, vec2);
7986       jccb(Assembler::notZero, TRUE_LABEL);
7987       jmpb(FALSE_LABEL);
7988 
7989       bind(COMPARE_TAIL); // len is zero
7990       movl(len, result);
7991       // Fallthru to tail compare
7992     }
7993   }
7994   // Compare 4-byte vectors
7995   andl(len, 0xfffffffc); // vector count (in bytes)
7996   jccb(Assembler::zero, COMPARE_CHAR);
7997 
7998   lea(ary1, Address(ary1, len, Address::times_1));
7999   negptr(len);
8000 
8001   bind(COMPARE_VECTORS);
8002   movl(tmp1, Address(ary1, len, Address::times_1));
8003   andl(tmp1, 0x80808080);
8004   jccb(Assembler::notZero, TRUE_LABEL);
8005   addptr(len, 4);
8006   jcc(Assembler::notZero, COMPARE_VECTORS);
8007 
8008   // Compare trailing char (final 2 bytes), if any
8009   bind(COMPARE_CHAR);
8010   testl(result, 0x2);   // tail  char
8011   jccb(Assembler::zero, COMPARE_BYTE);
8012   load_unsigned_short(tmp1, Address(ary1, 0));
8013   andl(tmp1, 0x00008080);
8014   jccb(Assembler::notZero, TRUE_LABEL);
8015   subptr(result, 2);
8016   lea(ary1, Address(ary1, 2));
8017 
8018   bind(COMPARE_BYTE);
8019   testl(result, 0x1);   // tail  byte
8020   jccb(Assembler::zero, FALSE_LABEL);
8021   load_unsigned_byte(tmp1, Address(ary1, 0));
8022   andl(tmp1, 0x00000080);
8023   jccb(Assembler::notEqual, TRUE_LABEL);
8024   jmpb(FALSE_LABEL);
8025 
8026   bind(TRUE_LABEL);
8027   movl(result, 1);   // return true
8028   jmpb(DONE);
8029 
8030   bind(FALSE_LABEL);
8031   xorl(result, result); // return false
8032 
8033   // That's it
8034   bind(DONE);
8035   if (UseAVX >= 2 && UseSSE >= 2) {
8036     // clean upper bits of YMM registers
8037     vpxor(vec1, vec1);
8038     vpxor(vec2, vec2);
8039   }
8040 }
8041 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8042 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8043                                    Register limit, Register result, Register chr,
8044                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8045   ShortBranchVerifier sbv(this);
8046   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8047 
8048   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8049   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8050 
8051   if (is_array_equ) {
8052     // Check the input args
8053     cmpoop(ary1, ary2);
8054     jcc(Assembler::equal, TRUE_LABEL);
8055 
8056     // Need additional checks for arrays_equals.
8057     testptr(ary1, ary1);
8058     jcc(Assembler::zero, FALSE_LABEL);
8059     testptr(ary2, ary2);
8060     jcc(Assembler::zero, FALSE_LABEL);
8061 
8062     // Check the lengths
8063     movl(limit, Address(ary1, length_offset));
8064     cmpl(limit, Address(ary2, length_offset));
8065     jcc(Assembler::notEqual, FALSE_LABEL);
8066   }
8067 
8068   // count == 0
8069   testl(limit, limit);
8070   jcc(Assembler::zero, TRUE_LABEL);
8071 
8072   if (is_array_equ) {
8073     // Load array address
8074     lea(ary1, Address(ary1, base_offset));
8075     lea(ary2, Address(ary2, base_offset));
8076   }
8077 
8078   if (is_array_equ && is_char) {
8079     // arrays_equals when used for char[].
8080     shll(limit, 1);      // byte count != 0
8081   }
8082   movl(result, limit); // copy
8083 
8084   if (UseAVX >= 2) {
8085     // With AVX2, use 32-byte vector compare
8086     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8087 
8088     // Compare 32-byte vectors
8089     andl(result, 0x0000001f);  //   tail count (in bytes)
8090     andl(limit, 0xffffffe0);   // vector count (in bytes)
8091     jcc(Assembler::zero, COMPARE_TAIL);
8092 
8093     lea(ary1, Address(ary1, limit, Address::times_1));
8094     lea(ary2, Address(ary2, limit, Address::times_1));
8095     negptr(limit);
8096 
8097     bind(COMPARE_WIDE_VECTORS);
8098 
8099 #ifdef _LP64
8100     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8101       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8102 
8103       cmpl(limit, -64);
8104       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8105 
8106       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8107 
8108       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8109       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8110       kortestql(k7, k7);
8111       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8112       addptr(limit, 64);  // update since we already compared at this addr
8113       cmpl(limit, -64);
8114       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8115 
8116       // At this point we may still need to compare -limit+result bytes.
8117       // We could execute the next two instruction and just continue via non-wide path:
8118       //  cmpl(limit, 0);
8119       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8120       // But since we stopped at the points ary{1,2}+limit which are
8121       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8122       // (|limit| <= 32 and result < 32),
8123       // we may just compare the last 64 bytes.
8124       //
8125       addptr(result, -64);   // it is safe, bc we just came from this area
8126       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8127       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8128       kortestql(k7, k7);
8129       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8130 
8131       jmp(TRUE_LABEL);
8132 
8133       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8134 
8135     }//if (VM_Version::supports_avx512vlbw())
8136 #endif //_LP64
8137 
8138     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8139     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8140     vpxor(vec1, vec2);
8141 
8142     vptest(vec1, vec1);
8143     jcc(Assembler::notZero, FALSE_LABEL);
8144     addptr(limit, 32);
8145     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8146 
8147     testl(result, result);
8148     jcc(Assembler::zero, TRUE_LABEL);
8149 
8150     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8151     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8152     vpxor(vec1, vec2);
8153 
8154     vptest(vec1, vec1);
8155     jccb(Assembler::notZero, FALSE_LABEL);
8156     jmpb(TRUE_LABEL);
8157 
8158     bind(COMPARE_TAIL); // limit is zero
8159     movl(limit, result);
8160     // Fallthru to tail compare
8161   } else if (UseSSE42Intrinsics) {
8162     // With SSE4.2, use double quad vector compare
8163     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8164 
8165     // Compare 16-byte vectors
8166     andl(result, 0x0000000f);  //   tail count (in bytes)
8167     andl(limit, 0xfffffff0);   // vector count (in bytes)
8168     jcc(Assembler::zero, COMPARE_TAIL);
8169 
8170     lea(ary1, Address(ary1, limit, Address::times_1));
8171     lea(ary2, Address(ary2, limit, Address::times_1));
8172     negptr(limit);
8173 
8174     bind(COMPARE_WIDE_VECTORS);
8175     movdqu(vec1, Address(ary1, limit, Address::times_1));
8176     movdqu(vec2, Address(ary2, limit, Address::times_1));
8177     pxor(vec1, vec2);
8178 
8179     ptest(vec1, vec1);
8180     jcc(Assembler::notZero, FALSE_LABEL);
8181     addptr(limit, 16);
8182     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8183 
8184     testl(result, result);
8185     jcc(Assembler::zero, TRUE_LABEL);
8186 
8187     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8188     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8189     pxor(vec1, vec2);
8190 
8191     ptest(vec1, vec1);
8192     jccb(Assembler::notZero, FALSE_LABEL);
8193     jmpb(TRUE_LABEL);
8194 
8195     bind(COMPARE_TAIL); // limit is zero
8196     movl(limit, result);
8197     // Fallthru to tail compare
8198   }
8199 
8200   // Compare 4-byte vectors
8201   andl(limit, 0xfffffffc); // vector count (in bytes)
8202   jccb(Assembler::zero, COMPARE_CHAR);
8203 
8204   lea(ary1, Address(ary1, limit, Address::times_1));
8205   lea(ary2, Address(ary2, limit, Address::times_1));
8206   negptr(limit);
8207 
8208   bind(COMPARE_VECTORS);
8209   movl(chr, Address(ary1, limit, Address::times_1));
8210   cmpl(chr, Address(ary2, limit, Address::times_1));
8211   jccb(Assembler::notEqual, FALSE_LABEL);
8212   addptr(limit, 4);
8213   jcc(Assembler::notZero, COMPARE_VECTORS);
8214 
8215   // Compare trailing char (final 2 bytes), if any
8216   bind(COMPARE_CHAR);
8217   testl(result, 0x2);   // tail  char
8218   jccb(Assembler::zero, COMPARE_BYTE);
8219   load_unsigned_short(chr, Address(ary1, 0));
8220   load_unsigned_short(limit, Address(ary2, 0));
8221   cmpl(chr, limit);
8222   jccb(Assembler::notEqual, FALSE_LABEL);
8223 
8224   if (is_array_equ && is_char) {
8225     bind(COMPARE_BYTE);
8226   } else {
8227     lea(ary1, Address(ary1, 2));
8228     lea(ary2, Address(ary2, 2));
8229 
8230     bind(COMPARE_BYTE);
8231     testl(result, 0x1);   // tail  byte
8232     jccb(Assembler::zero, TRUE_LABEL);
8233     load_unsigned_byte(chr, Address(ary1, 0));
8234     load_unsigned_byte(limit, Address(ary2, 0));
8235     cmpl(chr, limit);
8236     jccb(Assembler::notEqual, FALSE_LABEL);
8237   }
8238   bind(TRUE_LABEL);
8239   movl(result, 1);   // return true
8240   jmpb(DONE);
8241 
8242   bind(FALSE_LABEL);
8243   xorl(result, result); // return false
8244 
8245   // That's it
8246   bind(DONE);
8247   if (UseAVX >= 2) {
8248     // clean upper bits of YMM registers
8249     vpxor(vec1, vec1);
8250     vpxor(vec2, vec2);
8251   }
8252 }
8253 
8254 #endif
8255 
8256 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8257                                    Register to, Register value, Register count,
8258                                    Register rtmp, XMMRegister xtmp) {
8259   ShortBranchVerifier sbv(this);
8260   assert_different_registers(to, value, count, rtmp);
8261   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8262   Label L_fill_2_bytes, L_fill_4_bytes;
8263 
8264   int shift = -1;
8265   switch (t) {
8266     case T_BYTE:
8267       shift = 2;
8268       break;
8269     case T_SHORT:
8270       shift = 1;
8271       break;
8272     case T_INT:
8273       shift = 0;
8274       break;
8275     default: ShouldNotReachHere();
8276   }
8277 
8278   if (t == T_BYTE) {
8279     andl(value, 0xff);
8280     movl(rtmp, value);
8281     shll(rtmp, 8);
8282     orl(value, rtmp);
8283   }
8284   if (t == T_SHORT) {
8285     andl(value, 0xffff);
8286   }
8287   if (t == T_BYTE || t == T_SHORT) {
8288     movl(rtmp, value);
8289     shll(rtmp, 16);
8290     orl(value, rtmp);
8291   }
8292 
8293   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8294   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8295   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8296     // align source address at 4 bytes address boundary
8297     if (t == T_BYTE) {
8298       // One byte misalignment happens only for byte arrays
8299       testptr(to, 1);
8300       jccb(Assembler::zero, L_skip_align1);
8301       movb(Address(to, 0), value);
8302       increment(to);
8303       decrement(count);
8304       BIND(L_skip_align1);
8305     }
8306     // Two bytes misalignment happens only for byte and short (char) arrays
8307     testptr(to, 2);
8308     jccb(Assembler::zero, L_skip_align2);
8309     movw(Address(to, 0), value);
8310     addptr(to, 2);
8311     subl(count, 1<<(shift-1));
8312     BIND(L_skip_align2);
8313   }
8314   if (UseSSE < 2) {
8315     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8316     // Fill 32-byte chunks
8317     subl(count, 8 << shift);
8318     jcc(Assembler::less, L_check_fill_8_bytes);
8319     align(16);
8320 
8321     BIND(L_fill_32_bytes_loop);
8322 
8323     for (int i = 0; i < 32; i += 4) {
8324       movl(Address(to, i), value);
8325     }
8326 
8327     addptr(to, 32);
8328     subl(count, 8 << shift);
8329     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8330     BIND(L_check_fill_8_bytes);
8331     addl(count, 8 << shift);
8332     jccb(Assembler::zero, L_exit);
8333     jmpb(L_fill_8_bytes);
8334 
8335     //
8336     // length is too short, just fill qwords
8337     //
8338     BIND(L_fill_8_bytes_loop);
8339     movl(Address(to, 0), value);
8340     movl(Address(to, 4), value);
8341     addptr(to, 8);
8342     BIND(L_fill_8_bytes);
8343     subl(count, 1 << (shift + 1));
8344     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8345     // fall through to fill 4 bytes
8346   } else {
8347     Label L_fill_32_bytes;
8348     if (!UseUnalignedLoadStores) {
8349       // align to 8 bytes, we know we are 4 byte aligned to start
8350       testptr(to, 4);
8351       jccb(Assembler::zero, L_fill_32_bytes);
8352       movl(Address(to, 0), value);
8353       addptr(to, 4);
8354       subl(count, 1<<shift);
8355     }
8356     BIND(L_fill_32_bytes);
8357     {
8358       assert( UseSSE >= 2, "supported cpu only" );
8359       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8360       if (UseAVX > 2) {
8361         movl(rtmp, 0xffff);
8362         kmovwl(k1, rtmp);
8363       }
8364       movdl(xtmp, value);
8365       if (UseAVX > 2 && UseUnalignedLoadStores) {
8366         // Fill 64-byte chunks
8367         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8368         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8369 
8370         subl(count, 16 << shift);
8371         jcc(Assembler::less, L_check_fill_32_bytes);
8372         align(16);
8373 
8374         BIND(L_fill_64_bytes_loop);
8375         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8376         addptr(to, 64);
8377         subl(count, 16 << shift);
8378         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8379 
8380         BIND(L_check_fill_32_bytes);
8381         addl(count, 8 << shift);
8382         jccb(Assembler::less, L_check_fill_8_bytes);
8383         vmovdqu(Address(to, 0), xtmp);
8384         addptr(to, 32);
8385         subl(count, 8 << shift);
8386 
8387         BIND(L_check_fill_8_bytes);
8388       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8389         // Fill 64-byte chunks
8390         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8391         vpbroadcastd(xtmp, xtmp);
8392 
8393         subl(count, 16 << shift);
8394         jcc(Assembler::less, L_check_fill_32_bytes);
8395         align(16);
8396 
8397         BIND(L_fill_64_bytes_loop);
8398         vmovdqu(Address(to, 0), xtmp);
8399         vmovdqu(Address(to, 32), xtmp);
8400         addptr(to, 64);
8401         subl(count, 16 << shift);
8402         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8403 
8404         BIND(L_check_fill_32_bytes);
8405         addl(count, 8 << shift);
8406         jccb(Assembler::less, L_check_fill_8_bytes);
8407         vmovdqu(Address(to, 0), xtmp);
8408         addptr(to, 32);
8409         subl(count, 8 << shift);
8410 
8411         BIND(L_check_fill_8_bytes);
8412         // clean upper bits of YMM registers
8413         movdl(xtmp, value);
8414         pshufd(xtmp, xtmp, 0);
8415       } else {
8416         // Fill 32-byte chunks
8417         pshufd(xtmp, xtmp, 0);
8418 
8419         subl(count, 8 << shift);
8420         jcc(Assembler::less, L_check_fill_8_bytes);
8421         align(16);
8422 
8423         BIND(L_fill_32_bytes_loop);
8424 
8425         if (UseUnalignedLoadStores) {
8426           movdqu(Address(to, 0), xtmp);
8427           movdqu(Address(to, 16), xtmp);
8428         } else {
8429           movq(Address(to, 0), xtmp);
8430           movq(Address(to, 8), xtmp);
8431           movq(Address(to, 16), xtmp);
8432           movq(Address(to, 24), xtmp);
8433         }
8434 
8435         addptr(to, 32);
8436         subl(count, 8 << shift);
8437         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8438 
8439         BIND(L_check_fill_8_bytes);
8440       }
8441       addl(count, 8 << shift);
8442       jccb(Assembler::zero, L_exit);
8443       jmpb(L_fill_8_bytes);
8444 
8445       //
8446       // length is too short, just fill qwords
8447       //
8448       BIND(L_fill_8_bytes_loop);
8449       movq(Address(to, 0), xtmp);
8450       addptr(to, 8);
8451       BIND(L_fill_8_bytes);
8452       subl(count, 1 << (shift + 1));
8453       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8454     }
8455   }
8456   // fill trailing 4 bytes
8457   BIND(L_fill_4_bytes);
8458   testl(count, 1<<shift);
8459   jccb(Assembler::zero, L_fill_2_bytes);
8460   movl(Address(to, 0), value);
8461   if (t == T_BYTE || t == T_SHORT) {
8462     addptr(to, 4);
8463     BIND(L_fill_2_bytes);
8464     // fill trailing 2 bytes
8465     testl(count, 1<<(shift-1));
8466     jccb(Assembler::zero, L_fill_byte);
8467     movw(Address(to, 0), value);
8468     if (t == T_BYTE) {
8469       addptr(to, 2);
8470       BIND(L_fill_byte);
8471       // fill trailing byte
8472       testl(count, 1);
8473       jccb(Assembler::zero, L_exit);
8474       movb(Address(to, 0), value);
8475     } else {
8476       BIND(L_fill_byte);
8477     }
8478   } else {
8479     BIND(L_fill_2_bytes);
8480   }
8481   BIND(L_exit);
8482 }
8483 
8484 // encode char[] to byte[] in ISO_8859_1
8485    //@HotSpotIntrinsicCandidate
8486    //private static int implEncodeISOArray(byte[] sa, int sp,
8487    //byte[] da, int dp, int len) {
8488    //  int i = 0;
8489    //  for (; i < len; i++) {
8490    //    char c = StringUTF16.getChar(sa, sp++);
8491    //    if (c > '\u00FF')
8492    //      break;
8493    //    da[dp++] = (byte)c;
8494    //  }
8495    //  return i;
8496    //}
8497 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8498   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8499   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8500   Register tmp5, Register result) {
8501 
8502   // rsi: src
8503   // rdi: dst
8504   // rdx: len
8505   // rcx: tmp5
8506   // rax: result
8507   ShortBranchVerifier sbv(this);
8508   assert_different_registers(src, dst, len, tmp5, result);
8509   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8510 
8511   // set result
8512   xorl(result, result);
8513   // check for zero length
8514   testl(len, len);
8515   jcc(Assembler::zero, L_done);
8516 
8517   movl(result, len);
8518 
8519   // Setup pointers
8520   lea(src, Address(src, len, Address::times_2)); // char[]
8521   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8522   negptr(len);
8523 
8524   if (UseSSE42Intrinsics || UseAVX >= 2) {
8525     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8526     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8527 
8528     if (UseAVX >= 2) {
8529       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8530       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8531       movdl(tmp1Reg, tmp5);
8532       vpbroadcastd(tmp1Reg, tmp1Reg);
8533       jmp(L_chars_32_check);
8534 
8535       bind(L_copy_32_chars);
8536       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8537       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8538       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8539       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8540       jccb(Assembler::notZero, L_copy_32_chars_exit);
8541       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8542       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8543       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8544 
8545       bind(L_chars_32_check);
8546       addptr(len, 32);
8547       jcc(Assembler::lessEqual, L_copy_32_chars);
8548 
8549       bind(L_copy_32_chars_exit);
8550       subptr(len, 16);
8551       jccb(Assembler::greater, L_copy_16_chars_exit);
8552 
8553     } else if (UseSSE42Intrinsics) {
8554       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8555       movdl(tmp1Reg, tmp5);
8556       pshufd(tmp1Reg, tmp1Reg, 0);
8557       jmpb(L_chars_16_check);
8558     }
8559 
8560     bind(L_copy_16_chars);
8561     if (UseAVX >= 2) {
8562       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8563       vptest(tmp2Reg, tmp1Reg);
8564       jcc(Assembler::notZero, L_copy_16_chars_exit);
8565       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8566       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8567     } else {
8568       if (UseAVX > 0) {
8569         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8570         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8571         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8572       } else {
8573         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8574         por(tmp2Reg, tmp3Reg);
8575         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8576         por(tmp2Reg, tmp4Reg);
8577       }
8578       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8579       jccb(Assembler::notZero, L_copy_16_chars_exit);
8580       packuswb(tmp3Reg, tmp4Reg);
8581     }
8582     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8583 
8584     bind(L_chars_16_check);
8585     addptr(len, 16);
8586     jcc(Assembler::lessEqual, L_copy_16_chars);
8587 
8588     bind(L_copy_16_chars_exit);
8589     if (UseAVX >= 2) {
8590       // clean upper bits of YMM registers
8591       vpxor(tmp2Reg, tmp2Reg);
8592       vpxor(tmp3Reg, tmp3Reg);
8593       vpxor(tmp4Reg, tmp4Reg);
8594       movdl(tmp1Reg, tmp5);
8595       pshufd(tmp1Reg, tmp1Reg, 0);
8596     }
8597     subptr(len, 8);
8598     jccb(Assembler::greater, L_copy_8_chars_exit);
8599 
8600     bind(L_copy_8_chars);
8601     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8602     ptest(tmp3Reg, tmp1Reg);
8603     jccb(Assembler::notZero, L_copy_8_chars_exit);
8604     packuswb(tmp3Reg, tmp1Reg);
8605     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8606     addptr(len, 8);
8607     jccb(Assembler::lessEqual, L_copy_8_chars);
8608 
8609     bind(L_copy_8_chars_exit);
8610     subptr(len, 8);
8611     jccb(Assembler::zero, L_done);
8612   }
8613 
8614   bind(L_copy_1_char);
8615   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8616   testl(tmp5, 0xff00);      // check if Unicode char
8617   jccb(Assembler::notZero, L_copy_1_char_exit);
8618   movb(Address(dst, len, Address::times_1, 0), tmp5);
8619   addptr(len, 1);
8620   jccb(Assembler::less, L_copy_1_char);
8621 
8622   bind(L_copy_1_char_exit);
8623   addptr(result, len); // len is negative count of not processed elements
8624 
8625   bind(L_done);
8626 }
8627 
8628 #ifdef _LP64
8629 /**
8630  * Helper for multiply_to_len().
8631  */
8632 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8633   addq(dest_lo, src1);
8634   adcq(dest_hi, 0);
8635   addq(dest_lo, src2);
8636   adcq(dest_hi, 0);
8637 }
8638 
8639 /**
8640  * Multiply 64 bit by 64 bit first loop.
8641  */
8642 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8643                                            Register y, Register y_idx, Register z,
8644                                            Register carry, Register product,
8645                                            Register idx, Register kdx) {
8646   //
8647   //  jlong carry, x[], y[], z[];
8648   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8649   //    huge_128 product = y[idx] * x[xstart] + carry;
8650   //    z[kdx] = (jlong)product;
8651   //    carry  = (jlong)(product >>> 64);
8652   //  }
8653   //  z[xstart] = carry;
8654   //
8655 
8656   Label L_first_loop, L_first_loop_exit;
8657   Label L_one_x, L_one_y, L_multiply;
8658 
8659   decrementl(xstart);
8660   jcc(Assembler::negative, L_one_x);
8661 
8662   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8663   rorq(x_xstart, 32); // convert big-endian to little-endian
8664 
8665   bind(L_first_loop);
8666   decrementl(idx);
8667   jcc(Assembler::negative, L_first_loop_exit);
8668   decrementl(idx);
8669   jcc(Assembler::negative, L_one_y);
8670   movq(y_idx, Address(y, idx, Address::times_4,  0));
8671   rorq(y_idx, 32); // convert big-endian to little-endian
8672   bind(L_multiply);
8673   movq(product, x_xstart);
8674   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8675   addq(product, carry);
8676   adcq(rdx, 0);
8677   subl(kdx, 2);
8678   movl(Address(z, kdx, Address::times_4,  4), product);
8679   shrq(product, 32);
8680   movl(Address(z, kdx, Address::times_4,  0), product);
8681   movq(carry, rdx);
8682   jmp(L_first_loop);
8683 
8684   bind(L_one_y);
8685   movl(y_idx, Address(y,  0));
8686   jmp(L_multiply);
8687 
8688   bind(L_one_x);
8689   movl(x_xstart, Address(x,  0));
8690   jmp(L_first_loop);
8691 
8692   bind(L_first_loop_exit);
8693 }
8694 
8695 /**
8696  * Multiply 64 bit by 64 bit and add 128 bit.
8697  */
8698 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8699                                             Register yz_idx, Register idx,
8700                                             Register carry, Register product, int offset) {
8701   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8702   //     z[kdx] = (jlong)product;
8703 
8704   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8705   rorq(yz_idx, 32); // convert big-endian to little-endian
8706   movq(product, x_xstart);
8707   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8708   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8709   rorq(yz_idx, 32); // convert big-endian to little-endian
8710 
8711   add2_with_carry(rdx, product, carry, yz_idx);
8712 
8713   movl(Address(z, idx, Address::times_4,  offset+4), product);
8714   shrq(product, 32);
8715   movl(Address(z, idx, Address::times_4,  offset), product);
8716 
8717 }
8718 
8719 /**
8720  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8721  */
8722 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8723                                              Register yz_idx, Register idx, Register jdx,
8724                                              Register carry, Register product,
8725                                              Register carry2) {
8726   //   jlong carry, x[], y[], z[];
8727   //   int kdx = ystart+1;
8728   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8729   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8730   //     z[kdx+idx+1] = (jlong)product;
8731   //     jlong carry2  = (jlong)(product >>> 64);
8732   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8733   //     z[kdx+idx] = (jlong)product;
8734   //     carry  = (jlong)(product >>> 64);
8735   //   }
8736   //   idx += 2;
8737   //   if (idx > 0) {
8738   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8739   //     z[kdx+idx] = (jlong)product;
8740   //     carry  = (jlong)(product >>> 64);
8741   //   }
8742   //
8743 
8744   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8745 
8746   movl(jdx, idx);
8747   andl(jdx, 0xFFFFFFFC);
8748   shrl(jdx, 2);
8749 
8750   bind(L_third_loop);
8751   subl(jdx, 1);
8752   jcc(Assembler::negative, L_third_loop_exit);
8753   subl(idx, 4);
8754 
8755   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8756   movq(carry2, rdx);
8757 
8758   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8759   movq(carry, rdx);
8760   jmp(L_third_loop);
8761 
8762   bind (L_third_loop_exit);
8763 
8764   andl (idx, 0x3);
8765   jcc(Assembler::zero, L_post_third_loop_done);
8766 
8767   Label L_check_1;
8768   subl(idx, 2);
8769   jcc(Assembler::negative, L_check_1);
8770 
8771   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8772   movq(carry, rdx);
8773 
8774   bind (L_check_1);
8775   addl (idx, 0x2);
8776   andl (idx, 0x1);
8777   subl(idx, 1);
8778   jcc(Assembler::negative, L_post_third_loop_done);
8779 
8780   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8781   movq(product, x_xstart);
8782   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8783   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8784 
8785   add2_with_carry(rdx, product, yz_idx, carry);
8786 
8787   movl(Address(z, idx, Address::times_4,  0), product);
8788   shrq(product, 32);
8789 
8790   shlq(rdx, 32);
8791   orq(product, rdx);
8792   movq(carry, product);
8793 
8794   bind(L_post_third_loop_done);
8795 }
8796 
8797 /**
8798  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8799  *
8800  */
8801 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8802                                                   Register carry, Register carry2,
8803                                                   Register idx, Register jdx,
8804                                                   Register yz_idx1, Register yz_idx2,
8805                                                   Register tmp, Register tmp3, Register tmp4) {
8806   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8807 
8808   //   jlong carry, x[], y[], z[];
8809   //   int kdx = ystart+1;
8810   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8811   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8812   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8813   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8814   //     carry  = (jlong)(tmp4 >>> 64);
8815   //     z[kdx+idx+1] = (jlong)tmp3;
8816   //     z[kdx+idx] = (jlong)tmp4;
8817   //   }
8818   //   idx += 2;
8819   //   if (idx > 0) {
8820   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8821   //     z[kdx+idx] = (jlong)yz_idx1;
8822   //     carry  = (jlong)(yz_idx1 >>> 64);
8823   //   }
8824   //
8825 
8826   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8827 
8828   movl(jdx, idx);
8829   andl(jdx, 0xFFFFFFFC);
8830   shrl(jdx, 2);
8831 
8832   bind(L_third_loop);
8833   subl(jdx, 1);
8834   jcc(Assembler::negative, L_third_loop_exit);
8835   subl(idx, 4);
8836 
8837   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8838   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8839   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8840   rorxq(yz_idx2, yz_idx2, 32);
8841 
8842   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8843   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8844 
8845   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8846   rorxq(yz_idx1, yz_idx1, 32);
8847   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8848   rorxq(yz_idx2, yz_idx2, 32);
8849 
8850   if (VM_Version::supports_adx()) {
8851     adcxq(tmp3, carry);
8852     adoxq(tmp3, yz_idx1);
8853 
8854     adcxq(tmp4, tmp);
8855     adoxq(tmp4, yz_idx2);
8856 
8857     movl(carry, 0); // does not affect flags
8858     adcxq(carry2, carry);
8859     adoxq(carry2, carry);
8860   } else {
8861     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8862     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8863   }
8864   movq(carry, carry2);
8865 
8866   movl(Address(z, idx, Address::times_4, 12), tmp3);
8867   shrq(tmp3, 32);
8868   movl(Address(z, idx, Address::times_4,  8), tmp3);
8869 
8870   movl(Address(z, idx, Address::times_4,  4), tmp4);
8871   shrq(tmp4, 32);
8872   movl(Address(z, idx, Address::times_4,  0), tmp4);
8873 
8874   jmp(L_third_loop);
8875 
8876   bind (L_third_loop_exit);
8877 
8878   andl (idx, 0x3);
8879   jcc(Assembler::zero, L_post_third_loop_done);
8880 
8881   Label L_check_1;
8882   subl(idx, 2);
8883   jcc(Assembler::negative, L_check_1);
8884 
8885   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8886   rorxq(yz_idx1, yz_idx1, 32);
8887   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8888   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8889   rorxq(yz_idx2, yz_idx2, 32);
8890 
8891   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8892 
8893   movl(Address(z, idx, Address::times_4,  4), tmp3);
8894   shrq(tmp3, 32);
8895   movl(Address(z, idx, Address::times_4,  0), tmp3);
8896   movq(carry, tmp4);
8897 
8898   bind (L_check_1);
8899   addl (idx, 0x2);
8900   andl (idx, 0x1);
8901   subl(idx, 1);
8902   jcc(Assembler::negative, L_post_third_loop_done);
8903   movl(tmp4, Address(y, idx, Address::times_4,  0));
8904   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8905   movl(tmp4, Address(z, idx, Address::times_4,  0));
8906 
8907   add2_with_carry(carry2, tmp3, tmp4, carry);
8908 
8909   movl(Address(z, idx, Address::times_4,  0), tmp3);
8910   shrq(tmp3, 32);
8911 
8912   shlq(carry2, 32);
8913   orq(tmp3, carry2);
8914   movq(carry, tmp3);
8915 
8916   bind(L_post_third_loop_done);
8917 }
8918 
8919 /**
8920  * Code for BigInteger::multiplyToLen() instrinsic.
8921  *
8922  * rdi: x
8923  * rax: xlen
8924  * rsi: y
8925  * rcx: ylen
8926  * r8:  z
8927  * r11: zlen
8928  * r12: tmp1
8929  * r13: tmp2
8930  * r14: tmp3
8931  * r15: tmp4
8932  * rbx: tmp5
8933  *
8934  */
8935 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8936                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8937   ShortBranchVerifier sbv(this);
8938   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8939 
8940   push(tmp1);
8941   push(tmp2);
8942   push(tmp3);
8943   push(tmp4);
8944   push(tmp5);
8945 
8946   push(xlen);
8947   push(zlen);
8948 
8949   const Register idx = tmp1;
8950   const Register kdx = tmp2;
8951   const Register xstart = tmp3;
8952 
8953   const Register y_idx = tmp4;
8954   const Register carry = tmp5;
8955   const Register product  = xlen;
8956   const Register x_xstart = zlen;  // reuse register
8957 
8958   // First Loop.
8959   //
8960   //  final static long LONG_MASK = 0xffffffffL;
8961   //  int xstart = xlen - 1;
8962   //  int ystart = ylen - 1;
8963   //  long carry = 0;
8964   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8965   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8966   //    z[kdx] = (int)product;
8967   //    carry = product >>> 32;
8968   //  }
8969   //  z[xstart] = (int)carry;
8970   //
8971 
8972   movl(idx, ylen);      // idx = ylen;
8973   movl(kdx, zlen);      // kdx = xlen+ylen;
8974   xorq(carry, carry);   // carry = 0;
8975 
8976   Label L_done;
8977 
8978   movl(xstart, xlen);
8979   decrementl(xstart);
8980   jcc(Assembler::negative, L_done);
8981 
8982   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8983 
8984   Label L_second_loop;
8985   testl(kdx, kdx);
8986   jcc(Assembler::zero, L_second_loop);
8987 
8988   Label L_carry;
8989   subl(kdx, 1);
8990   jcc(Assembler::zero, L_carry);
8991 
8992   movl(Address(z, kdx, Address::times_4,  0), carry);
8993   shrq(carry, 32);
8994   subl(kdx, 1);
8995 
8996   bind(L_carry);
8997   movl(Address(z, kdx, Address::times_4,  0), carry);
8998 
8999   // Second and third (nested) loops.
9000   //
9001   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9002   //   carry = 0;
9003   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9004   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9005   //                    (z[k] & LONG_MASK) + carry;
9006   //     z[k] = (int)product;
9007   //     carry = product >>> 32;
9008   //   }
9009   //   z[i] = (int)carry;
9010   // }
9011   //
9012   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9013 
9014   const Register jdx = tmp1;
9015 
9016   bind(L_second_loop);
9017   xorl(carry, carry);    // carry = 0;
9018   movl(jdx, ylen);       // j = ystart+1
9019 
9020   subl(xstart, 1);       // i = xstart-1;
9021   jcc(Assembler::negative, L_done);
9022 
9023   push (z);
9024 
9025   Label L_last_x;
9026   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9027   subl(xstart, 1);       // i = xstart-1;
9028   jcc(Assembler::negative, L_last_x);
9029 
9030   if (UseBMI2Instructions) {
9031     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9032     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9033   } else {
9034     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9035     rorq(x_xstart, 32);  // convert big-endian to little-endian
9036   }
9037 
9038   Label L_third_loop_prologue;
9039   bind(L_third_loop_prologue);
9040 
9041   push (x);
9042   push (xstart);
9043   push (ylen);
9044 
9045 
9046   if (UseBMI2Instructions) {
9047     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9048   } else { // !UseBMI2Instructions
9049     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9050   }
9051 
9052   pop(ylen);
9053   pop(xlen);
9054   pop(x);
9055   pop(z);
9056 
9057   movl(tmp3, xlen);
9058   addl(tmp3, 1);
9059   movl(Address(z, tmp3, Address::times_4,  0), carry);
9060   subl(tmp3, 1);
9061   jccb(Assembler::negative, L_done);
9062 
9063   shrq(carry, 32);
9064   movl(Address(z, tmp3, Address::times_4,  0), carry);
9065   jmp(L_second_loop);
9066 
9067   // Next infrequent code is moved outside loops.
9068   bind(L_last_x);
9069   if (UseBMI2Instructions) {
9070     movl(rdx, Address(x,  0));
9071   } else {
9072     movl(x_xstart, Address(x,  0));
9073   }
9074   jmp(L_third_loop_prologue);
9075 
9076   bind(L_done);
9077 
9078   pop(zlen);
9079   pop(xlen);
9080 
9081   pop(tmp5);
9082   pop(tmp4);
9083   pop(tmp3);
9084   pop(tmp2);
9085   pop(tmp1);
9086 }
9087 
9088 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9089   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9090   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9091   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9092   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9093   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9094   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9095   Label SAME_TILL_END, DONE;
9096   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9097 
9098   //scale is in rcx in both Win64 and Unix
9099   ShortBranchVerifier sbv(this);
9100 
9101   shlq(length);
9102   xorq(result, result);
9103 
9104   if ((UseAVX > 2) &&
9105       VM_Version::supports_avx512vlbw()) {
9106     set_vector_masking();  // opening of the stub context for programming mask registers
9107     cmpq(length, 64);
9108     jcc(Assembler::less, VECTOR32_TAIL);
9109     movq(tmp1, length);
9110     andq(tmp1, 0x3F);      // tail count
9111     andq(length, ~(0x3F)); //vector count
9112 
9113     bind(VECTOR64_LOOP);
9114     // AVX512 code to compare 64 byte vectors.
9115     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9116     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9117     kortestql(k7, k7);
9118     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9119     addq(result, 64);
9120     subq(length, 64);
9121     jccb(Assembler::notZero, VECTOR64_LOOP);
9122 
9123     //bind(VECTOR64_TAIL);
9124     testq(tmp1, tmp1);
9125     jcc(Assembler::zero, SAME_TILL_END);
9126 
9127     bind(VECTOR64_TAIL);
9128     // AVX512 code to compare upto 63 byte vectors.
9129     // Save k1
9130     kmovql(k3, k1);
9131     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9132     shlxq(tmp2, tmp2, tmp1);
9133     notq(tmp2);
9134     kmovql(k1, tmp2);
9135 
9136     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9137     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9138 
9139     ktestql(k7, k1);
9140     // Restore k1
9141     kmovql(k1, k3);
9142     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9143 
9144     bind(VECTOR64_NOT_EQUAL);
9145     kmovql(tmp1, k7);
9146     notq(tmp1);
9147     tzcntq(tmp1, tmp1);
9148     addq(result, tmp1);
9149     shrq(result);
9150     jmp(DONE);
9151     bind(VECTOR32_TAIL);
9152     clear_vector_masking();   // closing of the stub context for programming mask registers
9153   }
9154 
9155   cmpq(length, 8);
9156   jcc(Assembler::equal, VECTOR8_LOOP);
9157   jcc(Assembler::less, VECTOR4_TAIL);
9158 
9159   if (UseAVX >= 2) {
9160 
9161     cmpq(length, 16);
9162     jcc(Assembler::equal, VECTOR16_LOOP);
9163     jcc(Assembler::less, VECTOR8_LOOP);
9164 
9165     cmpq(length, 32);
9166     jccb(Assembler::less, VECTOR16_TAIL);
9167 
9168     subq(length, 32);
9169     bind(VECTOR32_LOOP);
9170     vmovdqu(rymm0, Address(obja, result));
9171     vmovdqu(rymm1, Address(objb, result));
9172     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9173     vptest(rymm2, rymm2);
9174     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9175     addq(result, 32);
9176     subq(length, 32);
9177     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9178     addq(length, 32);
9179     jcc(Assembler::equal, SAME_TILL_END);
9180     //falling through if less than 32 bytes left //close the branch here.
9181 
9182     bind(VECTOR16_TAIL);
9183     cmpq(length, 16);
9184     jccb(Assembler::less, VECTOR8_TAIL);
9185     bind(VECTOR16_LOOP);
9186     movdqu(rymm0, Address(obja, result));
9187     movdqu(rymm1, Address(objb, result));
9188     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9189     ptest(rymm2, rymm2);
9190     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9191     addq(result, 16);
9192     subq(length, 16);
9193     jcc(Assembler::equal, SAME_TILL_END);
9194     //falling through if less than 16 bytes left
9195   } else {//regular intrinsics
9196 
9197     cmpq(length, 16);
9198     jccb(Assembler::less, VECTOR8_TAIL);
9199 
9200     subq(length, 16);
9201     bind(VECTOR16_LOOP);
9202     movdqu(rymm0, Address(obja, result));
9203     movdqu(rymm1, Address(objb, result));
9204     pxor(rymm0, rymm1);
9205     ptest(rymm0, rymm0);
9206     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9207     addq(result, 16);
9208     subq(length, 16);
9209     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9210     addq(length, 16);
9211     jcc(Assembler::equal, SAME_TILL_END);
9212     //falling through if less than 16 bytes left
9213   }
9214 
9215   bind(VECTOR8_TAIL);
9216   cmpq(length, 8);
9217   jccb(Assembler::less, VECTOR4_TAIL);
9218   bind(VECTOR8_LOOP);
9219   movq(tmp1, Address(obja, result));
9220   movq(tmp2, Address(objb, result));
9221   xorq(tmp1, tmp2);
9222   testq(tmp1, tmp1);
9223   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9224   addq(result, 8);
9225   subq(length, 8);
9226   jcc(Assembler::equal, SAME_TILL_END);
9227   //falling through if less than 8 bytes left
9228 
9229   bind(VECTOR4_TAIL);
9230   cmpq(length, 4);
9231   jccb(Assembler::less, BYTES_TAIL);
9232   bind(VECTOR4_LOOP);
9233   movl(tmp1, Address(obja, result));
9234   xorl(tmp1, Address(objb, result));
9235   testl(tmp1, tmp1);
9236   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9237   addq(result, 4);
9238   subq(length, 4);
9239   jcc(Assembler::equal, SAME_TILL_END);
9240   //falling through if less than 4 bytes left
9241 
9242   bind(BYTES_TAIL);
9243   bind(BYTES_LOOP);
9244   load_unsigned_byte(tmp1, Address(obja, result));
9245   load_unsigned_byte(tmp2, Address(objb, result));
9246   xorl(tmp1, tmp2);
9247   testl(tmp1, tmp1);
9248   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9249   decq(length);
9250   jccb(Assembler::zero, SAME_TILL_END);
9251   incq(result);
9252   load_unsigned_byte(tmp1, Address(obja, result));
9253   load_unsigned_byte(tmp2, Address(objb, result));
9254   xorl(tmp1, tmp2);
9255   testl(tmp1, tmp1);
9256   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9257   decq(length);
9258   jccb(Assembler::zero, SAME_TILL_END);
9259   incq(result);
9260   load_unsigned_byte(tmp1, Address(obja, result));
9261   load_unsigned_byte(tmp2, Address(objb, result));
9262   xorl(tmp1, tmp2);
9263   testl(tmp1, tmp1);
9264   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9265   jmpb(SAME_TILL_END);
9266 
9267   if (UseAVX >= 2) {
9268     bind(VECTOR32_NOT_EQUAL);
9269     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9270     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9271     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9272     vpmovmskb(tmp1, rymm0);
9273     bsfq(tmp1, tmp1);
9274     addq(result, tmp1);
9275     shrq(result);
9276     jmpb(DONE);
9277   }
9278 
9279   bind(VECTOR16_NOT_EQUAL);
9280   if (UseAVX >= 2) {
9281     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9282     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9283     pxor(rymm0, rymm2);
9284   } else {
9285     pcmpeqb(rymm2, rymm2);
9286     pxor(rymm0, rymm1);
9287     pcmpeqb(rymm0, rymm1);
9288     pxor(rymm0, rymm2);
9289   }
9290   pmovmskb(tmp1, rymm0);
9291   bsfq(tmp1, tmp1);
9292   addq(result, tmp1);
9293   shrq(result);
9294   jmpb(DONE);
9295 
9296   bind(VECTOR8_NOT_EQUAL);
9297   bind(VECTOR4_NOT_EQUAL);
9298   bsfq(tmp1, tmp1);
9299   shrq(tmp1, 3);
9300   addq(result, tmp1);
9301   bind(BYTES_NOT_EQUAL);
9302   shrq(result);
9303   jmpb(DONE);
9304 
9305   bind(SAME_TILL_END);
9306   mov64(result, -1);
9307 
9308   bind(DONE);
9309 }
9310 
9311 //Helper functions for square_to_len()
9312 
9313 /**
9314  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9315  * Preserves x and z and modifies rest of the registers.
9316  */
9317 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9318   // Perform square and right shift by 1
9319   // Handle odd xlen case first, then for even xlen do the following
9320   // jlong carry = 0;
9321   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9322   //     huge_128 product = x[j:j+1] * x[j:j+1];
9323   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9324   //     z[i+2:i+3] = (jlong)(product >>> 1);
9325   //     carry = (jlong)product;
9326   // }
9327 
9328   xorq(tmp5, tmp5);     // carry
9329   xorq(rdxReg, rdxReg);
9330   xorl(tmp1, tmp1);     // index for x
9331   xorl(tmp4, tmp4);     // index for z
9332 
9333   Label L_first_loop, L_first_loop_exit;
9334 
9335   testl(xlen, 1);
9336   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9337 
9338   // Square and right shift by 1 the odd element using 32 bit multiply
9339   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9340   imulq(raxReg, raxReg);
9341   shrq(raxReg, 1);
9342   adcq(tmp5, 0);
9343   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9344   incrementl(tmp1);
9345   addl(tmp4, 2);
9346 
9347   // Square and  right shift by 1 the rest using 64 bit multiply
9348   bind(L_first_loop);
9349   cmpptr(tmp1, xlen);
9350   jccb(Assembler::equal, L_first_loop_exit);
9351 
9352   // Square
9353   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9354   rorq(raxReg, 32);    // convert big-endian to little-endian
9355   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9356 
9357   // Right shift by 1 and save carry
9358   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9359   rcrq(rdxReg, 1);
9360   rcrq(raxReg, 1);
9361   adcq(tmp5, 0);
9362 
9363   // Store result in z
9364   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9365   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9366 
9367   // Update indices for x and z
9368   addl(tmp1, 2);
9369   addl(tmp4, 4);
9370   jmp(L_first_loop);
9371 
9372   bind(L_first_loop_exit);
9373 }
9374 
9375 
9376 /**
9377  * Perform the following multiply add operation using BMI2 instructions
9378  * carry:sum = sum + op1*op2 + carry
9379  * op2 should be in rdx
9380  * op2 is preserved, all other registers are modified
9381  */
9382 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9383   // assert op2 is rdx
9384   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9385   addq(sum, carry);
9386   adcq(tmp2, 0);
9387   addq(sum, op1);
9388   adcq(tmp2, 0);
9389   movq(carry, tmp2);
9390 }
9391 
9392 /**
9393  * Perform the following multiply add operation:
9394  * carry:sum = sum + op1*op2 + carry
9395  * Preserves op1, op2 and modifies rest of registers
9396  */
9397 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9398   // rdx:rax = op1 * op2
9399   movq(raxReg, op2);
9400   mulq(op1);
9401 
9402   //  rdx:rax = sum + carry + rdx:rax
9403   addq(sum, carry);
9404   adcq(rdxReg, 0);
9405   addq(sum, raxReg);
9406   adcq(rdxReg, 0);
9407 
9408   // carry:sum = rdx:sum
9409   movq(carry, rdxReg);
9410 }
9411 
9412 /**
9413  * Add 64 bit long carry into z[] with carry propogation.
9414  * Preserves z and carry register values and modifies rest of registers.
9415  *
9416  */
9417 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9418   Label L_fourth_loop, L_fourth_loop_exit;
9419 
9420   movl(tmp1, 1);
9421   subl(zlen, 2);
9422   addq(Address(z, zlen, Address::times_4, 0), carry);
9423 
9424   bind(L_fourth_loop);
9425   jccb(Assembler::carryClear, L_fourth_loop_exit);
9426   subl(zlen, 2);
9427   jccb(Assembler::negative, L_fourth_loop_exit);
9428   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9429   jmp(L_fourth_loop);
9430   bind(L_fourth_loop_exit);
9431 }
9432 
9433 /**
9434  * Shift z[] left by 1 bit.
9435  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9436  *
9437  */
9438 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9439 
9440   Label L_fifth_loop, L_fifth_loop_exit;
9441 
9442   // Fifth loop
9443   // Perform primitiveLeftShift(z, zlen, 1)
9444 
9445   const Register prev_carry = tmp1;
9446   const Register new_carry = tmp4;
9447   const Register value = tmp2;
9448   const Register zidx = tmp3;
9449 
9450   // int zidx, carry;
9451   // long value;
9452   // carry = 0;
9453   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9454   //    (carry:value)  = (z[i] << 1) | carry ;
9455   //    z[i] = value;
9456   // }
9457 
9458   movl(zidx, zlen);
9459   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9460 
9461   bind(L_fifth_loop);
9462   decl(zidx);  // Use decl to preserve carry flag
9463   decl(zidx);
9464   jccb(Assembler::negative, L_fifth_loop_exit);
9465 
9466   if (UseBMI2Instructions) {
9467      movq(value, Address(z, zidx, Address::times_4, 0));
9468      rclq(value, 1);
9469      rorxq(value, value, 32);
9470      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9471   }
9472   else {
9473     // clear new_carry
9474     xorl(new_carry, new_carry);
9475 
9476     // Shift z[i] by 1, or in previous carry and save new carry
9477     movq(value, Address(z, zidx, Address::times_4, 0));
9478     shlq(value, 1);
9479     adcl(new_carry, 0);
9480 
9481     orq(value, prev_carry);
9482     rorq(value, 0x20);
9483     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9484 
9485     // Set previous carry = new carry
9486     movl(prev_carry, new_carry);
9487   }
9488   jmp(L_fifth_loop);
9489 
9490   bind(L_fifth_loop_exit);
9491 }
9492 
9493 
9494 /**
9495  * Code for BigInteger::squareToLen() intrinsic
9496  *
9497  * rdi: x
9498  * rsi: len
9499  * r8:  z
9500  * rcx: zlen
9501  * r12: tmp1
9502  * r13: tmp2
9503  * r14: tmp3
9504  * r15: tmp4
9505  * rbx: tmp5
9506  *
9507  */
9508 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) {
9509 
9510   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;
9511   push(tmp1);
9512   push(tmp2);
9513   push(tmp3);
9514   push(tmp4);
9515   push(tmp5);
9516 
9517   // First loop
9518   // Store the squares, right shifted one bit (i.e., divided by 2).
9519   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9520 
9521   // Add in off-diagonal sums.
9522   //
9523   // Second, third (nested) and fourth loops.
9524   // zlen +=2;
9525   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9526   //    carry = 0;
9527   //    long op2 = x[xidx:xidx+1];
9528   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9529   //       k -= 2;
9530   //       long op1 = x[j:j+1];
9531   //       long sum = z[k:k+1];
9532   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9533   //       z[k:k+1] = sum;
9534   //    }
9535   //    add_one_64(z, k, carry, tmp_regs);
9536   // }
9537 
9538   const Register carry = tmp5;
9539   const Register sum = tmp3;
9540   const Register op1 = tmp4;
9541   Register op2 = tmp2;
9542 
9543   push(zlen);
9544   push(len);
9545   addl(zlen,2);
9546   bind(L_second_loop);
9547   xorq(carry, carry);
9548   subl(zlen, 4);
9549   subl(len, 2);
9550   push(zlen);
9551   push(len);
9552   cmpl(len, 0);
9553   jccb(Assembler::lessEqual, L_second_loop_exit);
9554 
9555   // Multiply an array by one 64 bit long.
9556   if (UseBMI2Instructions) {
9557     op2 = rdxReg;
9558     movq(op2, Address(x, len, Address::times_4,  0));
9559     rorxq(op2, op2, 32);
9560   }
9561   else {
9562     movq(op2, Address(x, len, Address::times_4,  0));
9563     rorq(op2, 32);
9564   }
9565 
9566   bind(L_third_loop);
9567   decrementl(len);
9568   jccb(Assembler::negative, L_third_loop_exit);
9569   decrementl(len);
9570   jccb(Assembler::negative, L_last_x);
9571 
9572   movq(op1, Address(x, len, Address::times_4,  0));
9573   rorq(op1, 32);
9574 
9575   bind(L_multiply);
9576   subl(zlen, 2);
9577   movq(sum, Address(z, zlen, Address::times_4,  0));
9578 
9579   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9580   if (UseBMI2Instructions) {
9581     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9582   }
9583   else {
9584     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9585   }
9586 
9587   movq(Address(z, zlen, Address::times_4, 0), sum);
9588 
9589   jmp(L_third_loop);
9590   bind(L_third_loop_exit);
9591 
9592   // Fourth loop
9593   // Add 64 bit long carry into z with carry propogation.
9594   // Uses offsetted zlen.
9595   add_one_64(z, zlen, carry, tmp1);
9596 
9597   pop(len);
9598   pop(zlen);
9599   jmp(L_second_loop);
9600 
9601   // Next infrequent code is moved outside loops.
9602   bind(L_last_x);
9603   movl(op1, Address(x, 0));
9604   jmp(L_multiply);
9605 
9606   bind(L_second_loop_exit);
9607   pop(len);
9608   pop(zlen);
9609   pop(len);
9610   pop(zlen);
9611 
9612   // Fifth loop
9613   // Shift z left 1 bit.
9614   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9615 
9616   // z[zlen-1] |= x[len-1] & 1;
9617   movl(tmp3, Address(x, len, Address::times_4, -4));
9618   andl(tmp3, 1);
9619   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9620 
9621   pop(tmp5);
9622   pop(tmp4);
9623   pop(tmp3);
9624   pop(tmp2);
9625   pop(tmp1);
9626 }
9627 
9628 /**
9629  * Helper function for mul_add()
9630  * Multiply the in[] by int k and add to out[] starting at offset offs using
9631  * 128 bit by 32 bit multiply and return the carry in tmp5.
9632  * Only quad int aligned length of in[] is operated on in this function.
9633  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9634  * This function preserves out, in and k registers.
9635  * len and offset point to the appropriate index in "in" & "out" correspondingly
9636  * tmp5 has the carry.
9637  * other registers are temporary and are modified.
9638  *
9639  */
9640 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9641   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9642   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9643 
9644   Label L_first_loop, L_first_loop_exit;
9645 
9646   movl(tmp1, len);
9647   shrl(tmp1, 2);
9648 
9649   bind(L_first_loop);
9650   subl(tmp1, 1);
9651   jccb(Assembler::negative, L_first_loop_exit);
9652 
9653   subl(len, 4);
9654   subl(offset, 4);
9655 
9656   Register op2 = tmp2;
9657   const Register sum = tmp3;
9658   const Register op1 = tmp4;
9659   const Register carry = tmp5;
9660 
9661   if (UseBMI2Instructions) {
9662     op2 = rdxReg;
9663   }
9664 
9665   movq(op1, Address(in, len, Address::times_4,  8));
9666   rorq(op1, 32);
9667   movq(sum, Address(out, offset, Address::times_4,  8));
9668   rorq(sum, 32);
9669   if (UseBMI2Instructions) {
9670     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9671   }
9672   else {
9673     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9674   }
9675   // Store back in big endian from little endian
9676   rorq(sum, 0x20);
9677   movq(Address(out, offset, Address::times_4,  8), sum);
9678 
9679   movq(op1, Address(in, len, Address::times_4,  0));
9680   rorq(op1, 32);
9681   movq(sum, Address(out, offset, Address::times_4,  0));
9682   rorq(sum, 32);
9683   if (UseBMI2Instructions) {
9684     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9685   }
9686   else {
9687     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9688   }
9689   // Store back in big endian from little endian
9690   rorq(sum, 0x20);
9691   movq(Address(out, offset, Address::times_4,  0), sum);
9692 
9693   jmp(L_first_loop);
9694   bind(L_first_loop_exit);
9695 }
9696 
9697 /**
9698  * Code for BigInteger::mulAdd() intrinsic
9699  *
9700  * rdi: out
9701  * rsi: in
9702  * r11: offs (out.length - offset)
9703  * rcx: len
9704  * r8:  k
9705  * r12: tmp1
9706  * r13: tmp2
9707  * r14: tmp3
9708  * r15: tmp4
9709  * rbx: tmp5
9710  * Multiply the in[] by word k and add to out[], return the carry in rax
9711  */
9712 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9713    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9714    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9715 
9716   Label L_carry, L_last_in, L_done;
9717 
9718 // carry = 0;
9719 // for (int j=len-1; j >= 0; j--) {
9720 //    long product = (in[j] & LONG_MASK) * kLong +
9721 //                   (out[offs] & LONG_MASK) + carry;
9722 //    out[offs--] = (int)product;
9723 //    carry = product >>> 32;
9724 // }
9725 //
9726   push(tmp1);
9727   push(tmp2);
9728   push(tmp3);
9729   push(tmp4);
9730   push(tmp5);
9731 
9732   Register op2 = tmp2;
9733   const Register sum = tmp3;
9734   const Register op1 = tmp4;
9735   const Register carry =  tmp5;
9736 
9737   if (UseBMI2Instructions) {
9738     op2 = rdxReg;
9739     movl(op2, k);
9740   }
9741   else {
9742     movl(op2, k);
9743   }
9744 
9745   xorq(carry, carry);
9746 
9747   //First loop
9748 
9749   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9750   //The carry is in tmp5
9751   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9752 
9753   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9754   decrementl(len);
9755   jccb(Assembler::negative, L_carry);
9756   decrementl(len);
9757   jccb(Assembler::negative, L_last_in);
9758 
9759   movq(op1, Address(in, len, Address::times_4,  0));
9760   rorq(op1, 32);
9761 
9762   subl(offs, 2);
9763   movq(sum, Address(out, offs, Address::times_4,  0));
9764   rorq(sum, 32);
9765 
9766   if (UseBMI2Instructions) {
9767     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9768   }
9769   else {
9770     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9771   }
9772 
9773   // Store back in big endian from little endian
9774   rorq(sum, 0x20);
9775   movq(Address(out, offs, Address::times_4,  0), sum);
9776 
9777   testl(len, len);
9778   jccb(Assembler::zero, L_carry);
9779 
9780   //Multiply the last in[] entry, if any
9781   bind(L_last_in);
9782   movl(op1, Address(in, 0));
9783   movl(sum, Address(out, offs, Address::times_4,  -4));
9784 
9785   movl(raxReg, k);
9786   mull(op1); //tmp4 * eax -> edx:eax
9787   addl(sum, carry);
9788   adcl(rdxReg, 0);
9789   addl(sum, raxReg);
9790   adcl(rdxReg, 0);
9791   movl(carry, rdxReg);
9792 
9793   movl(Address(out, offs, Address::times_4,  -4), sum);
9794 
9795   bind(L_carry);
9796   //return tmp5/carry as carry in rax
9797   movl(rax, carry);
9798 
9799   bind(L_done);
9800   pop(tmp5);
9801   pop(tmp4);
9802   pop(tmp3);
9803   pop(tmp2);
9804   pop(tmp1);
9805 }
9806 #endif
9807 
9808 /**
9809  * Emits code to update CRC-32 with a byte value according to constants in table
9810  *
9811  * @param [in,out]crc   Register containing the crc.
9812  * @param [in]val       Register containing the byte to fold into the CRC.
9813  * @param [in]table     Register containing the table of crc constants.
9814  *
9815  * uint32_t crc;
9816  * val = crc_table[(val ^ crc) & 0xFF];
9817  * crc = val ^ (crc >> 8);
9818  *
9819  */
9820 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9821   xorl(val, crc);
9822   andl(val, 0xFF);
9823   shrl(crc, 8); // unsigned shift
9824   xorl(crc, Address(table, val, Address::times_4, 0));
9825 }
9826 
9827 /**
9828 * Fold four 128-bit data chunks
9829 */
9830 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9831   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9832   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9833   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9834   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9835 }
9836 
9837 /**
9838  * Fold 128-bit data chunk
9839  */
9840 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9841   if (UseAVX > 0) {
9842     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9843     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9844     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9845     pxor(xcrc, xtmp);
9846   } else {
9847     movdqa(xtmp, xcrc);
9848     pclmulhdq(xtmp, xK);   // [123:64]
9849     pclmulldq(xcrc, xK);   // [63:0]
9850     pxor(xcrc, xtmp);
9851     movdqu(xtmp, Address(buf, offset));
9852     pxor(xcrc, xtmp);
9853   }
9854 }
9855 
9856 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9857   if (UseAVX > 0) {
9858     vpclmulhdq(xtmp, xK, xcrc);
9859     vpclmulldq(xcrc, xK, xcrc);
9860     pxor(xcrc, xbuf);
9861     pxor(xcrc, xtmp);
9862   } else {
9863     movdqa(xtmp, xcrc);
9864     pclmulhdq(xtmp, xK);
9865     pclmulldq(xcrc, xK);
9866     pxor(xcrc, xbuf);
9867     pxor(xcrc, xtmp);
9868   }
9869 }
9870 
9871 /**
9872  * 8-bit folds to compute 32-bit CRC
9873  *
9874  * uint64_t xcrc;
9875  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9876  */
9877 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9878   movdl(tmp, xcrc);
9879   andl(tmp, 0xFF);
9880   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9881   psrldq(xcrc, 1); // unsigned shift one byte
9882   pxor(xcrc, xtmp);
9883 }
9884 
9885 /**
9886  * uint32_t crc;
9887  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9888  */
9889 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9890   movl(tmp, crc);
9891   andl(tmp, 0xFF);
9892   shrl(crc, 8);
9893   xorl(crc, Address(table, tmp, Address::times_4, 0));
9894 }
9895 
9896 /**
9897  * @param crc   register containing existing CRC (32-bit)
9898  * @param buf   register pointing to input byte buffer (byte*)
9899  * @param len   register containing number of bytes
9900  * @param table register that will contain address of CRC table
9901  * @param tmp   scratch register
9902  */
9903 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9904   assert_different_registers(crc, buf, len, table, tmp, rax);
9905 
9906   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9907   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9908 
9909   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9910   // context for the registers used, where all instructions below are using 128-bit mode
9911   // On EVEX without VL and BW, these instructions will all be AVX.
9912   if (VM_Version::supports_avx512vlbw()) {
9913     movl(tmp, 0xffff);
9914     kmovwl(k1, tmp);
9915   }
9916 
9917   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9918   notl(crc); // ~crc
9919   cmpl(len, 16);
9920   jcc(Assembler::less, L_tail);
9921 
9922   // Align buffer to 16 bytes
9923   movl(tmp, buf);
9924   andl(tmp, 0xF);
9925   jccb(Assembler::zero, L_aligned);
9926   subl(tmp,  16);
9927   addl(len, tmp);
9928 
9929   align(4);
9930   BIND(L_align_loop);
9931   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9932   update_byte_crc32(crc, rax, table);
9933   increment(buf);
9934   incrementl(tmp);
9935   jccb(Assembler::less, L_align_loop);
9936 
9937   BIND(L_aligned);
9938   movl(tmp, len); // save
9939   shrl(len, 4);
9940   jcc(Assembler::zero, L_tail_restore);
9941 
9942   // Fold total 512 bits of polynomial on each iteration
9943   if (VM_Version::supports_vpclmulqdq()) {
9944     Label Parallel_loop, L_No_Parallel;
9945 
9946     cmpl(len, 8);
9947     jccb(Assembler::less, L_No_Parallel);
9948 
9949     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9950     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9951     movdl(xmm5, crc);
9952     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9953     addptr(buf, 64);
9954     subl(len, 7);
9955     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9956 
9957     BIND(Parallel_loop);
9958     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9959     addptr(buf, 64);
9960     subl(len, 4);
9961     jcc(Assembler::greater, Parallel_loop);
9962 
9963     vextracti64x2(xmm2, xmm1, 0x01);
9964     vextracti64x2(xmm3, xmm1, 0x02);
9965     vextracti64x2(xmm4, xmm1, 0x03);
9966     jmp(L_fold_512b);
9967 
9968     BIND(L_No_Parallel);
9969   }
9970   // Fold crc into first bytes of vector
9971   movdqa(xmm1, Address(buf, 0));
9972   movdl(rax, xmm1);
9973   xorl(crc, rax);
9974   if (VM_Version::supports_sse4_1()) {
9975     pinsrd(xmm1, crc, 0);
9976   } else {
9977     pinsrw(xmm1, crc, 0);
9978     shrl(crc, 16);
9979     pinsrw(xmm1, crc, 1);
9980   }
9981   addptr(buf, 16);
9982   subl(len, 4); // len > 0
9983   jcc(Assembler::less, L_fold_tail);
9984 
9985   movdqa(xmm2, Address(buf,  0));
9986   movdqa(xmm3, Address(buf, 16));
9987   movdqa(xmm4, Address(buf, 32));
9988   addptr(buf, 48);
9989   subl(len, 3);
9990   jcc(Assembler::lessEqual, L_fold_512b);
9991 
9992   // Fold total 512 bits of polynomial on each iteration,
9993   // 128 bits per each of 4 parallel streams.
9994   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9995 
9996   align(32);
9997   BIND(L_fold_512b_loop);
9998   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9999   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10000   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10001   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10002   addptr(buf, 64);
10003   subl(len, 4);
10004   jcc(Assembler::greater, L_fold_512b_loop);
10005 
10006   // Fold 512 bits to 128 bits.
10007   BIND(L_fold_512b);
10008   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10009   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10010   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10011   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10012 
10013   // Fold the rest of 128 bits data chunks
10014   BIND(L_fold_tail);
10015   addl(len, 3);
10016   jccb(Assembler::lessEqual, L_fold_128b);
10017   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10018 
10019   BIND(L_fold_tail_loop);
10020   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10021   addptr(buf, 16);
10022   decrementl(len);
10023   jccb(Assembler::greater, L_fold_tail_loop);
10024 
10025   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10026   BIND(L_fold_128b);
10027   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10028   if (UseAVX > 0) {
10029     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10030     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10031     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10032   } else {
10033     movdqa(xmm2, xmm0);
10034     pclmulqdq(xmm2, xmm1, 0x1);
10035     movdqa(xmm3, xmm0);
10036     pand(xmm3, xmm2);
10037     pclmulqdq(xmm0, xmm3, 0x1);
10038   }
10039   psrldq(xmm1, 8);
10040   psrldq(xmm2, 4);
10041   pxor(xmm0, xmm1);
10042   pxor(xmm0, xmm2);
10043 
10044   // 8 8-bit folds to compute 32-bit CRC.
10045   for (int j = 0; j < 4; j++) {
10046     fold_8bit_crc32(xmm0, table, xmm1, rax);
10047   }
10048   movdl(crc, xmm0); // mov 32 bits to general register
10049   for (int j = 0; j < 4; j++) {
10050     fold_8bit_crc32(crc, table, rax);
10051   }
10052 
10053   BIND(L_tail_restore);
10054   movl(len, tmp); // restore
10055   BIND(L_tail);
10056   andl(len, 0xf);
10057   jccb(Assembler::zero, L_exit);
10058 
10059   // Fold the rest of bytes
10060   align(4);
10061   BIND(L_tail_loop);
10062   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10063   update_byte_crc32(crc, rax, table);
10064   increment(buf);
10065   decrementl(len);
10066   jccb(Assembler::greater, L_tail_loop);
10067 
10068   BIND(L_exit);
10069   notl(crc); // ~c
10070 }
10071 
10072 #ifdef _LP64
10073 // S. Gueron / Information Processing Letters 112 (2012) 184
10074 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10075 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10076 // Output: the 64-bit carry-less product of B * CONST
10077 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10078                                      Register tmp1, Register tmp2, Register tmp3) {
10079   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10080   if (n > 0) {
10081     addq(tmp3, n * 256 * 8);
10082   }
10083   //    Q1 = TABLEExt[n][B & 0xFF];
10084   movl(tmp1, in);
10085   andl(tmp1, 0x000000FF);
10086   shll(tmp1, 3);
10087   addq(tmp1, tmp3);
10088   movq(tmp1, Address(tmp1, 0));
10089 
10090   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10091   movl(tmp2, in);
10092   shrl(tmp2, 8);
10093   andl(tmp2, 0x000000FF);
10094   shll(tmp2, 3);
10095   addq(tmp2, tmp3);
10096   movq(tmp2, Address(tmp2, 0));
10097 
10098   shlq(tmp2, 8);
10099   xorq(tmp1, tmp2);
10100 
10101   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10102   movl(tmp2, in);
10103   shrl(tmp2, 16);
10104   andl(tmp2, 0x000000FF);
10105   shll(tmp2, 3);
10106   addq(tmp2, tmp3);
10107   movq(tmp2, Address(tmp2, 0));
10108 
10109   shlq(tmp2, 16);
10110   xorq(tmp1, tmp2);
10111 
10112   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10113   shrl(in, 24);
10114   andl(in, 0x000000FF);
10115   shll(in, 3);
10116   addq(in, tmp3);
10117   movq(in, Address(in, 0));
10118 
10119   shlq(in, 24);
10120   xorq(in, tmp1);
10121   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10122 }
10123 
10124 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10125                                       Register in_out,
10126                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10127                                       XMMRegister w_xtmp2,
10128                                       Register tmp1,
10129                                       Register n_tmp2, Register n_tmp3) {
10130   if (is_pclmulqdq_supported) {
10131     movdl(w_xtmp1, in_out); // modified blindly
10132 
10133     movl(tmp1, const_or_pre_comp_const_index);
10134     movdl(w_xtmp2, tmp1);
10135     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10136 
10137     movdq(in_out, w_xtmp1);
10138   } else {
10139     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10140   }
10141 }
10142 
10143 // Recombination Alternative 2: No bit-reflections
10144 // T1 = (CRC_A * U1) << 1
10145 // T2 = (CRC_B * U2) << 1
10146 // C1 = T1 >> 32
10147 // C2 = T2 >> 32
10148 // T1 = T1 & 0xFFFFFFFF
10149 // T2 = T2 & 0xFFFFFFFF
10150 // T1 = CRC32(0, T1)
10151 // T2 = CRC32(0, T2)
10152 // C1 = C1 ^ T1
10153 // C2 = C2 ^ T2
10154 // CRC = C1 ^ C2 ^ CRC_C
10155 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,
10156                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10157                                      Register tmp1, Register tmp2,
10158                                      Register n_tmp3) {
10159   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10160   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10161   shlq(in_out, 1);
10162   movl(tmp1, in_out);
10163   shrq(in_out, 32);
10164   xorl(tmp2, tmp2);
10165   crc32(tmp2, tmp1, 4);
10166   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10167   shlq(in1, 1);
10168   movl(tmp1, in1);
10169   shrq(in1, 32);
10170   xorl(tmp2, tmp2);
10171   crc32(tmp2, tmp1, 4);
10172   xorl(in1, tmp2);
10173   xorl(in_out, in1);
10174   xorl(in_out, in2);
10175 }
10176 
10177 // Set N to predefined value
10178 // Subtract from a lenght of a buffer
10179 // execute in a loop:
10180 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10181 // for i = 1 to N do
10182 //  CRC_A = CRC32(CRC_A, A[i])
10183 //  CRC_B = CRC32(CRC_B, B[i])
10184 //  CRC_C = CRC32(CRC_C, C[i])
10185 // end for
10186 // Recombine
10187 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,
10188                                        Register in_out1, Register in_out2, Register in_out3,
10189                                        Register tmp1, Register tmp2, Register tmp3,
10190                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10191                                        Register tmp4, Register tmp5,
10192                                        Register n_tmp6) {
10193   Label L_processPartitions;
10194   Label L_processPartition;
10195   Label L_exit;
10196 
10197   bind(L_processPartitions);
10198   cmpl(in_out1, 3 * size);
10199   jcc(Assembler::less, L_exit);
10200     xorl(tmp1, tmp1);
10201     xorl(tmp2, tmp2);
10202     movq(tmp3, in_out2);
10203     addq(tmp3, size);
10204 
10205     bind(L_processPartition);
10206       crc32(in_out3, Address(in_out2, 0), 8);
10207       crc32(tmp1, Address(in_out2, size), 8);
10208       crc32(tmp2, Address(in_out2, size * 2), 8);
10209       addq(in_out2, 8);
10210       cmpq(in_out2, tmp3);
10211       jcc(Assembler::less, L_processPartition);
10212     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10213             w_xtmp1, w_xtmp2, w_xtmp3,
10214             tmp4, tmp5,
10215             n_tmp6);
10216     addq(in_out2, 2 * size);
10217     subl(in_out1, 3 * size);
10218     jmp(L_processPartitions);
10219 
10220   bind(L_exit);
10221 }
10222 #else
10223 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10224                                      Register tmp1, Register tmp2, Register tmp3,
10225                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10226   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10227   if (n > 0) {
10228     addl(tmp3, n * 256 * 8);
10229   }
10230   //    Q1 = TABLEExt[n][B & 0xFF];
10231   movl(tmp1, in_out);
10232   andl(tmp1, 0x000000FF);
10233   shll(tmp1, 3);
10234   addl(tmp1, tmp3);
10235   movq(xtmp1, Address(tmp1, 0));
10236 
10237   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10238   movl(tmp2, in_out);
10239   shrl(tmp2, 8);
10240   andl(tmp2, 0x000000FF);
10241   shll(tmp2, 3);
10242   addl(tmp2, tmp3);
10243   movq(xtmp2, Address(tmp2, 0));
10244 
10245   psllq(xtmp2, 8);
10246   pxor(xtmp1, xtmp2);
10247 
10248   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10249   movl(tmp2, in_out);
10250   shrl(tmp2, 16);
10251   andl(tmp2, 0x000000FF);
10252   shll(tmp2, 3);
10253   addl(tmp2, tmp3);
10254   movq(xtmp2, Address(tmp2, 0));
10255 
10256   psllq(xtmp2, 16);
10257   pxor(xtmp1, xtmp2);
10258 
10259   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10260   shrl(in_out, 24);
10261   andl(in_out, 0x000000FF);
10262   shll(in_out, 3);
10263   addl(in_out, tmp3);
10264   movq(xtmp2, Address(in_out, 0));
10265 
10266   psllq(xtmp2, 24);
10267   pxor(xtmp1, xtmp2); // Result in CXMM
10268   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10269 }
10270 
10271 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10272                                       Register in_out,
10273                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10274                                       XMMRegister w_xtmp2,
10275                                       Register tmp1,
10276                                       Register n_tmp2, Register n_tmp3) {
10277   if (is_pclmulqdq_supported) {
10278     movdl(w_xtmp1, in_out);
10279 
10280     movl(tmp1, const_or_pre_comp_const_index);
10281     movdl(w_xtmp2, tmp1);
10282     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10283     // Keep result in XMM since GPR is 32 bit in length
10284   } else {
10285     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10286   }
10287 }
10288 
10289 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,
10290                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10291                                      Register tmp1, Register tmp2,
10292                                      Register n_tmp3) {
10293   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10294   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10295 
10296   psllq(w_xtmp1, 1);
10297   movdl(tmp1, w_xtmp1);
10298   psrlq(w_xtmp1, 32);
10299   movdl(in_out, w_xtmp1);
10300 
10301   xorl(tmp2, tmp2);
10302   crc32(tmp2, tmp1, 4);
10303   xorl(in_out, tmp2);
10304 
10305   psllq(w_xtmp2, 1);
10306   movdl(tmp1, w_xtmp2);
10307   psrlq(w_xtmp2, 32);
10308   movdl(in1, w_xtmp2);
10309 
10310   xorl(tmp2, tmp2);
10311   crc32(tmp2, tmp1, 4);
10312   xorl(in1, tmp2);
10313   xorl(in_out, in1);
10314   xorl(in_out, in2);
10315 }
10316 
10317 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,
10318                                        Register in_out1, Register in_out2, Register in_out3,
10319                                        Register tmp1, Register tmp2, Register tmp3,
10320                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10321                                        Register tmp4, Register tmp5,
10322                                        Register n_tmp6) {
10323   Label L_processPartitions;
10324   Label L_processPartition;
10325   Label L_exit;
10326 
10327   bind(L_processPartitions);
10328   cmpl(in_out1, 3 * size);
10329   jcc(Assembler::less, L_exit);
10330     xorl(tmp1, tmp1);
10331     xorl(tmp2, tmp2);
10332     movl(tmp3, in_out2);
10333     addl(tmp3, size);
10334 
10335     bind(L_processPartition);
10336       crc32(in_out3, Address(in_out2, 0), 4);
10337       crc32(tmp1, Address(in_out2, size), 4);
10338       crc32(tmp2, Address(in_out2, size*2), 4);
10339       crc32(in_out3, Address(in_out2, 0+4), 4);
10340       crc32(tmp1, Address(in_out2, size+4), 4);
10341       crc32(tmp2, Address(in_out2, size*2+4), 4);
10342       addl(in_out2, 8);
10343       cmpl(in_out2, tmp3);
10344       jcc(Assembler::less, L_processPartition);
10345 
10346         push(tmp3);
10347         push(in_out1);
10348         push(in_out2);
10349         tmp4 = tmp3;
10350         tmp5 = in_out1;
10351         n_tmp6 = in_out2;
10352 
10353       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10354             w_xtmp1, w_xtmp2, w_xtmp3,
10355             tmp4, tmp5,
10356             n_tmp6);
10357 
10358         pop(in_out2);
10359         pop(in_out1);
10360         pop(tmp3);
10361 
10362     addl(in_out2, 2 * size);
10363     subl(in_out1, 3 * size);
10364     jmp(L_processPartitions);
10365 
10366   bind(L_exit);
10367 }
10368 #endif //LP64
10369 
10370 #ifdef _LP64
10371 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10372 // Input: A buffer I of L bytes.
10373 // Output: the CRC32C value of the buffer.
10374 // Notations:
10375 // Write L = 24N + r, with N = floor (L/24).
10376 // r = L mod 24 (0 <= r < 24).
10377 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10378 // N quadwords, and R consists of r bytes.
10379 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10380 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10381 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10382 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10383 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10384                                           Register tmp1, Register tmp2, Register tmp3,
10385                                           Register tmp4, Register tmp5, Register tmp6,
10386                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10387                                           bool is_pclmulqdq_supported) {
10388   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10389   Label L_wordByWord;
10390   Label L_byteByByteProlog;
10391   Label L_byteByByte;
10392   Label L_exit;
10393 
10394   if (is_pclmulqdq_supported ) {
10395     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10396     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10397 
10398     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10399     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10400 
10401     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10402     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10403     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10404   } else {
10405     const_or_pre_comp_const_index[0] = 1;
10406     const_or_pre_comp_const_index[1] = 0;
10407 
10408     const_or_pre_comp_const_index[2] = 3;
10409     const_or_pre_comp_const_index[3] = 2;
10410 
10411     const_or_pre_comp_const_index[4] = 5;
10412     const_or_pre_comp_const_index[5] = 4;
10413    }
10414   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10415                     in2, in1, in_out,
10416                     tmp1, tmp2, tmp3,
10417                     w_xtmp1, w_xtmp2, w_xtmp3,
10418                     tmp4, tmp5,
10419                     tmp6);
10420   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10421                     in2, in1, in_out,
10422                     tmp1, tmp2, tmp3,
10423                     w_xtmp1, w_xtmp2, w_xtmp3,
10424                     tmp4, tmp5,
10425                     tmp6);
10426   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10427                     in2, in1, in_out,
10428                     tmp1, tmp2, tmp3,
10429                     w_xtmp1, w_xtmp2, w_xtmp3,
10430                     tmp4, tmp5,
10431                     tmp6);
10432   movl(tmp1, in2);
10433   andl(tmp1, 0x00000007);
10434   negl(tmp1);
10435   addl(tmp1, in2);
10436   addq(tmp1, in1);
10437 
10438   BIND(L_wordByWord);
10439   cmpq(in1, tmp1);
10440   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10441     crc32(in_out, Address(in1, 0), 4);
10442     addq(in1, 4);
10443     jmp(L_wordByWord);
10444 
10445   BIND(L_byteByByteProlog);
10446   andl(in2, 0x00000007);
10447   movl(tmp2, 1);
10448 
10449   BIND(L_byteByByte);
10450   cmpl(tmp2, in2);
10451   jccb(Assembler::greater, L_exit);
10452     crc32(in_out, Address(in1, 0), 1);
10453     incq(in1);
10454     incl(tmp2);
10455     jmp(L_byteByByte);
10456 
10457   BIND(L_exit);
10458 }
10459 #else
10460 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10461                                           Register tmp1, Register  tmp2, Register tmp3,
10462                                           Register tmp4, Register  tmp5, Register tmp6,
10463                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10464                                           bool is_pclmulqdq_supported) {
10465   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10466   Label L_wordByWord;
10467   Label L_byteByByteProlog;
10468   Label L_byteByByte;
10469   Label L_exit;
10470 
10471   if (is_pclmulqdq_supported) {
10472     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10473     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10474 
10475     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10476     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10477 
10478     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10479     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10480   } else {
10481     const_or_pre_comp_const_index[0] = 1;
10482     const_or_pre_comp_const_index[1] = 0;
10483 
10484     const_or_pre_comp_const_index[2] = 3;
10485     const_or_pre_comp_const_index[3] = 2;
10486 
10487     const_or_pre_comp_const_index[4] = 5;
10488     const_or_pre_comp_const_index[5] = 4;
10489   }
10490   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10491                     in2, in1, in_out,
10492                     tmp1, tmp2, tmp3,
10493                     w_xtmp1, w_xtmp2, w_xtmp3,
10494                     tmp4, tmp5,
10495                     tmp6);
10496   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10497                     in2, in1, in_out,
10498                     tmp1, tmp2, tmp3,
10499                     w_xtmp1, w_xtmp2, w_xtmp3,
10500                     tmp4, tmp5,
10501                     tmp6);
10502   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10503                     in2, in1, in_out,
10504                     tmp1, tmp2, tmp3,
10505                     w_xtmp1, w_xtmp2, w_xtmp3,
10506                     tmp4, tmp5,
10507                     tmp6);
10508   movl(tmp1, in2);
10509   andl(tmp1, 0x00000007);
10510   negl(tmp1);
10511   addl(tmp1, in2);
10512   addl(tmp1, in1);
10513 
10514   BIND(L_wordByWord);
10515   cmpl(in1, tmp1);
10516   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10517     crc32(in_out, Address(in1,0), 4);
10518     addl(in1, 4);
10519     jmp(L_wordByWord);
10520 
10521   BIND(L_byteByByteProlog);
10522   andl(in2, 0x00000007);
10523   movl(tmp2, 1);
10524 
10525   BIND(L_byteByByte);
10526   cmpl(tmp2, in2);
10527   jccb(Assembler::greater, L_exit);
10528     movb(tmp1, Address(in1, 0));
10529     crc32(in_out, tmp1, 1);
10530     incl(in1);
10531     incl(tmp2);
10532     jmp(L_byteByByte);
10533 
10534   BIND(L_exit);
10535 }
10536 #endif // LP64
10537 #undef BIND
10538 #undef BLOCK_COMMENT
10539 
10540 // Compress char[] array to byte[].
10541 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10542 //   @HotSpotIntrinsicCandidate
10543 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10544 //     for (int i = 0; i < len; i++) {
10545 //       int c = src[srcOff++];
10546 //       if (c >>> 8 != 0) {
10547 //         return 0;
10548 //       }
10549 //       dst[dstOff++] = (byte)c;
10550 //     }
10551 //     return len;
10552 //   }
10553 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10554   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10555   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10556   Register tmp5, Register result) {
10557   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10558 
10559   // rsi: src
10560   // rdi: dst
10561   // rdx: len
10562   // rcx: tmp5
10563   // rax: result
10564 
10565   // rsi holds start addr of source char[] to be compressed
10566   // rdi holds start addr of destination byte[]
10567   // rdx holds length
10568 
10569   assert(len != result, "");
10570 
10571   // save length for return
10572   push(len);
10573 
10574   if ((UseAVX > 2) && // AVX512
10575     VM_Version::supports_avx512vlbw() &&
10576     VM_Version::supports_bmi2()) {
10577 
10578     set_vector_masking();  // opening of the stub context for programming mask registers
10579 
10580     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10581 
10582     // alignement
10583     Label post_alignement;
10584 
10585     // if length of the string is less than 16, handle it in an old fashioned
10586     // way
10587     testl(len, -32);
10588     jcc(Assembler::zero, below_threshold);
10589 
10590     // First check whether a character is compressable ( <= 0xFF).
10591     // Create mask to test for Unicode chars inside zmm vector
10592     movl(result, 0x00FF);
10593     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10594 
10595     // Save k1
10596     kmovql(k3, k1);
10597 
10598     testl(len, -64);
10599     jcc(Assembler::zero, post_alignement);
10600 
10601     movl(tmp5, dst);
10602     andl(tmp5, (32 - 1));
10603     negl(tmp5);
10604     andl(tmp5, (32 - 1));
10605 
10606     // bail out when there is nothing to be done
10607     testl(tmp5, 0xFFFFFFFF);
10608     jcc(Assembler::zero, post_alignement);
10609 
10610     // ~(~0 << len), where len is the # of remaining elements to process
10611     movl(result, 0xFFFFFFFF);
10612     shlxl(result, result, tmp5);
10613     notl(result);
10614     kmovdl(k1, result);
10615 
10616     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10617     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10618     ktestd(k2, k1);
10619     jcc(Assembler::carryClear, restore_k1_return_zero);
10620 
10621     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10622 
10623     addptr(src, tmp5);
10624     addptr(src, tmp5);
10625     addptr(dst, tmp5);
10626     subl(len, tmp5);
10627 
10628     bind(post_alignement);
10629     // end of alignement
10630 
10631     movl(tmp5, len);
10632     andl(tmp5, (32 - 1));    // tail count (in chars)
10633     andl(len, ~(32 - 1));    // vector count (in chars)
10634     jcc(Assembler::zero, copy_loop_tail);
10635 
10636     lea(src, Address(src, len, Address::times_2));
10637     lea(dst, Address(dst, len, Address::times_1));
10638     negptr(len);
10639 
10640     bind(copy_32_loop);
10641     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10642     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10643     kortestdl(k2, k2);
10644     jcc(Assembler::carryClear, restore_k1_return_zero);
10645 
10646     // All elements in current processed chunk are valid candidates for
10647     // compression. Write a truncated byte elements to the memory.
10648     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10649     addptr(len, 32);
10650     jcc(Assembler::notZero, copy_32_loop);
10651 
10652     bind(copy_loop_tail);
10653     // bail out when there is nothing to be done
10654     testl(tmp5, 0xFFFFFFFF);
10655     // Restore k1
10656     kmovql(k1, k3);
10657     jcc(Assembler::zero, return_length);
10658 
10659     movl(len, tmp5);
10660 
10661     // ~(~0 << len), where len is the # of remaining elements to process
10662     movl(result, 0xFFFFFFFF);
10663     shlxl(result, result, len);
10664     notl(result);
10665 
10666     kmovdl(k1, result);
10667 
10668     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10669     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10670     ktestd(k2, k1);
10671     jcc(Assembler::carryClear, restore_k1_return_zero);
10672 
10673     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10674     // Restore k1
10675     kmovql(k1, k3);
10676     jmp(return_length);
10677 
10678     bind(restore_k1_return_zero);
10679     // Restore k1
10680     kmovql(k1, k3);
10681     jmp(return_zero);
10682 
10683     clear_vector_masking();   // closing of the stub context for programming mask registers
10684   }
10685   if (UseSSE42Intrinsics) {
10686     Label copy_32_loop, copy_16, copy_tail;
10687 
10688     bind(below_threshold);
10689 
10690     movl(result, len);
10691 
10692     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10693 
10694     // vectored compression
10695     andl(len, 0xfffffff0);    // vector count (in chars)
10696     andl(result, 0x0000000f);    // tail count (in chars)
10697     testl(len, len);
10698     jccb(Assembler::zero, copy_16);
10699 
10700     // compress 16 chars per iter
10701     movdl(tmp1Reg, tmp5);
10702     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10703     pxor(tmp4Reg, tmp4Reg);
10704 
10705     lea(src, Address(src, len, Address::times_2));
10706     lea(dst, Address(dst, len, Address::times_1));
10707     negptr(len);
10708 
10709     bind(copy_32_loop);
10710     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10711     por(tmp4Reg, tmp2Reg);
10712     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10713     por(tmp4Reg, tmp3Reg);
10714     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10715     jcc(Assembler::notZero, return_zero);
10716     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10717     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10718     addptr(len, 16);
10719     jcc(Assembler::notZero, copy_32_loop);
10720 
10721     // compress next vector of 8 chars (if any)
10722     bind(copy_16);
10723     movl(len, result);
10724     andl(len, 0xfffffff8);    // vector count (in chars)
10725     andl(result, 0x00000007);    // tail count (in chars)
10726     testl(len, len);
10727     jccb(Assembler::zero, copy_tail);
10728 
10729     movdl(tmp1Reg, tmp5);
10730     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10731     pxor(tmp3Reg, tmp3Reg);
10732 
10733     movdqu(tmp2Reg, Address(src, 0));
10734     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10735     jccb(Assembler::notZero, return_zero);
10736     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10737     movq(Address(dst, 0), tmp2Reg);
10738     addptr(src, 16);
10739     addptr(dst, 8);
10740 
10741     bind(copy_tail);
10742     movl(len, result);
10743   }
10744   // compress 1 char per iter
10745   testl(len, len);
10746   jccb(Assembler::zero, return_length);
10747   lea(src, Address(src, len, Address::times_2));
10748   lea(dst, Address(dst, len, Address::times_1));
10749   negptr(len);
10750 
10751   bind(copy_chars_loop);
10752   load_unsigned_short(result, Address(src, len, Address::times_2));
10753   testl(result, 0xff00);      // check if Unicode char
10754   jccb(Assembler::notZero, return_zero);
10755   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10756   increment(len);
10757   jcc(Assembler::notZero, copy_chars_loop);
10758 
10759   // if compression succeeded, return length
10760   bind(return_length);
10761   pop(result);
10762   jmpb(done);
10763 
10764   // if compression failed, return 0
10765   bind(return_zero);
10766   xorl(result, result);
10767   addptr(rsp, wordSize);
10768 
10769   bind(done);
10770 }
10771 
10772 // Inflate byte[] array to char[].
10773 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10774 //   @HotSpotIntrinsicCandidate
10775 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10776 //     for (int i = 0; i < len; i++) {
10777 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10778 //     }
10779 //   }
10780 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10781   XMMRegister tmp1, Register tmp2) {
10782   Label copy_chars_loop, done, below_threshold;
10783   // rsi: src
10784   // rdi: dst
10785   // rdx: len
10786   // rcx: tmp2
10787 
10788   // rsi holds start addr of source byte[] to be inflated
10789   // rdi holds start addr of destination char[]
10790   // rdx holds length
10791   assert_different_registers(src, dst, len, tmp2);
10792 
10793   if ((UseAVX > 2) && // AVX512
10794     VM_Version::supports_avx512vlbw() &&
10795     VM_Version::supports_bmi2()) {
10796 
10797     set_vector_masking();  // opening of the stub context for programming mask registers
10798 
10799     Label copy_32_loop, copy_tail;
10800     Register tmp3_aliased = len;
10801 
10802     // if length of the string is less than 16, handle it in an old fashioned
10803     // way
10804     testl(len, -16);
10805     jcc(Assembler::zero, below_threshold);
10806 
10807     // In order to use only one arithmetic operation for the main loop we use
10808     // this pre-calculation
10809     movl(tmp2, len);
10810     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10811     andl(len, -32);     // vector count
10812     jccb(Assembler::zero, copy_tail);
10813 
10814     lea(src, Address(src, len, Address::times_1));
10815     lea(dst, Address(dst, len, Address::times_2));
10816     negptr(len);
10817 
10818 
10819     // inflate 32 chars per iter
10820     bind(copy_32_loop);
10821     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10822     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10823     addptr(len, 32);
10824     jcc(Assembler::notZero, copy_32_loop);
10825 
10826     bind(copy_tail);
10827     // bail out when there is nothing to be done
10828     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10829     jcc(Assembler::zero, done);
10830 
10831     // Save k1
10832     kmovql(k2, k1);
10833 
10834     // ~(~0 << length), where length is the # of remaining elements to process
10835     movl(tmp3_aliased, -1);
10836     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10837     notl(tmp3_aliased);
10838     kmovdl(k1, tmp3_aliased);
10839     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10840     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10841 
10842     // Restore k1
10843     kmovql(k1, k2);
10844     jmp(done);
10845 
10846     clear_vector_masking();   // closing of the stub context for programming mask registers
10847   }
10848   if (UseSSE42Intrinsics) {
10849     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10850 
10851     movl(tmp2, len);
10852 
10853     if (UseAVX > 1) {
10854       andl(tmp2, (16 - 1));
10855       andl(len, -16);
10856       jccb(Assembler::zero, copy_new_tail);
10857     } else {
10858       andl(tmp2, 0x00000007);   // tail count (in chars)
10859       andl(len, 0xfffffff8);    // vector count (in chars)
10860       jccb(Assembler::zero, copy_tail);
10861     }
10862 
10863     // vectored inflation
10864     lea(src, Address(src, len, Address::times_1));
10865     lea(dst, Address(dst, len, Address::times_2));
10866     negptr(len);
10867 
10868     if (UseAVX > 1) {
10869       bind(copy_16_loop);
10870       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10871       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10872       addptr(len, 16);
10873       jcc(Assembler::notZero, copy_16_loop);
10874 
10875       bind(below_threshold);
10876       bind(copy_new_tail);
10877       if ((UseAVX > 2) &&
10878         VM_Version::supports_avx512vlbw() &&
10879         VM_Version::supports_bmi2()) {
10880         movl(tmp2, len);
10881       } else {
10882         movl(len, tmp2);
10883       }
10884       andl(tmp2, 0x00000007);
10885       andl(len, 0xFFFFFFF8);
10886       jccb(Assembler::zero, copy_tail);
10887 
10888       pmovzxbw(tmp1, Address(src, 0));
10889       movdqu(Address(dst, 0), tmp1);
10890       addptr(src, 8);
10891       addptr(dst, 2 * 8);
10892 
10893       jmp(copy_tail, true);
10894     }
10895 
10896     // inflate 8 chars per iter
10897     bind(copy_8_loop);
10898     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10899     movdqu(Address(dst, len, Address::times_2), tmp1);
10900     addptr(len, 8);
10901     jcc(Assembler::notZero, copy_8_loop);
10902 
10903     bind(copy_tail);
10904     movl(len, tmp2);
10905 
10906     cmpl(len, 4);
10907     jccb(Assembler::less, copy_bytes);
10908 
10909     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10910     pmovzxbw(tmp1, tmp1);
10911     movq(Address(dst, 0), tmp1);
10912     subptr(len, 4);
10913     addptr(src, 4);
10914     addptr(dst, 8);
10915 
10916     bind(copy_bytes);
10917   }
10918   testl(len, len);
10919   jccb(Assembler::zero, done);
10920   lea(src, Address(src, len, Address::times_1));
10921   lea(dst, Address(dst, len, Address::times_2));
10922   negptr(len);
10923 
10924   // inflate 1 char per iter
10925   bind(copy_chars_loop);
10926   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10927   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10928   increment(len);
10929   jcc(Assembler::notZero, copy_chars_loop);
10930 
10931   bind(done);
10932 }
10933 
10934 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10935   switch (cond) {
10936     // Note some conditions are synonyms for others
10937     case Assembler::zero:         return Assembler::notZero;
10938     case Assembler::notZero:      return Assembler::zero;
10939     case Assembler::less:         return Assembler::greaterEqual;
10940     case Assembler::lessEqual:    return Assembler::greater;
10941     case Assembler::greater:      return Assembler::lessEqual;
10942     case Assembler::greaterEqual: return Assembler::less;
10943     case Assembler::below:        return Assembler::aboveEqual;
10944     case Assembler::belowEqual:   return Assembler::above;
10945     case Assembler::above:        return Assembler::belowEqual;
10946     case Assembler::aboveEqual:   return Assembler::below;
10947     case Assembler::overflow:     return Assembler::noOverflow;
10948     case Assembler::noOverflow:   return Assembler::overflow;
10949     case Assembler::negative:     return Assembler::positive;
10950     case Assembler::positive:     return Assembler::negative;
10951     case Assembler::parity:       return Assembler::noParity;
10952     case Assembler::noParity:     return Assembler::parity;
10953   }
10954   ShouldNotReachHere(); return Assembler::overflow;
10955 }
10956 
10957 SkipIfEqual::SkipIfEqual(
10958     MacroAssembler* masm, const bool* flag_addr, bool value) {
10959   _masm = masm;
10960   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10961   _masm->jcc(Assembler::equal, _label);
10962 }
10963 
10964 SkipIfEqual::~SkipIfEqual() {
10965   _masm->bind(_label);
10966 }
10967 
10968 // 32-bit Windows has its own fast-path implementation
10969 // of get_thread
10970 #if !defined(WIN32) || defined(_LP64)
10971 
10972 // This is simply a call to Thread::current()
10973 void MacroAssembler::get_thread(Register thread) {
10974   if (thread != rax) {
10975     push(rax);
10976   }
10977   LP64_ONLY(push(rdi);)
10978   LP64_ONLY(push(rsi);)
10979   push(rdx);
10980   push(rcx);
10981 #ifdef _LP64
10982   push(r8);
10983   push(r9);
10984   push(r10);
10985   push(r11);
10986 #endif
10987 
10988   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10989 
10990 #ifdef _LP64
10991   pop(r11);
10992   pop(r10);
10993   pop(r9);
10994   pop(r8);
10995 #endif
10996   pop(rcx);
10997   pop(rdx);
10998   LP64_ONLY(pop(rsi);)
10999   LP64_ONLY(pop(rdi);)
11000   if (thread != rax) {
11001     mov(thread, rax);
11002     pop(rax);
11003   }
11004 }
11005 
11006 #endif