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   assert_different_registers(result, tmp);
6280 
6281   // Only 64 bit platforms support GCs that require a tmp register
6282   // Only IN_HEAP loads require a thread_tmp register
6283   // OopHandle::resolve is an indirection like jobject.
6284   access_load_at(T_OBJECT, IN_ROOT | IN_CONCURRENT_ROOT,
6285                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
6286 }
6287 
6288 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
6289   // get mirror
6290   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6291   movptr(mirror, Address(method, Method::const_offset()));
6292   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6293   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6294   movptr(mirror, Address(mirror, mirror_offset));
6295   resolve_oop_handle(mirror, tmp);
6296 }
6297 
6298 void MacroAssembler::load_klass(Register dst, Register src) {
6299 #ifdef _LP64
6300   if (UseCompressedClassPointers) {
6301     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6302     decode_klass_not_null(dst);
6303   } else
6304 #endif
6305     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6306 }
6307 
6308 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6309   load_klass(dst, src);
6310   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6311 }
6312 
6313 void MacroAssembler::store_klass(Register dst, Register src) {
6314 #ifdef _LP64
6315   if (UseCompressedClassPointers) {
6316     encode_klass_not_null(src);
6317     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6318   } else
6319 #endif
6320     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6321 }
6322 
6323 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6324                                     Register tmp1, Register thread_tmp) {
6325   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6326   bool as_raw = (decorators & AS_RAW) != 0;
6327   if (as_raw) {
6328     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6329   } else {
6330     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6331   }
6332 }
6333 
6334 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6335                                      Register tmp1, Register tmp2) {
6336   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6337   bool as_raw = (decorators & AS_RAW) != 0;
6338   if (as_raw) {
6339     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6340   } else {
6341     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6342   }
6343 }
6344 
6345 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6346                                    Register thread_tmp, DecoratorSet decorators) {
6347   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6348 }
6349 
6350 // Doesn't do verfication, generates fixed size code
6351 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6352                                             Register thread_tmp, DecoratorSet decorators) {
6353   access_load_at(T_OBJECT, IN_HEAP | OOP_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6354 }
6355 
6356 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6357                                     Register tmp2, DecoratorSet decorators) {
6358   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6359 }
6360 
6361 // Used for storing NULLs.
6362 void MacroAssembler::store_heap_oop_null(Address dst) {
6363   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6364 }
6365 
6366 #ifdef _LP64
6367 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6368   if (UseCompressedClassPointers) {
6369     // Store to klass gap in destination
6370     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6371   }
6372 }
6373 
6374 #ifdef ASSERT
6375 void MacroAssembler::verify_heapbase(const char* msg) {
6376   assert (UseCompressedOops, "should be compressed");
6377   assert (Universe::heap() != NULL, "java heap should be initialized");
6378   if (CheckCompressedOops) {
6379     Label ok;
6380     push(rscratch1); // cmpptr trashes rscratch1
6381     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6382     jcc(Assembler::equal, ok);
6383     STOP(msg);
6384     bind(ok);
6385     pop(rscratch1);
6386   }
6387 }
6388 #endif
6389 
6390 // Algorithm must match oop.inline.hpp encode_heap_oop.
6391 void MacroAssembler::encode_heap_oop(Register r) {
6392 #ifdef ASSERT
6393   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6394 #endif
6395   verify_oop(r, "broken oop in encode_heap_oop");
6396   if (Universe::narrow_oop_base() == NULL) {
6397     if (Universe::narrow_oop_shift() != 0) {
6398       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6399       shrq(r, LogMinObjAlignmentInBytes);
6400     }
6401     return;
6402   }
6403   testq(r, r);
6404   cmovq(Assembler::equal, r, r12_heapbase);
6405   subq(r, r12_heapbase);
6406   shrq(r, LogMinObjAlignmentInBytes);
6407 }
6408 
6409 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6410 #ifdef ASSERT
6411   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6412   if (CheckCompressedOops) {
6413     Label ok;
6414     testq(r, r);
6415     jcc(Assembler::notEqual, ok);
6416     STOP("null oop passed to encode_heap_oop_not_null");
6417     bind(ok);
6418   }
6419 #endif
6420   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6421   if (Universe::narrow_oop_base() != NULL) {
6422     subq(r, r12_heapbase);
6423   }
6424   if (Universe::narrow_oop_shift() != 0) {
6425     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6426     shrq(r, LogMinObjAlignmentInBytes);
6427   }
6428 }
6429 
6430 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6431 #ifdef ASSERT
6432   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6433   if (CheckCompressedOops) {
6434     Label ok;
6435     testq(src, src);
6436     jcc(Assembler::notEqual, ok);
6437     STOP("null oop passed to encode_heap_oop_not_null2");
6438     bind(ok);
6439   }
6440 #endif
6441   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6442   if (dst != src) {
6443     movq(dst, src);
6444   }
6445   if (Universe::narrow_oop_base() != NULL) {
6446     subq(dst, r12_heapbase);
6447   }
6448   if (Universe::narrow_oop_shift() != 0) {
6449     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6450     shrq(dst, LogMinObjAlignmentInBytes);
6451   }
6452 }
6453 
6454 void  MacroAssembler::decode_heap_oop(Register r) {
6455 #ifdef ASSERT
6456   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6457 #endif
6458   if (Universe::narrow_oop_base() == NULL) {
6459     if (Universe::narrow_oop_shift() != 0) {
6460       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6461       shlq(r, LogMinObjAlignmentInBytes);
6462     }
6463   } else {
6464     Label done;
6465     shlq(r, LogMinObjAlignmentInBytes);
6466     jccb(Assembler::equal, done);
6467     addq(r, r12_heapbase);
6468     bind(done);
6469   }
6470   verify_oop(r, "broken oop in decode_heap_oop");
6471 }
6472 
6473 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6474   // Note: it will change flags
6475   assert (UseCompressedOops, "should only be used for compressed headers");
6476   assert (Universe::heap() != NULL, "java heap should be initialized");
6477   // Cannot assert, unverified entry point counts instructions (see .ad file)
6478   // vtableStubs also counts instructions in pd_code_size_limit.
6479   // Also do not verify_oop as this is called by verify_oop.
6480   if (Universe::narrow_oop_shift() != 0) {
6481     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6482     shlq(r, LogMinObjAlignmentInBytes);
6483     if (Universe::narrow_oop_base() != NULL) {
6484       addq(r, r12_heapbase);
6485     }
6486   } else {
6487     assert (Universe::narrow_oop_base() == NULL, "sanity");
6488   }
6489 }
6490 
6491 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6492   // Note: it will change flags
6493   assert (UseCompressedOops, "should only be used for compressed headers");
6494   assert (Universe::heap() != NULL, "java heap should be initialized");
6495   // Cannot assert, unverified entry point counts instructions (see .ad file)
6496   // vtableStubs also counts instructions in pd_code_size_limit.
6497   // Also do not verify_oop as this is called by verify_oop.
6498   if (Universe::narrow_oop_shift() != 0) {
6499     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6500     if (LogMinObjAlignmentInBytes == Address::times_8) {
6501       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6502     } else {
6503       if (dst != src) {
6504         movq(dst, src);
6505       }
6506       shlq(dst, LogMinObjAlignmentInBytes);
6507       if (Universe::narrow_oop_base() != NULL) {
6508         addq(dst, r12_heapbase);
6509       }
6510     }
6511   } else {
6512     assert (Universe::narrow_oop_base() == NULL, "sanity");
6513     if (dst != src) {
6514       movq(dst, src);
6515     }
6516   }
6517 }
6518 
6519 void MacroAssembler::encode_klass_not_null(Register r) {
6520   if (Universe::narrow_klass_base() != NULL) {
6521     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6522     assert(r != r12_heapbase, "Encoding a klass in r12");
6523     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6524     subq(r, r12_heapbase);
6525   }
6526   if (Universe::narrow_klass_shift() != 0) {
6527     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6528     shrq(r, LogKlassAlignmentInBytes);
6529   }
6530   if (Universe::narrow_klass_base() != NULL) {
6531     reinit_heapbase();
6532   }
6533 }
6534 
6535 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6536   if (dst == src) {
6537     encode_klass_not_null(src);
6538   } else {
6539     if (Universe::narrow_klass_base() != NULL) {
6540       mov64(dst, (int64_t)Universe::narrow_klass_base());
6541       negq(dst);
6542       addq(dst, src);
6543     } else {
6544       movptr(dst, src);
6545     }
6546     if (Universe::narrow_klass_shift() != 0) {
6547       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6548       shrq(dst, LogKlassAlignmentInBytes);
6549     }
6550   }
6551 }
6552 
6553 // Function instr_size_for_decode_klass_not_null() counts the instructions
6554 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6555 // when (Universe::heap() != NULL).  Hence, if the instructions they
6556 // generate change, then this method needs to be updated.
6557 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6558   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6559   if (Universe::narrow_klass_base() != NULL) {
6560     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6561     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6562   } else {
6563     // longest load decode klass function, mov64, leaq
6564     return 16;
6565   }
6566 }
6567 
6568 // !!! If the instructions that get generated here change then function
6569 // instr_size_for_decode_klass_not_null() needs to get updated.
6570 void  MacroAssembler::decode_klass_not_null(Register r) {
6571   // Note: it will change flags
6572   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6573   assert(r != r12_heapbase, "Decoding a klass in r12");
6574   // Cannot assert, unverified entry point counts instructions (see .ad file)
6575   // vtableStubs also counts instructions in pd_code_size_limit.
6576   // Also do not verify_oop as this is called by verify_oop.
6577   if (Universe::narrow_klass_shift() != 0) {
6578     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6579     shlq(r, LogKlassAlignmentInBytes);
6580   }
6581   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6582   if (Universe::narrow_klass_base() != NULL) {
6583     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6584     addq(r, r12_heapbase);
6585     reinit_heapbase();
6586   }
6587 }
6588 
6589 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6590   // Note: it will change flags
6591   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6592   if (dst == src) {
6593     decode_klass_not_null(dst);
6594   } else {
6595     // Cannot assert, unverified entry point counts instructions (see .ad file)
6596     // vtableStubs also counts instructions in pd_code_size_limit.
6597     // Also do not verify_oop as this is called by verify_oop.
6598     mov64(dst, (int64_t)Universe::narrow_klass_base());
6599     if (Universe::narrow_klass_shift() != 0) {
6600       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6601       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6602       leaq(dst, Address(dst, src, Address::times_8, 0));
6603     } else {
6604       addq(dst, src);
6605     }
6606   }
6607 }
6608 
6609 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6610   assert (UseCompressedOops, "should only be used for compressed headers");
6611   assert (Universe::heap() != NULL, "java heap should be initialized");
6612   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6613   int oop_index = oop_recorder()->find_index(obj);
6614   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6615   mov_narrow_oop(dst, oop_index, rspec);
6616 }
6617 
6618 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6619   assert (UseCompressedOops, "should only be used for compressed headers");
6620   assert (Universe::heap() != NULL, "java heap should be initialized");
6621   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6622   int oop_index = oop_recorder()->find_index(obj);
6623   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6624   mov_narrow_oop(dst, oop_index, rspec);
6625 }
6626 
6627 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6628   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6629   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6630   int klass_index = oop_recorder()->find_index(k);
6631   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6632   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6633 }
6634 
6635 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6636   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6637   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6638   int klass_index = oop_recorder()->find_index(k);
6639   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6640   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6641 }
6642 
6643 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6644   assert (UseCompressedOops, "should only be used for compressed headers");
6645   assert (Universe::heap() != NULL, "java heap should be initialized");
6646   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6647   int oop_index = oop_recorder()->find_index(obj);
6648   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6649   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6650 }
6651 
6652 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6653   assert (UseCompressedOops, "should only be used for compressed headers");
6654   assert (Universe::heap() != NULL, "java heap should be initialized");
6655   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6656   int oop_index = oop_recorder()->find_index(obj);
6657   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6658   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6659 }
6660 
6661 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6662   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6663   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6664   int klass_index = oop_recorder()->find_index(k);
6665   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6666   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6667 }
6668 
6669 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6670   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6671   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6672   int klass_index = oop_recorder()->find_index(k);
6673   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6674   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6675 }
6676 
6677 void MacroAssembler::reinit_heapbase() {
6678   if (UseCompressedOops || UseCompressedClassPointers) {
6679     if (Universe::heap() != NULL) {
6680       if (Universe::narrow_oop_base() == NULL) {
6681         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6682       } else {
6683         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6684       }
6685     } else {
6686       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6687     }
6688   }
6689 }
6690 
6691 #endif // _LP64
6692 
6693 // C2 compiled method's prolog code.
6694 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6695 
6696   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6697   // NativeJump::patch_verified_entry will be able to patch out the entry
6698   // code safely. The push to verify stack depth is ok at 5 bytes,
6699   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6700   // stack bang then we must use the 6 byte frame allocation even if
6701   // we have no frame. :-(
6702   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6703 
6704   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6705   // Remove word for return addr
6706   framesize -= wordSize;
6707   stack_bang_size -= wordSize;
6708 
6709   // Calls to C2R adapters often do not accept exceptional returns.
6710   // We require that their callers must bang for them.  But be careful, because
6711   // some VM calls (such as call site linkage) can use several kilobytes of
6712   // stack.  But the stack safety zone should account for that.
6713   // See bugs 4446381, 4468289, 4497237.
6714   if (stack_bang_size > 0) {
6715     generate_stack_overflow_check(stack_bang_size);
6716 
6717     // We always push rbp, so that on return to interpreter rbp, will be
6718     // restored correctly and we can correct the stack.
6719     push(rbp);
6720     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6721     if (PreserveFramePointer) {
6722       mov(rbp, rsp);
6723     }
6724     // Remove word for ebp
6725     framesize -= wordSize;
6726 
6727     // Create frame
6728     if (framesize) {
6729       subptr(rsp, framesize);
6730     }
6731   } else {
6732     // Create frame (force generation of a 4 byte immediate value)
6733     subptr_imm32(rsp, framesize);
6734 
6735     // Save RBP register now.
6736     framesize -= wordSize;
6737     movptr(Address(rsp, framesize), rbp);
6738     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6739     if (PreserveFramePointer) {
6740       movptr(rbp, rsp);
6741       if (framesize > 0) {
6742         addptr(rbp, framesize);
6743       }
6744     }
6745   }
6746 
6747   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6748     framesize -= wordSize;
6749     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6750   }
6751 
6752 #ifndef _LP64
6753   // If method sets FPU control word do it now
6754   if (fp_mode_24b) {
6755     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6756   }
6757   if (UseSSE >= 2 && VerifyFPU) {
6758     verify_FPU(0, "FPU stack must be clean on entry");
6759   }
6760 #endif
6761 
6762 #ifdef ASSERT
6763   if (VerifyStackAtCalls) {
6764     Label L;
6765     push(rax);
6766     mov(rax, rsp);
6767     andptr(rax, StackAlignmentInBytes-1);
6768     cmpptr(rax, StackAlignmentInBytes-wordSize);
6769     pop(rax);
6770     jcc(Assembler::equal, L);
6771     STOP("Stack is not properly aligned!");
6772     bind(L);
6773   }
6774 #endif
6775 
6776 }
6777 
6778 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6779   // cnt - number of qwords (8-byte words).
6780   // base - start address, qword aligned.
6781   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6782   assert(base==rdi, "base register must be edi for rep stos");
6783   assert(tmp==rax,   "tmp register must be eax for rep stos");
6784   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6785   assert(InitArrayShortSize % BytesPerLong == 0,
6786     "InitArrayShortSize should be the multiple of BytesPerLong");
6787 
6788   Label DONE;
6789 
6790   xorptr(tmp, tmp);
6791 
6792   if (!is_large) {
6793     Label LOOP, LONG;
6794     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6795     jccb(Assembler::greater, LONG);
6796 
6797     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6798 
6799     decrement(cnt);
6800     jccb(Assembler::negative, DONE); // Zero length
6801 
6802     // Use individual pointer-sized stores for small counts:
6803     BIND(LOOP);
6804     movptr(Address(base, cnt, Address::times_ptr), tmp);
6805     decrement(cnt);
6806     jccb(Assembler::greaterEqual, LOOP);
6807     jmpb(DONE);
6808 
6809     BIND(LONG);
6810   }
6811 
6812   // Use longer rep-prefixed ops for non-small counts:
6813   if (UseFastStosb) {
6814     shlptr(cnt, 3); // convert to number of bytes
6815     rep_stosb();
6816   } else {
6817     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6818     rep_stos();
6819   }
6820 
6821   BIND(DONE);
6822 }
6823 
6824 #ifdef COMPILER2
6825 
6826 // IndexOf for constant substrings with size >= 8 chars
6827 // which don't need to be loaded through stack.
6828 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6829                                       Register cnt1, Register cnt2,
6830                                       int int_cnt2,  Register result,
6831                                       XMMRegister vec, Register tmp,
6832                                       int ae) {
6833   ShortBranchVerifier sbv(this);
6834   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6835   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6836 
6837   // This method uses the pcmpestri instruction with bound registers
6838   //   inputs:
6839   //     xmm - substring
6840   //     rax - substring length (elements count)
6841   //     mem - scanned string
6842   //     rdx - string length (elements count)
6843   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6844   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6845   //   outputs:
6846   //     rcx - matched index in string
6847   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6848   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6849   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6850   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6851   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6852 
6853   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6854         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6855         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6856 
6857   // Note, inline_string_indexOf() generates checks:
6858   // if (substr.count > string.count) return -1;
6859   // if (substr.count == 0) return 0;
6860   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6861 
6862   // Load substring.
6863   if (ae == StrIntrinsicNode::UL) {
6864     pmovzxbw(vec, Address(str2, 0));
6865   } else {
6866     movdqu(vec, Address(str2, 0));
6867   }
6868   movl(cnt2, int_cnt2);
6869   movptr(result, str1); // string addr
6870 
6871   if (int_cnt2 > stride) {
6872     jmpb(SCAN_TO_SUBSTR);
6873 
6874     // Reload substr for rescan, this code
6875     // is executed only for large substrings (> 8 chars)
6876     bind(RELOAD_SUBSTR);
6877     if (ae == StrIntrinsicNode::UL) {
6878       pmovzxbw(vec, Address(str2, 0));
6879     } else {
6880       movdqu(vec, Address(str2, 0));
6881     }
6882     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6883 
6884     bind(RELOAD_STR);
6885     // We came here after the beginning of the substring was
6886     // matched but the rest of it was not so we need to search
6887     // again. Start from the next element after the previous match.
6888 
6889     // cnt2 is number of substring reminding elements and
6890     // cnt1 is number of string reminding elements when cmp failed.
6891     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6892     subl(cnt1, cnt2);
6893     addl(cnt1, int_cnt2);
6894     movl(cnt2, int_cnt2); // Now restore cnt2
6895 
6896     decrementl(cnt1);     // Shift to next element
6897     cmpl(cnt1, cnt2);
6898     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6899 
6900     addptr(result, (1<<scale1));
6901 
6902   } // (int_cnt2 > 8)
6903 
6904   // Scan string for start of substr in 16-byte vectors
6905   bind(SCAN_TO_SUBSTR);
6906   pcmpestri(vec, Address(result, 0), mode);
6907   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6908   subl(cnt1, stride);
6909   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6910   cmpl(cnt1, cnt2);
6911   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6912   addptr(result, 16);
6913   jmpb(SCAN_TO_SUBSTR);
6914 
6915   // Found a potential substr
6916   bind(FOUND_CANDIDATE);
6917   // Matched whole vector if first element matched (tmp(rcx) == 0).
6918   if (int_cnt2 == stride) {
6919     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6920   } else { // int_cnt2 > 8
6921     jccb(Assembler::overflow, FOUND_SUBSTR);
6922   }
6923   // After pcmpestri tmp(rcx) contains matched element index
6924   // Compute start addr of substr
6925   lea(result, Address(result, tmp, scale1));
6926 
6927   // Make sure string is still long enough
6928   subl(cnt1, tmp);
6929   cmpl(cnt1, cnt2);
6930   if (int_cnt2 == stride) {
6931     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6932   } else { // int_cnt2 > 8
6933     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6934   }
6935   // Left less then substring.
6936 
6937   bind(RET_NOT_FOUND);
6938   movl(result, -1);
6939   jmp(EXIT);
6940 
6941   if (int_cnt2 > stride) {
6942     // This code is optimized for the case when whole substring
6943     // is matched if its head is matched.
6944     bind(MATCH_SUBSTR_HEAD);
6945     pcmpestri(vec, Address(result, 0), mode);
6946     // Reload only string if does not match
6947     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6948 
6949     Label CONT_SCAN_SUBSTR;
6950     // Compare the rest of substring (> 8 chars).
6951     bind(FOUND_SUBSTR);
6952     // First 8 chars are already matched.
6953     negptr(cnt2);
6954     addptr(cnt2, stride);
6955 
6956     bind(SCAN_SUBSTR);
6957     subl(cnt1, stride);
6958     cmpl(cnt2, -stride); // Do not read beyond substring
6959     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6960     // Back-up strings to avoid reading beyond substring:
6961     // cnt1 = cnt1 - cnt2 + 8
6962     addl(cnt1, cnt2); // cnt2 is negative
6963     addl(cnt1, stride);
6964     movl(cnt2, stride); negptr(cnt2);
6965     bind(CONT_SCAN_SUBSTR);
6966     if (int_cnt2 < (int)G) {
6967       int tail_off1 = int_cnt2<<scale1;
6968       int tail_off2 = int_cnt2<<scale2;
6969       if (ae == StrIntrinsicNode::UL) {
6970         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6971       } else {
6972         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6973       }
6974       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6975     } else {
6976       // calculate index in register to avoid integer overflow (int_cnt2*2)
6977       movl(tmp, int_cnt2);
6978       addptr(tmp, cnt2);
6979       if (ae == StrIntrinsicNode::UL) {
6980         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6981       } else {
6982         movdqu(vec, Address(str2, tmp, scale2, 0));
6983       }
6984       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6985     }
6986     // Need to reload strings pointers if not matched whole vector
6987     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6988     addptr(cnt2, stride);
6989     jcc(Assembler::negative, SCAN_SUBSTR);
6990     // Fall through if found full substring
6991 
6992   } // (int_cnt2 > 8)
6993 
6994   bind(RET_FOUND);
6995   // Found result if we matched full small substring.
6996   // Compute substr offset
6997   subptr(result, str1);
6998   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6999     shrl(result, 1); // index
7000   }
7001   bind(EXIT);
7002 
7003 } // string_indexofC8
7004 
7005 // Small strings are loaded through stack if they cross page boundary.
7006 void MacroAssembler::string_indexof(Register str1, Register str2,
7007                                     Register cnt1, Register cnt2,
7008                                     int int_cnt2,  Register result,
7009                                     XMMRegister vec, Register tmp,
7010                                     int ae) {
7011   ShortBranchVerifier sbv(this);
7012   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7013   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7014 
7015   //
7016   // int_cnt2 is length of small (< 8 chars) constant substring
7017   // or (-1) for non constant substring in which case its length
7018   // is in cnt2 register.
7019   //
7020   // Note, inline_string_indexOf() generates checks:
7021   // if (substr.count > string.count) return -1;
7022   // if (substr.count == 0) return 0;
7023   //
7024   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7025   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7026   // This method uses the pcmpestri instruction with bound registers
7027   //   inputs:
7028   //     xmm - substring
7029   //     rax - substring length (elements count)
7030   //     mem - scanned string
7031   //     rdx - string length (elements count)
7032   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7033   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7034   //   outputs:
7035   //     rcx - matched index in string
7036   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7037   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7038   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7039   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7040 
7041   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7042         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7043         FOUND_CANDIDATE;
7044 
7045   { //========================================================
7046     // We don't know where these strings are located
7047     // and we can't read beyond them. Load them through stack.
7048     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7049 
7050     movptr(tmp, rsp); // save old SP
7051 
7052     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7053       if (int_cnt2 == (1>>scale2)) { // One byte
7054         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7055         load_unsigned_byte(result, Address(str2, 0));
7056         movdl(vec, result); // move 32 bits
7057       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7058         // Not enough header space in 32-bit VM: 12+3 = 15.
7059         movl(result, Address(str2, -1));
7060         shrl(result, 8);
7061         movdl(vec, result); // move 32 bits
7062       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7063         load_unsigned_short(result, Address(str2, 0));
7064         movdl(vec, result); // move 32 bits
7065       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7066         movdl(vec, Address(str2, 0)); // move 32 bits
7067       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7068         movq(vec, Address(str2, 0));  // move 64 bits
7069       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7070         // Array header size is 12 bytes in 32-bit VM
7071         // + 6 bytes for 3 chars == 18 bytes,
7072         // enough space to load vec and shift.
7073         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7074         if (ae == StrIntrinsicNode::UL) {
7075           int tail_off = int_cnt2-8;
7076           pmovzxbw(vec, Address(str2, tail_off));
7077           psrldq(vec, -2*tail_off);
7078         }
7079         else {
7080           int tail_off = int_cnt2*(1<<scale2);
7081           movdqu(vec, Address(str2, tail_off-16));
7082           psrldq(vec, 16-tail_off);
7083         }
7084       }
7085     } else { // not constant substring
7086       cmpl(cnt2, stride);
7087       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7088 
7089       // We can read beyond string if srt+16 does not cross page boundary
7090       // since heaps are aligned and mapped by pages.
7091       assert(os::vm_page_size() < (int)G, "default page should be small");
7092       movl(result, str2); // We need only low 32 bits
7093       andl(result, (os::vm_page_size()-1));
7094       cmpl(result, (os::vm_page_size()-16));
7095       jccb(Assembler::belowEqual, CHECK_STR);
7096 
7097       // Move small strings to stack to allow load 16 bytes into vec.
7098       subptr(rsp, 16);
7099       int stk_offset = wordSize-(1<<scale2);
7100       push(cnt2);
7101 
7102       bind(COPY_SUBSTR);
7103       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7104         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7105         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7106       } else if (ae == StrIntrinsicNode::UU) {
7107         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7108         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7109       }
7110       decrement(cnt2);
7111       jccb(Assembler::notZero, COPY_SUBSTR);
7112 
7113       pop(cnt2);
7114       movptr(str2, rsp);  // New substring address
7115     } // non constant
7116 
7117     bind(CHECK_STR);
7118     cmpl(cnt1, stride);
7119     jccb(Assembler::aboveEqual, BIG_STRINGS);
7120 
7121     // Check cross page boundary.
7122     movl(result, str1); // We need only low 32 bits
7123     andl(result, (os::vm_page_size()-1));
7124     cmpl(result, (os::vm_page_size()-16));
7125     jccb(Assembler::belowEqual, BIG_STRINGS);
7126 
7127     subptr(rsp, 16);
7128     int stk_offset = -(1<<scale1);
7129     if (int_cnt2 < 0) { // not constant
7130       push(cnt2);
7131       stk_offset += wordSize;
7132     }
7133     movl(cnt2, cnt1);
7134 
7135     bind(COPY_STR);
7136     if (ae == StrIntrinsicNode::LL) {
7137       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7138       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7139     } else {
7140       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7141       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7142     }
7143     decrement(cnt2);
7144     jccb(Assembler::notZero, COPY_STR);
7145 
7146     if (int_cnt2 < 0) { // not constant
7147       pop(cnt2);
7148     }
7149     movptr(str1, rsp);  // New string address
7150 
7151     bind(BIG_STRINGS);
7152     // Load substring.
7153     if (int_cnt2 < 0) { // -1
7154       if (ae == StrIntrinsicNode::UL) {
7155         pmovzxbw(vec, Address(str2, 0));
7156       } else {
7157         movdqu(vec, Address(str2, 0));
7158       }
7159       push(cnt2);       // substr count
7160       push(str2);       // substr addr
7161       push(str1);       // string addr
7162     } else {
7163       // Small (< 8 chars) constant substrings are loaded already.
7164       movl(cnt2, int_cnt2);
7165     }
7166     push(tmp);  // original SP
7167 
7168   } // Finished loading
7169 
7170   //========================================================
7171   // Start search
7172   //
7173 
7174   movptr(result, str1); // string addr
7175 
7176   if (int_cnt2  < 0) {  // Only for non constant substring
7177     jmpb(SCAN_TO_SUBSTR);
7178 
7179     // SP saved at sp+0
7180     // String saved at sp+1*wordSize
7181     // Substr saved at sp+2*wordSize
7182     // Substr count saved at sp+3*wordSize
7183 
7184     // Reload substr for rescan, this code
7185     // is executed only for large substrings (> 8 chars)
7186     bind(RELOAD_SUBSTR);
7187     movptr(str2, Address(rsp, 2*wordSize));
7188     movl(cnt2, Address(rsp, 3*wordSize));
7189     if (ae == StrIntrinsicNode::UL) {
7190       pmovzxbw(vec, Address(str2, 0));
7191     } else {
7192       movdqu(vec, Address(str2, 0));
7193     }
7194     // We came here after the beginning of the substring was
7195     // matched but the rest of it was not so we need to search
7196     // again. Start from the next element after the previous match.
7197     subptr(str1, result); // Restore counter
7198     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7199       shrl(str1, 1);
7200     }
7201     addl(cnt1, str1);
7202     decrementl(cnt1);   // Shift to next element
7203     cmpl(cnt1, cnt2);
7204     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7205 
7206     addptr(result, (1<<scale1));
7207   } // non constant
7208 
7209   // Scan string for start of substr in 16-byte vectors
7210   bind(SCAN_TO_SUBSTR);
7211   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7212   pcmpestri(vec, Address(result, 0), mode);
7213   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7214   subl(cnt1, stride);
7215   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7216   cmpl(cnt1, cnt2);
7217   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7218   addptr(result, 16);
7219 
7220   bind(ADJUST_STR);
7221   cmpl(cnt1, stride); // Do not read beyond string
7222   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7223   // Back-up string to avoid reading beyond string.
7224   lea(result, Address(result, cnt1, scale1, -16));
7225   movl(cnt1, stride);
7226   jmpb(SCAN_TO_SUBSTR);
7227 
7228   // Found a potential substr
7229   bind(FOUND_CANDIDATE);
7230   // After pcmpestri tmp(rcx) contains matched element index
7231 
7232   // Make sure string is still long enough
7233   subl(cnt1, tmp);
7234   cmpl(cnt1, cnt2);
7235   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7236   // Left less then substring.
7237 
7238   bind(RET_NOT_FOUND);
7239   movl(result, -1);
7240   jmpb(CLEANUP);
7241 
7242   bind(FOUND_SUBSTR);
7243   // Compute start addr of substr
7244   lea(result, Address(result, tmp, scale1));
7245   if (int_cnt2 > 0) { // Constant substring
7246     // Repeat search for small substring (< 8 chars)
7247     // from new point without reloading substring.
7248     // Have to check that we don't read beyond string.
7249     cmpl(tmp, stride-int_cnt2);
7250     jccb(Assembler::greater, ADJUST_STR);
7251     // Fall through if matched whole substring.
7252   } else { // non constant
7253     assert(int_cnt2 == -1, "should be != 0");
7254 
7255     addl(tmp, cnt2);
7256     // Found result if we matched whole substring.
7257     cmpl(tmp, stride);
7258     jccb(Assembler::lessEqual, RET_FOUND);
7259 
7260     // Repeat search for small substring (<= 8 chars)
7261     // from new point 'str1' without reloading substring.
7262     cmpl(cnt2, stride);
7263     // Have to check that we don't read beyond string.
7264     jccb(Assembler::lessEqual, ADJUST_STR);
7265 
7266     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7267     // Compare the rest of substring (> 8 chars).
7268     movptr(str1, result);
7269 
7270     cmpl(tmp, cnt2);
7271     // First 8 chars are already matched.
7272     jccb(Assembler::equal, CHECK_NEXT);
7273 
7274     bind(SCAN_SUBSTR);
7275     pcmpestri(vec, Address(str1, 0), mode);
7276     // Need to reload strings pointers if not matched whole vector
7277     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7278 
7279     bind(CHECK_NEXT);
7280     subl(cnt2, stride);
7281     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7282     addptr(str1, 16);
7283     if (ae == StrIntrinsicNode::UL) {
7284       addptr(str2, 8);
7285     } else {
7286       addptr(str2, 16);
7287     }
7288     subl(cnt1, stride);
7289     cmpl(cnt2, stride); // Do not read beyond substring
7290     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7291     // Back-up strings to avoid reading beyond substring.
7292 
7293     if (ae == StrIntrinsicNode::UL) {
7294       lea(str2, Address(str2, cnt2, scale2, -8));
7295       lea(str1, Address(str1, cnt2, scale1, -16));
7296     } else {
7297       lea(str2, Address(str2, cnt2, scale2, -16));
7298       lea(str1, Address(str1, cnt2, scale1, -16));
7299     }
7300     subl(cnt1, cnt2);
7301     movl(cnt2, stride);
7302     addl(cnt1, stride);
7303     bind(CONT_SCAN_SUBSTR);
7304     if (ae == StrIntrinsicNode::UL) {
7305       pmovzxbw(vec, Address(str2, 0));
7306     } else {
7307       movdqu(vec, Address(str2, 0));
7308     }
7309     jmp(SCAN_SUBSTR);
7310 
7311     bind(RET_FOUND_LONG);
7312     movptr(str1, Address(rsp, wordSize));
7313   } // non constant
7314 
7315   bind(RET_FOUND);
7316   // Compute substr offset
7317   subptr(result, str1);
7318   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7319     shrl(result, 1); // index
7320   }
7321   bind(CLEANUP);
7322   pop(rsp); // restore SP
7323 
7324 } // string_indexof
7325 
7326 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7327                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7328   ShortBranchVerifier sbv(this);
7329   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7330 
7331   int stride = 8;
7332 
7333   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7334         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7335         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7336         FOUND_SEQ_CHAR, DONE_LABEL;
7337 
7338   movptr(result, str1);
7339   if (UseAVX >= 2) {
7340     cmpl(cnt1, stride);
7341     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7342     cmpl(cnt1, 2*stride);
7343     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7344     movdl(vec1, ch);
7345     vpbroadcastw(vec1, vec1);
7346     vpxor(vec2, vec2);
7347     movl(tmp, cnt1);
7348     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7349     andl(cnt1,0x0000000F);  //tail count (in chars)
7350 
7351     bind(SCAN_TO_16_CHAR_LOOP);
7352     vmovdqu(vec3, Address(result, 0));
7353     vpcmpeqw(vec3, vec3, vec1, 1);
7354     vptest(vec2, vec3);
7355     jcc(Assembler::carryClear, FOUND_CHAR);
7356     addptr(result, 32);
7357     subl(tmp, 2*stride);
7358     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7359     jmp(SCAN_TO_8_CHAR);
7360     bind(SCAN_TO_8_CHAR_INIT);
7361     movdl(vec1, ch);
7362     pshuflw(vec1, vec1, 0x00);
7363     pshufd(vec1, vec1, 0);
7364     pxor(vec2, vec2);
7365   }
7366   bind(SCAN_TO_8_CHAR);
7367   cmpl(cnt1, stride);
7368   if (UseAVX >= 2) {
7369     jcc(Assembler::less, SCAN_TO_CHAR);
7370   } else {
7371     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7372     movdl(vec1, ch);
7373     pshuflw(vec1, vec1, 0x00);
7374     pshufd(vec1, vec1, 0);
7375     pxor(vec2, vec2);
7376   }
7377   movl(tmp, cnt1);
7378   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7379   andl(cnt1,0x00000007);  //tail count (in chars)
7380 
7381   bind(SCAN_TO_8_CHAR_LOOP);
7382   movdqu(vec3, Address(result, 0));
7383   pcmpeqw(vec3, vec1);
7384   ptest(vec2, vec3);
7385   jcc(Assembler::carryClear, FOUND_CHAR);
7386   addptr(result, 16);
7387   subl(tmp, stride);
7388   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7389   bind(SCAN_TO_CHAR);
7390   testl(cnt1, cnt1);
7391   jcc(Assembler::zero, RET_NOT_FOUND);
7392   bind(SCAN_TO_CHAR_LOOP);
7393   load_unsigned_short(tmp, Address(result, 0));
7394   cmpl(ch, tmp);
7395   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7396   addptr(result, 2);
7397   subl(cnt1, 1);
7398   jccb(Assembler::zero, RET_NOT_FOUND);
7399   jmp(SCAN_TO_CHAR_LOOP);
7400 
7401   bind(RET_NOT_FOUND);
7402   movl(result, -1);
7403   jmpb(DONE_LABEL);
7404 
7405   bind(FOUND_CHAR);
7406   if (UseAVX >= 2) {
7407     vpmovmskb(tmp, vec3);
7408   } else {
7409     pmovmskb(tmp, vec3);
7410   }
7411   bsfl(ch, tmp);
7412   addl(result, ch);
7413 
7414   bind(FOUND_SEQ_CHAR);
7415   subptr(result, str1);
7416   shrl(result, 1);
7417 
7418   bind(DONE_LABEL);
7419 } // string_indexof_char
7420 
7421 // helper function for string_compare
7422 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7423                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7424                                         Address::ScaleFactor scale2, Register index, int ae) {
7425   if (ae == StrIntrinsicNode::LL) {
7426     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7427     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7428   } else if (ae == StrIntrinsicNode::UU) {
7429     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7430     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7431   } else {
7432     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7433     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7434   }
7435 }
7436 
7437 // Compare strings, used for char[] and byte[].
7438 void MacroAssembler::string_compare(Register str1, Register str2,
7439                                     Register cnt1, Register cnt2, Register result,
7440                                     XMMRegister vec1, int ae) {
7441   ShortBranchVerifier sbv(this);
7442   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7443   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7444   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7445   int stride2x2 = 0x40;
7446   Address::ScaleFactor scale = Address::no_scale;
7447   Address::ScaleFactor scale1 = Address::no_scale;
7448   Address::ScaleFactor scale2 = Address::no_scale;
7449 
7450   if (ae != StrIntrinsicNode::LL) {
7451     stride2x2 = 0x20;
7452   }
7453 
7454   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7455     shrl(cnt2, 1);
7456   }
7457   // Compute the minimum of the string lengths and the
7458   // difference of the string lengths (stack).
7459   // Do the conditional move stuff
7460   movl(result, cnt1);
7461   subl(cnt1, cnt2);
7462   push(cnt1);
7463   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7464 
7465   // Is the minimum length zero?
7466   testl(cnt2, cnt2);
7467   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7468   if (ae == StrIntrinsicNode::LL) {
7469     // Load first bytes
7470     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7471     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7472   } else if (ae == StrIntrinsicNode::UU) {
7473     // Load first characters
7474     load_unsigned_short(result, Address(str1, 0));
7475     load_unsigned_short(cnt1, Address(str2, 0));
7476   } else {
7477     load_unsigned_byte(result, Address(str1, 0));
7478     load_unsigned_short(cnt1, Address(str2, 0));
7479   }
7480   subl(result, cnt1);
7481   jcc(Assembler::notZero,  POP_LABEL);
7482 
7483   if (ae == StrIntrinsicNode::UU) {
7484     // Divide length by 2 to get number of chars
7485     shrl(cnt2, 1);
7486   }
7487   cmpl(cnt2, 1);
7488   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7489 
7490   // Check if the strings start at the same location and setup scale and stride
7491   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7492     cmpptr(str1, str2);
7493     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7494     if (ae == StrIntrinsicNode::LL) {
7495       scale = Address::times_1;
7496       stride = 16;
7497     } else {
7498       scale = Address::times_2;
7499       stride = 8;
7500     }
7501   } else {
7502     scale1 = Address::times_1;
7503     scale2 = Address::times_2;
7504     // scale not used
7505     stride = 8;
7506   }
7507 
7508   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7509     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7510     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7511     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7512     Label COMPARE_TAIL_LONG;
7513     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7514 
7515     int pcmpmask = 0x19;
7516     if (ae == StrIntrinsicNode::LL) {
7517       pcmpmask &= ~0x01;
7518     }
7519 
7520     // Setup to compare 16-chars (32-bytes) vectors,
7521     // start from first character again because it has aligned address.
7522     if (ae == StrIntrinsicNode::LL) {
7523       stride2 = 32;
7524     } else {
7525       stride2 = 16;
7526     }
7527     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7528       adr_stride = stride << scale;
7529     } else {
7530       adr_stride1 = 8;  //stride << scale1;
7531       adr_stride2 = 16; //stride << scale2;
7532     }
7533 
7534     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7535     // rax and rdx are used by pcmpestri as elements counters
7536     movl(result, cnt2);
7537     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7538     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7539 
7540     // fast path : compare first 2 8-char vectors.
7541     bind(COMPARE_16_CHARS);
7542     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7543       movdqu(vec1, Address(str1, 0));
7544     } else {
7545       pmovzxbw(vec1, Address(str1, 0));
7546     }
7547     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7548     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7549 
7550     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7551       movdqu(vec1, Address(str1, adr_stride));
7552       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7553     } else {
7554       pmovzxbw(vec1, Address(str1, adr_stride1));
7555       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7556     }
7557     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7558     addl(cnt1, stride);
7559 
7560     // Compare the characters at index in cnt1
7561     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7562     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7563     subl(result, cnt2);
7564     jmp(POP_LABEL);
7565 
7566     // Setup the registers to start vector comparison loop
7567     bind(COMPARE_WIDE_VECTORS);
7568     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7569       lea(str1, Address(str1, result, scale));
7570       lea(str2, Address(str2, result, scale));
7571     } else {
7572       lea(str1, Address(str1, result, scale1));
7573       lea(str2, Address(str2, result, scale2));
7574     }
7575     subl(result, stride2);
7576     subl(cnt2, stride2);
7577     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7578     negptr(result);
7579 
7580     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7581     bind(COMPARE_WIDE_VECTORS_LOOP);
7582 
7583 #ifdef _LP64
7584     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7585       cmpl(cnt2, stride2x2);
7586       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7587       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7588       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7589 
7590       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7591       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7592         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7593         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7594       } else {
7595         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7596         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7597       }
7598       kortestql(k7, k7);
7599       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7600       addptr(result, stride2x2);  // update since we already compared at this addr
7601       subl(cnt2, stride2x2);      // and sub the size too
7602       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7603 
7604       vpxor(vec1, vec1);
7605       jmpb(COMPARE_WIDE_TAIL);
7606     }//if (VM_Version::supports_avx512vlbw())
7607 #endif // _LP64
7608 
7609 
7610     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7611     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7612       vmovdqu(vec1, Address(str1, result, scale));
7613       vpxor(vec1, Address(str2, result, scale));
7614     } else {
7615       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7616       vpxor(vec1, Address(str2, result, scale2));
7617     }
7618     vptest(vec1, vec1);
7619     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7620     addptr(result, stride2);
7621     subl(cnt2, stride2);
7622     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7623     // clean upper bits of YMM registers
7624     vpxor(vec1, vec1);
7625 
7626     // compare wide vectors tail
7627     bind(COMPARE_WIDE_TAIL);
7628     testptr(result, result);
7629     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7630 
7631     movl(result, stride2);
7632     movl(cnt2, result);
7633     negptr(result);
7634     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7635 
7636     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7637     bind(VECTOR_NOT_EQUAL);
7638     // clean upper bits of YMM registers
7639     vpxor(vec1, vec1);
7640     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7641       lea(str1, Address(str1, result, scale));
7642       lea(str2, Address(str2, result, scale));
7643     } else {
7644       lea(str1, Address(str1, result, scale1));
7645       lea(str2, Address(str2, result, scale2));
7646     }
7647     jmp(COMPARE_16_CHARS);
7648 
7649     // Compare tail chars, length between 1 to 15 chars
7650     bind(COMPARE_TAIL_LONG);
7651     movl(cnt2, result);
7652     cmpl(cnt2, stride);
7653     jcc(Assembler::less, COMPARE_SMALL_STR);
7654 
7655     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7656       movdqu(vec1, Address(str1, 0));
7657     } else {
7658       pmovzxbw(vec1, Address(str1, 0));
7659     }
7660     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7661     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7662     subptr(cnt2, stride);
7663     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7664     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7665       lea(str1, Address(str1, result, scale));
7666       lea(str2, Address(str2, result, scale));
7667     } else {
7668       lea(str1, Address(str1, result, scale1));
7669       lea(str2, Address(str2, result, scale2));
7670     }
7671     negptr(cnt2);
7672     jmpb(WHILE_HEAD_LABEL);
7673 
7674     bind(COMPARE_SMALL_STR);
7675   } else if (UseSSE42Intrinsics) {
7676     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7677     int pcmpmask = 0x19;
7678     // Setup to compare 8-char (16-byte) vectors,
7679     // start from first character again because it has aligned address.
7680     movl(result, cnt2);
7681     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7682     if (ae == StrIntrinsicNode::LL) {
7683       pcmpmask &= ~0x01;
7684     }
7685     jcc(Assembler::zero, COMPARE_TAIL);
7686     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7687       lea(str1, Address(str1, result, scale));
7688       lea(str2, Address(str2, result, scale));
7689     } else {
7690       lea(str1, Address(str1, result, scale1));
7691       lea(str2, Address(str2, result, scale2));
7692     }
7693     negptr(result);
7694 
7695     // pcmpestri
7696     //   inputs:
7697     //     vec1- substring
7698     //     rax - negative string length (elements count)
7699     //     mem - scanned string
7700     //     rdx - string length (elements count)
7701     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7702     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7703     //   outputs:
7704     //     rcx - first mismatched element index
7705     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7706 
7707     bind(COMPARE_WIDE_VECTORS);
7708     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7709       movdqu(vec1, Address(str1, result, scale));
7710       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7711     } else {
7712       pmovzxbw(vec1, Address(str1, result, scale1));
7713       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7714     }
7715     // After pcmpestri cnt1(rcx) contains mismatched element index
7716 
7717     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7718     addptr(result, stride);
7719     subptr(cnt2, stride);
7720     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7721 
7722     // compare wide vectors tail
7723     testptr(result, result);
7724     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7725 
7726     movl(cnt2, stride);
7727     movl(result, stride);
7728     negptr(result);
7729     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7730       movdqu(vec1, Address(str1, result, scale));
7731       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7732     } else {
7733       pmovzxbw(vec1, Address(str1, result, scale1));
7734       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7735     }
7736     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7737 
7738     // Mismatched characters in the vectors
7739     bind(VECTOR_NOT_EQUAL);
7740     addptr(cnt1, result);
7741     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7742     subl(result, cnt2);
7743     jmpb(POP_LABEL);
7744 
7745     bind(COMPARE_TAIL); // limit is zero
7746     movl(cnt2, result);
7747     // Fallthru to tail compare
7748   }
7749   // Shift str2 and str1 to the end of the arrays, negate min
7750   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7751     lea(str1, Address(str1, cnt2, scale));
7752     lea(str2, Address(str2, cnt2, scale));
7753   } else {
7754     lea(str1, Address(str1, cnt2, scale1));
7755     lea(str2, Address(str2, cnt2, scale2));
7756   }
7757   decrementl(cnt2);  // first character was compared already
7758   negptr(cnt2);
7759 
7760   // Compare the rest of the elements
7761   bind(WHILE_HEAD_LABEL);
7762   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7763   subl(result, cnt1);
7764   jccb(Assembler::notZero, POP_LABEL);
7765   increment(cnt2);
7766   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7767 
7768   // Strings are equal up to min length.  Return the length difference.
7769   bind(LENGTH_DIFF_LABEL);
7770   pop(result);
7771   if (ae == StrIntrinsicNode::UU) {
7772     // Divide diff by 2 to get number of chars
7773     sarl(result, 1);
7774   }
7775   jmpb(DONE_LABEL);
7776 
7777 #ifdef _LP64
7778   if (VM_Version::supports_avx512vlbw()) {
7779 
7780     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7781 
7782     kmovql(cnt1, k7);
7783     notq(cnt1);
7784     bsfq(cnt2, cnt1);
7785     if (ae != StrIntrinsicNode::LL) {
7786       // Divide diff by 2 to get number of chars
7787       sarl(cnt2, 1);
7788     }
7789     addq(result, cnt2);
7790     if (ae == StrIntrinsicNode::LL) {
7791       load_unsigned_byte(cnt1, Address(str2, result));
7792       load_unsigned_byte(result, Address(str1, result));
7793     } else if (ae == StrIntrinsicNode::UU) {
7794       load_unsigned_short(cnt1, Address(str2, result, scale));
7795       load_unsigned_short(result, Address(str1, result, scale));
7796     } else {
7797       load_unsigned_short(cnt1, Address(str2, result, scale2));
7798       load_unsigned_byte(result, Address(str1, result, scale1));
7799     }
7800     subl(result, cnt1);
7801     jmpb(POP_LABEL);
7802   }//if (VM_Version::supports_avx512vlbw())
7803 #endif // _LP64
7804 
7805   // Discard the stored length difference
7806   bind(POP_LABEL);
7807   pop(cnt1);
7808 
7809   // That's it
7810   bind(DONE_LABEL);
7811   if(ae == StrIntrinsicNode::UL) {
7812     negl(result);
7813   }
7814 
7815 }
7816 
7817 // Search for Non-ASCII character (Negative byte value) in a byte array,
7818 // return true if it has any and false otherwise.
7819 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7820 //   @HotSpotIntrinsicCandidate
7821 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7822 //     for (int i = off; i < off + len; i++) {
7823 //       if (ba[i] < 0) {
7824 //         return true;
7825 //       }
7826 //     }
7827 //     return false;
7828 //   }
7829 void MacroAssembler::has_negatives(Register ary1, Register len,
7830   Register result, Register tmp1,
7831   XMMRegister vec1, XMMRegister vec2) {
7832   // rsi: byte array
7833   // rcx: len
7834   // rax: result
7835   ShortBranchVerifier sbv(this);
7836   assert_different_registers(ary1, len, result, tmp1);
7837   assert_different_registers(vec1, vec2);
7838   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7839 
7840   // len == 0
7841   testl(len, len);
7842   jcc(Assembler::zero, FALSE_LABEL);
7843 
7844   if ((UseAVX > 2) && // AVX512
7845     VM_Version::supports_avx512vlbw() &&
7846     VM_Version::supports_bmi2()) {
7847 
7848     set_vector_masking();  // opening of the stub context for programming mask registers
7849 
7850     Label test_64_loop, test_tail;
7851     Register tmp3_aliased = len;
7852 
7853     movl(tmp1, len);
7854     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7855 
7856     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7857     andl(len, ~(64 - 1));    // vector count (in chars)
7858     jccb(Assembler::zero, test_tail);
7859 
7860     lea(ary1, Address(ary1, len, Address::times_1));
7861     negptr(len);
7862 
7863     bind(test_64_loop);
7864     // Check whether our 64 elements of size byte contain negatives
7865     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7866     kortestql(k2, k2);
7867     jcc(Assembler::notZero, TRUE_LABEL);
7868 
7869     addptr(len, 64);
7870     jccb(Assembler::notZero, test_64_loop);
7871 
7872 
7873     bind(test_tail);
7874     // bail out when there is nothing to be done
7875     testl(tmp1, -1);
7876     jcc(Assembler::zero, FALSE_LABEL);
7877 
7878     // Save k1
7879     kmovql(k3, k1);
7880 
7881     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7882 #ifdef _LP64
7883     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7884     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7885     notq(tmp3_aliased);
7886     kmovql(k1, tmp3_aliased);
7887 #else
7888     Label k_init;
7889     jmp(k_init);
7890 
7891     // We could not read 64-bits from a general purpose register thus we move
7892     // data required to compose 64 1's to the instruction stream
7893     // We emit 64 byte wide series of elements from 0..63 which later on would
7894     // be used as a compare targets with tail count contained in tmp1 register.
7895     // Result would be a k1 register having tmp1 consecutive number or 1
7896     // counting from least significant bit.
7897     address tmp = pc();
7898     emit_int64(0x0706050403020100);
7899     emit_int64(0x0F0E0D0C0B0A0908);
7900     emit_int64(0x1716151413121110);
7901     emit_int64(0x1F1E1D1C1B1A1918);
7902     emit_int64(0x2726252423222120);
7903     emit_int64(0x2F2E2D2C2B2A2928);
7904     emit_int64(0x3736353433323130);
7905     emit_int64(0x3F3E3D3C3B3A3938);
7906 
7907     bind(k_init);
7908     lea(len, InternalAddress(tmp));
7909     // create mask to test for negative byte inside a vector
7910     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7911     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7912 
7913 #endif
7914     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7915     ktestq(k2, k1);
7916     // Restore k1
7917     kmovql(k1, k3);
7918     jcc(Assembler::notZero, TRUE_LABEL);
7919 
7920     jmp(FALSE_LABEL);
7921 
7922     clear_vector_masking();   // closing of the stub context for programming mask registers
7923   } else {
7924     movl(result, len); // copy
7925 
7926     if (UseAVX == 2 && UseSSE >= 2) {
7927       // With AVX2, use 32-byte vector compare
7928       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7929 
7930       // Compare 32-byte vectors
7931       andl(result, 0x0000001f);  //   tail count (in bytes)
7932       andl(len, 0xffffffe0);   // vector count (in bytes)
7933       jccb(Assembler::zero, COMPARE_TAIL);
7934 
7935       lea(ary1, Address(ary1, len, Address::times_1));
7936       negptr(len);
7937 
7938       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7939       movdl(vec2, tmp1);
7940       vpbroadcastd(vec2, vec2);
7941 
7942       bind(COMPARE_WIDE_VECTORS);
7943       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7944       vptest(vec1, vec2);
7945       jccb(Assembler::notZero, TRUE_LABEL);
7946       addptr(len, 32);
7947       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7948 
7949       testl(result, result);
7950       jccb(Assembler::zero, FALSE_LABEL);
7951 
7952       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7953       vptest(vec1, vec2);
7954       jccb(Assembler::notZero, TRUE_LABEL);
7955       jmpb(FALSE_LABEL);
7956 
7957       bind(COMPARE_TAIL); // len is zero
7958       movl(len, result);
7959       // Fallthru to tail compare
7960     } else if (UseSSE42Intrinsics) {
7961       // With SSE4.2, use double quad vector compare
7962       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7963 
7964       // Compare 16-byte vectors
7965       andl(result, 0x0000000f);  //   tail count (in bytes)
7966       andl(len, 0xfffffff0);   // vector count (in bytes)
7967       jccb(Assembler::zero, COMPARE_TAIL);
7968 
7969       lea(ary1, Address(ary1, len, Address::times_1));
7970       negptr(len);
7971 
7972       movl(tmp1, 0x80808080);
7973       movdl(vec2, tmp1);
7974       pshufd(vec2, vec2, 0);
7975 
7976       bind(COMPARE_WIDE_VECTORS);
7977       movdqu(vec1, Address(ary1, len, Address::times_1));
7978       ptest(vec1, vec2);
7979       jccb(Assembler::notZero, TRUE_LABEL);
7980       addptr(len, 16);
7981       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7982 
7983       testl(result, result);
7984       jccb(Assembler::zero, FALSE_LABEL);
7985 
7986       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7987       ptest(vec1, vec2);
7988       jccb(Assembler::notZero, TRUE_LABEL);
7989       jmpb(FALSE_LABEL);
7990 
7991       bind(COMPARE_TAIL); // len is zero
7992       movl(len, result);
7993       // Fallthru to tail compare
7994     }
7995   }
7996   // Compare 4-byte vectors
7997   andl(len, 0xfffffffc); // vector count (in bytes)
7998   jccb(Assembler::zero, COMPARE_CHAR);
7999 
8000   lea(ary1, Address(ary1, len, Address::times_1));
8001   negptr(len);
8002 
8003   bind(COMPARE_VECTORS);
8004   movl(tmp1, Address(ary1, len, Address::times_1));
8005   andl(tmp1, 0x80808080);
8006   jccb(Assembler::notZero, TRUE_LABEL);
8007   addptr(len, 4);
8008   jcc(Assembler::notZero, COMPARE_VECTORS);
8009 
8010   // Compare trailing char (final 2 bytes), if any
8011   bind(COMPARE_CHAR);
8012   testl(result, 0x2);   // tail  char
8013   jccb(Assembler::zero, COMPARE_BYTE);
8014   load_unsigned_short(tmp1, Address(ary1, 0));
8015   andl(tmp1, 0x00008080);
8016   jccb(Assembler::notZero, TRUE_LABEL);
8017   subptr(result, 2);
8018   lea(ary1, Address(ary1, 2));
8019 
8020   bind(COMPARE_BYTE);
8021   testl(result, 0x1);   // tail  byte
8022   jccb(Assembler::zero, FALSE_LABEL);
8023   load_unsigned_byte(tmp1, Address(ary1, 0));
8024   andl(tmp1, 0x00000080);
8025   jccb(Assembler::notEqual, TRUE_LABEL);
8026   jmpb(FALSE_LABEL);
8027 
8028   bind(TRUE_LABEL);
8029   movl(result, 1);   // return true
8030   jmpb(DONE);
8031 
8032   bind(FALSE_LABEL);
8033   xorl(result, result); // return false
8034 
8035   // That's it
8036   bind(DONE);
8037   if (UseAVX >= 2 && UseSSE >= 2) {
8038     // clean upper bits of YMM registers
8039     vpxor(vec1, vec1);
8040     vpxor(vec2, vec2);
8041   }
8042 }
8043 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8044 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8045                                    Register limit, Register result, Register chr,
8046                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8047   ShortBranchVerifier sbv(this);
8048   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8049 
8050   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8051   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8052 
8053   if (is_array_equ) {
8054     // Check the input args
8055     cmpoop(ary1, ary2);
8056     jcc(Assembler::equal, TRUE_LABEL);
8057 
8058     // Need additional checks for arrays_equals.
8059     testptr(ary1, ary1);
8060     jcc(Assembler::zero, FALSE_LABEL);
8061     testptr(ary2, ary2);
8062     jcc(Assembler::zero, FALSE_LABEL);
8063 
8064     // Check the lengths
8065     movl(limit, Address(ary1, length_offset));
8066     cmpl(limit, Address(ary2, length_offset));
8067     jcc(Assembler::notEqual, FALSE_LABEL);
8068   }
8069 
8070   // count == 0
8071   testl(limit, limit);
8072   jcc(Assembler::zero, TRUE_LABEL);
8073 
8074   if (is_array_equ) {
8075     // Load array address
8076     lea(ary1, Address(ary1, base_offset));
8077     lea(ary2, Address(ary2, base_offset));
8078   }
8079 
8080   if (is_array_equ && is_char) {
8081     // arrays_equals when used for char[].
8082     shll(limit, 1);      // byte count != 0
8083   }
8084   movl(result, limit); // copy
8085 
8086   if (UseAVX >= 2) {
8087     // With AVX2, use 32-byte vector compare
8088     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8089 
8090     // Compare 32-byte vectors
8091     andl(result, 0x0000001f);  //   tail count (in bytes)
8092     andl(limit, 0xffffffe0);   // vector count (in bytes)
8093     jcc(Assembler::zero, COMPARE_TAIL);
8094 
8095     lea(ary1, Address(ary1, limit, Address::times_1));
8096     lea(ary2, Address(ary2, limit, Address::times_1));
8097     negptr(limit);
8098 
8099     bind(COMPARE_WIDE_VECTORS);
8100 
8101 #ifdef _LP64
8102     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8103       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8104 
8105       cmpl(limit, -64);
8106       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8107 
8108       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8109 
8110       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8111       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8112       kortestql(k7, k7);
8113       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8114       addptr(limit, 64);  // update since we already compared at this addr
8115       cmpl(limit, -64);
8116       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8117 
8118       // At this point we may still need to compare -limit+result bytes.
8119       // We could execute the next two instruction and just continue via non-wide path:
8120       //  cmpl(limit, 0);
8121       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8122       // But since we stopped at the points ary{1,2}+limit which are
8123       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8124       // (|limit| <= 32 and result < 32),
8125       // we may just compare the last 64 bytes.
8126       //
8127       addptr(result, -64);   // it is safe, bc we just came from this area
8128       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8129       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8130       kortestql(k7, k7);
8131       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8132 
8133       jmp(TRUE_LABEL);
8134 
8135       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8136 
8137     }//if (VM_Version::supports_avx512vlbw())
8138 #endif //_LP64
8139 
8140     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8141     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8142     vpxor(vec1, vec2);
8143 
8144     vptest(vec1, vec1);
8145     jcc(Assembler::notZero, FALSE_LABEL);
8146     addptr(limit, 32);
8147     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8148 
8149     testl(result, result);
8150     jcc(Assembler::zero, TRUE_LABEL);
8151 
8152     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8153     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8154     vpxor(vec1, vec2);
8155 
8156     vptest(vec1, vec1);
8157     jccb(Assembler::notZero, FALSE_LABEL);
8158     jmpb(TRUE_LABEL);
8159 
8160     bind(COMPARE_TAIL); // limit is zero
8161     movl(limit, result);
8162     // Fallthru to tail compare
8163   } else if (UseSSE42Intrinsics) {
8164     // With SSE4.2, use double quad vector compare
8165     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8166 
8167     // Compare 16-byte vectors
8168     andl(result, 0x0000000f);  //   tail count (in bytes)
8169     andl(limit, 0xfffffff0);   // vector count (in bytes)
8170     jcc(Assembler::zero, COMPARE_TAIL);
8171 
8172     lea(ary1, Address(ary1, limit, Address::times_1));
8173     lea(ary2, Address(ary2, limit, Address::times_1));
8174     negptr(limit);
8175 
8176     bind(COMPARE_WIDE_VECTORS);
8177     movdqu(vec1, Address(ary1, limit, Address::times_1));
8178     movdqu(vec2, Address(ary2, limit, Address::times_1));
8179     pxor(vec1, vec2);
8180 
8181     ptest(vec1, vec1);
8182     jcc(Assembler::notZero, FALSE_LABEL);
8183     addptr(limit, 16);
8184     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8185 
8186     testl(result, result);
8187     jcc(Assembler::zero, TRUE_LABEL);
8188 
8189     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8190     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8191     pxor(vec1, vec2);
8192 
8193     ptest(vec1, vec1);
8194     jccb(Assembler::notZero, FALSE_LABEL);
8195     jmpb(TRUE_LABEL);
8196 
8197     bind(COMPARE_TAIL); // limit is zero
8198     movl(limit, result);
8199     // Fallthru to tail compare
8200   }
8201 
8202   // Compare 4-byte vectors
8203   andl(limit, 0xfffffffc); // vector count (in bytes)
8204   jccb(Assembler::zero, COMPARE_CHAR);
8205 
8206   lea(ary1, Address(ary1, limit, Address::times_1));
8207   lea(ary2, Address(ary2, limit, Address::times_1));
8208   negptr(limit);
8209 
8210   bind(COMPARE_VECTORS);
8211   movl(chr, Address(ary1, limit, Address::times_1));
8212   cmpl(chr, Address(ary2, limit, Address::times_1));
8213   jccb(Assembler::notEqual, FALSE_LABEL);
8214   addptr(limit, 4);
8215   jcc(Assembler::notZero, COMPARE_VECTORS);
8216 
8217   // Compare trailing char (final 2 bytes), if any
8218   bind(COMPARE_CHAR);
8219   testl(result, 0x2);   // tail  char
8220   jccb(Assembler::zero, COMPARE_BYTE);
8221   load_unsigned_short(chr, Address(ary1, 0));
8222   load_unsigned_short(limit, Address(ary2, 0));
8223   cmpl(chr, limit);
8224   jccb(Assembler::notEqual, FALSE_LABEL);
8225 
8226   if (is_array_equ && is_char) {
8227     bind(COMPARE_BYTE);
8228   } else {
8229     lea(ary1, Address(ary1, 2));
8230     lea(ary2, Address(ary2, 2));
8231 
8232     bind(COMPARE_BYTE);
8233     testl(result, 0x1);   // tail  byte
8234     jccb(Assembler::zero, TRUE_LABEL);
8235     load_unsigned_byte(chr, Address(ary1, 0));
8236     load_unsigned_byte(limit, Address(ary2, 0));
8237     cmpl(chr, limit);
8238     jccb(Assembler::notEqual, FALSE_LABEL);
8239   }
8240   bind(TRUE_LABEL);
8241   movl(result, 1);   // return true
8242   jmpb(DONE);
8243 
8244   bind(FALSE_LABEL);
8245   xorl(result, result); // return false
8246 
8247   // That's it
8248   bind(DONE);
8249   if (UseAVX >= 2) {
8250     // clean upper bits of YMM registers
8251     vpxor(vec1, vec1);
8252     vpxor(vec2, vec2);
8253   }
8254 }
8255 
8256 #endif
8257 
8258 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8259                                    Register to, Register value, Register count,
8260                                    Register rtmp, XMMRegister xtmp) {
8261   ShortBranchVerifier sbv(this);
8262   assert_different_registers(to, value, count, rtmp);
8263   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8264   Label L_fill_2_bytes, L_fill_4_bytes;
8265 
8266   int shift = -1;
8267   switch (t) {
8268     case T_BYTE:
8269       shift = 2;
8270       break;
8271     case T_SHORT:
8272       shift = 1;
8273       break;
8274     case T_INT:
8275       shift = 0;
8276       break;
8277     default: ShouldNotReachHere();
8278   }
8279 
8280   if (t == T_BYTE) {
8281     andl(value, 0xff);
8282     movl(rtmp, value);
8283     shll(rtmp, 8);
8284     orl(value, rtmp);
8285   }
8286   if (t == T_SHORT) {
8287     andl(value, 0xffff);
8288   }
8289   if (t == T_BYTE || t == T_SHORT) {
8290     movl(rtmp, value);
8291     shll(rtmp, 16);
8292     orl(value, rtmp);
8293   }
8294 
8295   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8296   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8297   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8298     // align source address at 4 bytes address boundary
8299     if (t == T_BYTE) {
8300       // One byte misalignment happens only for byte arrays
8301       testptr(to, 1);
8302       jccb(Assembler::zero, L_skip_align1);
8303       movb(Address(to, 0), value);
8304       increment(to);
8305       decrement(count);
8306       BIND(L_skip_align1);
8307     }
8308     // Two bytes misalignment happens only for byte and short (char) arrays
8309     testptr(to, 2);
8310     jccb(Assembler::zero, L_skip_align2);
8311     movw(Address(to, 0), value);
8312     addptr(to, 2);
8313     subl(count, 1<<(shift-1));
8314     BIND(L_skip_align2);
8315   }
8316   if (UseSSE < 2) {
8317     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8318     // Fill 32-byte chunks
8319     subl(count, 8 << shift);
8320     jcc(Assembler::less, L_check_fill_8_bytes);
8321     align(16);
8322 
8323     BIND(L_fill_32_bytes_loop);
8324 
8325     for (int i = 0; i < 32; i += 4) {
8326       movl(Address(to, i), value);
8327     }
8328 
8329     addptr(to, 32);
8330     subl(count, 8 << shift);
8331     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8332     BIND(L_check_fill_8_bytes);
8333     addl(count, 8 << shift);
8334     jccb(Assembler::zero, L_exit);
8335     jmpb(L_fill_8_bytes);
8336 
8337     //
8338     // length is too short, just fill qwords
8339     //
8340     BIND(L_fill_8_bytes_loop);
8341     movl(Address(to, 0), value);
8342     movl(Address(to, 4), value);
8343     addptr(to, 8);
8344     BIND(L_fill_8_bytes);
8345     subl(count, 1 << (shift + 1));
8346     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8347     // fall through to fill 4 bytes
8348   } else {
8349     Label L_fill_32_bytes;
8350     if (!UseUnalignedLoadStores) {
8351       // align to 8 bytes, we know we are 4 byte aligned to start
8352       testptr(to, 4);
8353       jccb(Assembler::zero, L_fill_32_bytes);
8354       movl(Address(to, 0), value);
8355       addptr(to, 4);
8356       subl(count, 1<<shift);
8357     }
8358     BIND(L_fill_32_bytes);
8359     {
8360       assert( UseSSE >= 2, "supported cpu only" );
8361       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8362       if (UseAVX > 2) {
8363         movl(rtmp, 0xffff);
8364         kmovwl(k1, rtmp);
8365       }
8366       movdl(xtmp, value);
8367       if (UseAVX > 2 && UseUnalignedLoadStores) {
8368         // Fill 64-byte chunks
8369         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8370         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8371 
8372         subl(count, 16 << shift);
8373         jcc(Assembler::less, L_check_fill_32_bytes);
8374         align(16);
8375 
8376         BIND(L_fill_64_bytes_loop);
8377         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8378         addptr(to, 64);
8379         subl(count, 16 << shift);
8380         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8381 
8382         BIND(L_check_fill_32_bytes);
8383         addl(count, 8 << shift);
8384         jccb(Assembler::less, L_check_fill_8_bytes);
8385         vmovdqu(Address(to, 0), xtmp);
8386         addptr(to, 32);
8387         subl(count, 8 << shift);
8388 
8389         BIND(L_check_fill_8_bytes);
8390       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8391         // Fill 64-byte chunks
8392         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8393         vpbroadcastd(xtmp, xtmp);
8394 
8395         subl(count, 16 << shift);
8396         jcc(Assembler::less, L_check_fill_32_bytes);
8397         align(16);
8398 
8399         BIND(L_fill_64_bytes_loop);
8400         vmovdqu(Address(to, 0), xtmp);
8401         vmovdqu(Address(to, 32), xtmp);
8402         addptr(to, 64);
8403         subl(count, 16 << shift);
8404         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8405 
8406         BIND(L_check_fill_32_bytes);
8407         addl(count, 8 << shift);
8408         jccb(Assembler::less, L_check_fill_8_bytes);
8409         vmovdqu(Address(to, 0), xtmp);
8410         addptr(to, 32);
8411         subl(count, 8 << shift);
8412 
8413         BIND(L_check_fill_8_bytes);
8414         // clean upper bits of YMM registers
8415         movdl(xtmp, value);
8416         pshufd(xtmp, xtmp, 0);
8417       } else {
8418         // Fill 32-byte chunks
8419         pshufd(xtmp, xtmp, 0);
8420 
8421         subl(count, 8 << shift);
8422         jcc(Assembler::less, L_check_fill_8_bytes);
8423         align(16);
8424 
8425         BIND(L_fill_32_bytes_loop);
8426 
8427         if (UseUnalignedLoadStores) {
8428           movdqu(Address(to, 0), xtmp);
8429           movdqu(Address(to, 16), xtmp);
8430         } else {
8431           movq(Address(to, 0), xtmp);
8432           movq(Address(to, 8), xtmp);
8433           movq(Address(to, 16), xtmp);
8434           movq(Address(to, 24), xtmp);
8435         }
8436 
8437         addptr(to, 32);
8438         subl(count, 8 << shift);
8439         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8440 
8441         BIND(L_check_fill_8_bytes);
8442       }
8443       addl(count, 8 << shift);
8444       jccb(Assembler::zero, L_exit);
8445       jmpb(L_fill_8_bytes);
8446 
8447       //
8448       // length is too short, just fill qwords
8449       //
8450       BIND(L_fill_8_bytes_loop);
8451       movq(Address(to, 0), xtmp);
8452       addptr(to, 8);
8453       BIND(L_fill_8_bytes);
8454       subl(count, 1 << (shift + 1));
8455       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8456     }
8457   }
8458   // fill trailing 4 bytes
8459   BIND(L_fill_4_bytes);
8460   testl(count, 1<<shift);
8461   jccb(Assembler::zero, L_fill_2_bytes);
8462   movl(Address(to, 0), value);
8463   if (t == T_BYTE || t == T_SHORT) {
8464     addptr(to, 4);
8465     BIND(L_fill_2_bytes);
8466     // fill trailing 2 bytes
8467     testl(count, 1<<(shift-1));
8468     jccb(Assembler::zero, L_fill_byte);
8469     movw(Address(to, 0), value);
8470     if (t == T_BYTE) {
8471       addptr(to, 2);
8472       BIND(L_fill_byte);
8473       // fill trailing byte
8474       testl(count, 1);
8475       jccb(Assembler::zero, L_exit);
8476       movb(Address(to, 0), value);
8477     } else {
8478       BIND(L_fill_byte);
8479     }
8480   } else {
8481     BIND(L_fill_2_bytes);
8482   }
8483   BIND(L_exit);
8484 }
8485 
8486 // encode char[] to byte[] in ISO_8859_1
8487    //@HotSpotIntrinsicCandidate
8488    //private static int implEncodeISOArray(byte[] sa, int sp,
8489    //byte[] da, int dp, int len) {
8490    //  int i = 0;
8491    //  for (; i < len; i++) {
8492    //    char c = StringUTF16.getChar(sa, sp++);
8493    //    if (c > '\u00FF')
8494    //      break;
8495    //    da[dp++] = (byte)c;
8496    //  }
8497    //  return i;
8498    //}
8499 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8500   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8501   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8502   Register tmp5, Register result) {
8503 
8504   // rsi: src
8505   // rdi: dst
8506   // rdx: len
8507   // rcx: tmp5
8508   // rax: result
8509   ShortBranchVerifier sbv(this);
8510   assert_different_registers(src, dst, len, tmp5, result);
8511   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8512 
8513   // set result
8514   xorl(result, result);
8515   // check for zero length
8516   testl(len, len);
8517   jcc(Assembler::zero, L_done);
8518 
8519   movl(result, len);
8520 
8521   // Setup pointers
8522   lea(src, Address(src, len, Address::times_2)); // char[]
8523   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8524   negptr(len);
8525 
8526   if (UseSSE42Intrinsics || UseAVX >= 2) {
8527     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8528     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8529 
8530     if (UseAVX >= 2) {
8531       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8532       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8533       movdl(tmp1Reg, tmp5);
8534       vpbroadcastd(tmp1Reg, tmp1Reg);
8535       jmp(L_chars_32_check);
8536 
8537       bind(L_copy_32_chars);
8538       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8539       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8540       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8541       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8542       jccb(Assembler::notZero, L_copy_32_chars_exit);
8543       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8544       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8545       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8546 
8547       bind(L_chars_32_check);
8548       addptr(len, 32);
8549       jcc(Assembler::lessEqual, L_copy_32_chars);
8550 
8551       bind(L_copy_32_chars_exit);
8552       subptr(len, 16);
8553       jccb(Assembler::greater, L_copy_16_chars_exit);
8554 
8555     } else if (UseSSE42Intrinsics) {
8556       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8557       movdl(tmp1Reg, tmp5);
8558       pshufd(tmp1Reg, tmp1Reg, 0);
8559       jmpb(L_chars_16_check);
8560     }
8561 
8562     bind(L_copy_16_chars);
8563     if (UseAVX >= 2) {
8564       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8565       vptest(tmp2Reg, tmp1Reg);
8566       jcc(Assembler::notZero, L_copy_16_chars_exit);
8567       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8568       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8569     } else {
8570       if (UseAVX > 0) {
8571         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8572         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8573         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8574       } else {
8575         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8576         por(tmp2Reg, tmp3Reg);
8577         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8578         por(tmp2Reg, tmp4Reg);
8579       }
8580       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8581       jccb(Assembler::notZero, L_copy_16_chars_exit);
8582       packuswb(tmp3Reg, tmp4Reg);
8583     }
8584     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8585 
8586     bind(L_chars_16_check);
8587     addptr(len, 16);
8588     jcc(Assembler::lessEqual, L_copy_16_chars);
8589 
8590     bind(L_copy_16_chars_exit);
8591     if (UseAVX >= 2) {
8592       // clean upper bits of YMM registers
8593       vpxor(tmp2Reg, tmp2Reg);
8594       vpxor(tmp3Reg, tmp3Reg);
8595       vpxor(tmp4Reg, tmp4Reg);
8596       movdl(tmp1Reg, tmp5);
8597       pshufd(tmp1Reg, tmp1Reg, 0);
8598     }
8599     subptr(len, 8);
8600     jccb(Assembler::greater, L_copy_8_chars_exit);
8601 
8602     bind(L_copy_8_chars);
8603     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8604     ptest(tmp3Reg, tmp1Reg);
8605     jccb(Assembler::notZero, L_copy_8_chars_exit);
8606     packuswb(tmp3Reg, tmp1Reg);
8607     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8608     addptr(len, 8);
8609     jccb(Assembler::lessEqual, L_copy_8_chars);
8610 
8611     bind(L_copy_8_chars_exit);
8612     subptr(len, 8);
8613     jccb(Assembler::zero, L_done);
8614   }
8615 
8616   bind(L_copy_1_char);
8617   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8618   testl(tmp5, 0xff00);      // check if Unicode char
8619   jccb(Assembler::notZero, L_copy_1_char_exit);
8620   movb(Address(dst, len, Address::times_1, 0), tmp5);
8621   addptr(len, 1);
8622   jccb(Assembler::less, L_copy_1_char);
8623 
8624   bind(L_copy_1_char_exit);
8625   addptr(result, len); // len is negative count of not processed elements
8626 
8627   bind(L_done);
8628 }
8629 
8630 #ifdef _LP64
8631 /**
8632  * Helper for multiply_to_len().
8633  */
8634 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8635   addq(dest_lo, src1);
8636   adcq(dest_hi, 0);
8637   addq(dest_lo, src2);
8638   adcq(dest_hi, 0);
8639 }
8640 
8641 /**
8642  * Multiply 64 bit by 64 bit first loop.
8643  */
8644 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8645                                            Register y, Register y_idx, Register z,
8646                                            Register carry, Register product,
8647                                            Register idx, Register kdx) {
8648   //
8649   //  jlong carry, x[], y[], z[];
8650   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8651   //    huge_128 product = y[idx] * x[xstart] + carry;
8652   //    z[kdx] = (jlong)product;
8653   //    carry  = (jlong)(product >>> 64);
8654   //  }
8655   //  z[xstart] = carry;
8656   //
8657 
8658   Label L_first_loop, L_first_loop_exit;
8659   Label L_one_x, L_one_y, L_multiply;
8660 
8661   decrementl(xstart);
8662   jcc(Assembler::negative, L_one_x);
8663 
8664   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8665   rorq(x_xstart, 32); // convert big-endian to little-endian
8666 
8667   bind(L_first_loop);
8668   decrementl(idx);
8669   jcc(Assembler::negative, L_first_loop_exit);
8670   decrementl(idx);
8671   jcc(Assembler::negative, L_one_y);
8672   movq(y_idx, Address(y, idx, Address::times_4,  0));
8673   rorq(y_idx, 32); // convert big-endian to little-endian
8674   bind(L_multiply);
8675   movq(product, x_xstart);
8676   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8677   addq(product, carry);
8678   adcq(rdx, 0);
8679   subl(kdx, 2);
8680   movl(Address(z, kdx, Address::times_4,  4), product);
8681   shrq(product, 32);
8682   movl(Address(z, kdx, Address::times_4,  0), product);
8683   movq(carry, rdx);
8684   jmp(L_first_loop);
8685 
8686   bind(L_one_y);
8687   movl(y_idx, Address(y,  0));
8688   jmp(L_multiply);
8689 
8690   bind(L_one_x);
8691   movl(x_xstart, Address(x,  0));
8692   jmp(L_first_loop);
8693 
8694   bind(L_first_loop_exit);
8695 }
8696 
8697 /**
8698  * Multiply 64 bit by 64 bit and add 128 bit.
8699  */
8700 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8701                                             Register yz_idx, Register idx,
8702                                             Register carry, Register product, int offset) {
8703   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8704   //     z[kdx] = (jlong)product;
8705 
8706   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8707   rorq(yz_idx, 32); // convert big-endian to little-endian
8708   movq(product, x_xstart);
8709   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8710   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8711   rorq(yz_idx, 32); // convert big-endian to little-endian
8712 
8713   add2_with_carry(rdx, product, carry, yz_idx);
8714 
8715   movl(Address(z, idx, Address::times_4,  offset+4), product);
8716   shrq(product, 32);
8717   movl(Address(z, idx, Address::times_4,  offset), product);
8718 
8719 }
8720 
8721 /**
8722  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8723  */
8724 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8725                                              Register yz_idx, Register idx, Register jdx,
8726                                              Register carry, Register product,
8727                                              Register carry2) {
8728   //   jlong carry, x[], y[], z[];
8729   //   int kdx = ystart+1;
8730   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8731   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8732   //     z[kdx+idx+1] = (jlong)product;
8733   //     jlong carry2  = (jlong)(product >>> 64);
8734   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8735   //     z[kdx+idx] = (jlong)product;
8736   //     carry  = (jlong)(product >>> 64);
8737   //   }
8738   //   idx += 2;
8739   //   if (idx > 0) {
8740   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8741   //     z[kdx+idx] = (jlong)product;
8742   //     carry  = (jlong)(product >>> 64);
8743   //   }
8744   //
8745 
8746   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8747 
8748   movl(jdx, idx);
8749   andl(jdx, 0xFFFFFFFC);
8750   shrl(jdx, 2);
8751 
8752   bind(L_third_loop);
8753   subl(jdx, 1);
8754   jcc(Assembler::negative, L_third_loop_exit);
8755   subl(idx, 4);
8756 
8757   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8758   movq(carry2, rdx);
8759 
8760   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8761   movq(carry, rdx);
8762   jmp(L_third_loop);
8763 
8764   bind (L_third_loop_exit);
8765 
8766   andl (idx, 0x3);
8767   jcc(Assembler::zero, L_post_third_loop_done);
8768 
8769   Label L_check_1;
8770   subl(idx, 2);
8771   jcc(Assembler::negative, L_check_1);
8772 
8773   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8774   movq(carry, rdx);
8775 
8776   bind (L_check_1);
8777   addl (idx, 0x2);
8778   andl (idx, 0x1);
8779   subl(idx, 1);
8780   jcc(Assembler::negative, L_post_third_loop_done);
8781 
8782   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8783   movq(product, x_xstart);
8784   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8785   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8786 
8787   add2_with_carry(rdx, product, yz_idx, carry);
8788 
8789   movl(Address(z, idx, Address::times_4,  0), product);
8790   shrq(product, 32);
8791 
8792   shlq(rdx, 32);
8793   orq(product, rdx);
8794   movq(carry, product);
8795 
8796   bind(L_post_third_loop_done);
8797 }
8798 
8799 /**
8800  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8801  *
8802  */
8803 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8804                                                   Register carry, Register carry2,
8805                                                   Register idx, Register jdx,
8806                                                   Register yz_idx1, Register yz_idx2,
8807                                                   Register tmp, Register tmp3, Register tmp4) {
8808   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8809 
8810   //   jlong carry, x[], y[], z[];
8811   //   int kdx = ystart+1;
8812   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8813   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8814   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8815   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8816   //     carry  = (jlong)(tmp4 >>> 64);
8817   //     z[kdx+idx+1] = (jlong)tmp3;
8818   //     z[kdx+idx] = (jlong)tmp4;
8819   //   }
8820   //   idx += 2;
8821   //   if (idx > 0) {
8822   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8823   //     z[kdx+idx] = (jlong)yz_idx1;
8824   //     carry  = (jlong)(yz_idx1 >>> 64);
8825   //   }
8826   //
8827 
8828   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8829 
8830   movl(jdx, idx);
8831   andl(jdx, 0xFFFFFFFC);
8832   shrl(jdx, 2);
8833 
8834   bind(L_third_loop);
8835   subl(jdx, 1);
8836   jcc(Assembler::negative, L_third_loop_exit);
8837   subl(idx, 4);
8838 
8839   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8840   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8841   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8842   rorxq(yz_idx2, yz_idx2, 32);
8843 
8844   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8845   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8846 
8847   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8848   rorxq(yz_idx1, yz_idx1, 32);
8849   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8850   rorxq(yz_idx2, yz_idx2, 32);
8851 
8852   if (VM_Version::supports_adx()) {
8853     adcxq(tmp3, carry);
8854     adoxq(tmp3, yz_idx1);
8855 
8856     adcxq(tmp4, tmp);
8857     adoxq(tmp4, yz_idx2);
8858 
8859     movl(carry, 0); // does not affect flags
8860     adcxq(carry2, carry);
8861     adoxq(carry2, carry);
8862   } else {
8863     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8864     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8865   }
8866   movq(carry, carry2);
8867 
8868   movl(Address(z, idx, Address::times_4, 12), tmp3);
8869   shrq(tmp3, 32);
8870   movl(Address(z, idx, Address::times_4,  8), tmp3);
8871 
8872   movl(Address(z, idx, Address::times_4,  4), tmp4);
8873   shrq(tmp4, 32);
8874   movl(Address(z, idx, Address::times_4,  0), tmp4);
8875 
8876   jmp(L_third_loop);
8877 
8878   bind (L_third_loop_exit);
8879 
8880   andl (idx, 0x3);
8881   jcc(Assembler::zero, L_post_third_loop_done);
8882 
8883   Label L_check_1;
8884   subl(idx, 2);
8885   jcc(Assembler::negative, L_check_1);
8886 
8887   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8888   rorxq(yz_idx1, yz_idx1, 32);
8889   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8890   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8891   rorxq(yz_idx2, yz_idx2, 32);
8892 
8893   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8894 
8895   movl(Address(z, idx, Address::times_4,  4), tmp3);
8896   shrq(tmp3, 32);
8897   movl(Address(z, idx, Address::times_4,  0), tmp3);
8898   movq(carry, tmp4);
8899 
8900   bind (L_check_1);
8901   addl (idx, 0x2);
8902   andl (idx, 0x1);
8903   subl(idx, 1);
8904   jcc(Assembler::negative, L_post_third_loop_done);
8905   movl(tmp4, Address(y, idx, Address::times_4,  0));
8906   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8907   movl(tmp4, Address(z, idx, Address::times_4,  0));
8908 
8909   add2_with_carry(carry2, tmp3, tmp4, carry);
8910 
8911   movl(Address(z, idx, Address::times_4,  0), tmp3);
8912   shrq(tmp3, 32);
8913 
8914   shlq(carry2, 32);
8915   orq(tmp3, carry2);
8916   movq(carry, tmp3);
8917 
8918   bind(L_post_third_loop_done);
8919 }
8920 
8921 /**
8922  * Code for BigInteger::multiplyToLen() instrinsic.
8923  *
8924  * rdi: x
8925  * rax: xlen
8926  * rsi: y
8927  * rcx: ylen
8928  * r8:  z
8929  * r11: zlen
8930  * r12: tmp1
8931  * r13: tmp2
8932  * r14: tmp3
8933  * r15: tmp4
8934  * rbx: tmp5
8935  *
8936  */
8937 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8938                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8939   ShortBranchVerifier sbv(this);
8940   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8941 
8942   push(tmp1);
8943   push(tmp2);
8944   push(tmp3);
8945   push(tmp4);
8946   push(tmp5);
8947 
8948   push(xlen);
8949   push(zlen);
8950 
8951   const Register idx = tmp1;
8952   const Register kdx = tmp2;
8953   const Register xstart = tmp3;
8954 
8955   const Register y_idx = tmp4;
8956   const Register carry = tmp5;
8957   const Register product  = xlen;
8958   const Register x_xstart = zlen;  // reuse register
8959 
8960   // First Loop.
8961   //
8962   //  final static long LONG_MASK = 0xffffffffL;
8963   //  int xstart = xlen - 1;
8964   //  int ystart = ylen - 1;
8965   //  long carry = 0;
8966   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8967   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8968   //    z[kdx] = (int)product;
8969   //    carry = product >>> 32;
8970   //  }
8971   //  z[xstart] = (int)carry;
8972   //
8973 
8974   movl(idx, ylen);      // idx = ylen;
8975   movl(kdx, zlen);      // kdx = xlen+ylen;
8976   xorq(carry, carry);   // carry = 0;
8977 
8978   Label L_done;
8979 
8980   movl(xstart, xlen);
8981   decrementl(xstart);
8982   jcc(Assembler::negative, L_done);
8983 
8984   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8985 
8986   Label L_second_loop;
8987   testl(kdx, kdx);
8988   jcc(Assembler::zero, L_second_loop);
8989 
8990   Label L_carry;
8991   subl(kdx, 1);
8992   jcc(Assembler::zero, L_carry);
8993 
8994   movl(Address(z, kdx, Address::times_4,  0), carry);
8995   shrq(carry, 32);
8996   subl(kdx, 1);
8997 
8998   bind(L_carry);
8999   movl(Address(z, kdx, Address::times_4,  0), carry);
9000 
9001   // Second and third (nested) loops.
9002   //
9003   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9004   //   carry = 0;
9005   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9006   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9007   //                    (z[k] & LONG_MASK) + carry;
9008   //     z[k] = (int)product;
9009   //     carry = product >>> 32;
9010   //   }
9011   //   z[i] = (int)carry;
9012   // }
9013   //
9014   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9015 
9016   const Register jdx = tmp1;
9017 
9018   bind(L_second_loop);
9019   xorl(carry, carry);    // carry = 0;
9020   movl(jdx, ylen);       // j = ystart+1
9021 
9022   subl(xstart, 1);       // i = xstart-1;
9023   jcc(Assembler::negative, L_done);
9024 
9025   push (z);
9026 
9027   Label L_last_x;
9028   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9029   subl(xstart, 1);       // i = xstart-1;
9030   jcc(Assembler::negative, L_last_x);
9031 
9032   if (UseBMI2Instructions) {
9033     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9034     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9035   } else {
9036     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9037     rorq(x_xstart, 32);  // convert big-endian to little-endian
9038   }
9039 
9040   Label L_third_loop_prologue;
9041   bind(L_third_loop_prologue);
9042 
9043   push (x);
9044   push (xstart);
9045   push (ylen);
9046 
9047 
9048   if (UseBMI2Instructions) {
9049     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9050   } else { // !UseBMI2Instructions
9051     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9052   }
9053 
9054   pop(ylen);
9055   pop(xlen);
9056   pop(x);
9057   pop(z);
9058 
9059   movl(tmp3, xlen);
9060   addl(tmp3, 1);
9061   movl(Address(z, tmp3, Address::times_4,  0), carry);
9062   subl(tmp3, 1);
9063   jccb(Assembler::negative, L_done);
9064 
9065   shrq(carry, 32);
9066   movl(Address(z, tmp3, Address::times_4,  0), carry);
9067   jmp(L_second_loop);
9068 
9069   // Next infrequent code is moved outside loops.
9070   bind(L_last_x);
9071   if (UseBMI2Instructions) {
9072     movl(rdx, Address(x,  0));
9073   } else {
9074     movl(x_xstart, Address(x,  0));
9075   }
9076   jmp(L_third_loop_prologue);
9077 
9078   bind(L_done);
9079 
9080   pop(zlen);
9081   pop(xlen);
9082 
9083   pop(tmp5);
9084   pop(tmp4);
9085   pop(tmp3);
9086   pop(tmp2);
9087   pop(tmp1);
9088 }
9089 
9090 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9091   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9092   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9093   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9094   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9095   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9096   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9097   Label SAME_TILL_END, DONE;
9098   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9099 
9100   //scale is in rcx in both Win64 and Unix
9101   ShortBranchVerifier sbv(this);
9102 
9103   shlq(length);
9104   xorq(result, result);
9105 
9106   if ((UseAVX > 2) &&
9107       VM_Version::supports_avx512vlbw()) {
9108     set_vector_masking();  // opening of the stub context for programming mask registers
9109     cmpq(length, 64);
9110     jcc(Assembler::less, VECTOR32_TAIL);
9111     movq(tmp1, length);
9112     andq(tmp1, 0x3F);      // tail count
9113     andq(length, ~(0x3F)); //vector count
9114 
9115     bind(VECTOR64_LOOP);
9116     // AVX512 code to compare 64 byte vectors.
9117     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9118     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9119     kortestql(k7, k7);
9120     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9121     addq(result, 64);
9122     subq(length, 64);
9123     jccb(Assembler::notZero, VECTOR64_LOOP);
9124 
9125     //bind(VECTOR64_TAIL);
9126     testq(tmp1, tmp1);
9127     jcc(Assembler::zero, SAME_TILL_END);
9128 
9129     bind(VECTOR64_TAIL);
9130     // AVX512 code to compare upto 63 byte vectors.
9131     // Save k1
9132     kmovql(k3, k1);
9133     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9134     shlxq(tmp2, tmp2, tmp1);
9135     notq(tmp2);
9136     kmovql(k1, tmp2);
9137 
9138     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9139     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9140 
9141     ktestql(k7, k1);
9142     // Restore k1
9143     kmovql(k1, k3);
9144     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9145 
9146     bind(VECTOR64_NOT_EQUAL);
9147     kmovql(tmp1, k7);
9148     notq(tmp1);
9149     tzcntq(tmp1, tmp1);
9150     addq(result, tmp1);
9151     shrq(result);
9152     jmp(DONE);
9153     bind(VECTOR32_TAIL);
9154     clear_vector_masking();   // closing of the stub context for programming mask registers
9155   }
9156 
9157   cmpq(length, 8);
9158   jcc(Assembler::equal, VECTOR8_LOOP);
9159   jcc(Assembler::less, VECTOR4_TAIL);
9160 
9161   if (UseAVX >= 2) {
9162 
9163     cmpq(length, 16);
9164     jcc(Assembler::equal, VECTOR16_LOOP);
9165     jcc(Assembler::less, VECTOR8_LOOP);
9166 
9167     cmpq(length, 32);
9168     jccb(Assembler::less, VECTOR16_TAIL);
9169 
9170     subq(length, 32);
9171     bind(VECTOR32_LOOP);
9172     vmovdqu(rymm0, Address(obja, result));
9173     vmovdqu(rymm1, Address(objb, result));
9174     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9175     vptest(rymm2, rymm2);
9176     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9177     addq(result, 32);
9178     subq(length, 32);
9179     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9180     addq(length, 32);
9181     jcc(Assembler::equal, SAME_TILL_END);
9182     //falling through if less than 32 bytes left //close the branch here.
9183 
9184     bind(VECTOR16_TAIL);
9185     cmpq(length, 16);
9186     jccb(Assembler::less, VECTOR8_TAIL);
9187     bind(VECTOR16_LOOP);
9188     movdqu(rymm0, Address(obja, result));
9189     movdqu(rymm1, Address(objb, result));
9190     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9191     ptest(rymm2, rymm2);
9192     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9193     addq(result, 16);
9194     subq(length, 16);
9195     jcc(Assembler::equal, SAME_TILL_END);
9196     //falling through if less than 16 bytes left
9197   } else {//regular intrinsics
9198 
9199     cmpq(length, 16);
9200     jccb(Assembler::less, VECTOR8_TAIL);
9201 
9202     subq(length, 16);
9203     bind(VECTOR16_LOOP);
9204     movdqu(rymm0, Address(obja, result));
9205     movdqu(rymm1, Address(objb, result));
9206     pxor(rymm0, rymm1);
9207     ptest(rymm0, rymm0);
9208     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9209     addq(result, 16);
9210     subq(length, 16);
9211     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9212     addq(length, 16);
9213     jcc(Assembler::equal, SAME_TILL_END);
9214     //falling through if less than 16 bytes left
9215   }
9216 
9217   bind(VECTOR8_TAIL);
9218   cmpq(length, 8);
9219   jccb(Assembler::less, VECTOR4_TAIL);
9220   bind(VECTOR8_LOOP);
9221   movq(tmp1, Address(obja, result));
9222   movq(tmp2, Address(objb, result));
9223   xorq(tmp1, tmp2);
9224   testq(tmp1, tmp1);
9225   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9226   addq(result, 8);
9227   subq(length, 8);
9228   jcc(Assembler::equal, SAME_TILL_END);
9229   //falling through if less than 8 bytes left
9230 
9231   bind(VECTOR4_TAIL);
9232   cmpq(length, 4);
9233   jccb(Assembler::less, BYTES_TAIL);
9234   bind(VECTOR4_LOOP);
9235   movl(tmp1, Address(obja, result));
9236   xorl(tmp1, Address(objb, result));
9237   testl(tmp1, tmp1);
9238   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9239   addq(result, 4);
9240   subq(length, 4);
9241   jcc(Assembler::equal, SAME_TILL_END);
9242   //falling through if less than 4 bytes left
9243 
9244   bind(BYTES_TAIL);
9245   bind(BYTES_LOOP);
9246   load_unsigned_byte(tmp1, Address(obja, result));
9247   load_unsigned_byte(tmp2, Address(objb, result));
9248   xorl(tmp1, tmp2);
9249   testl(tmp1, tmp1);
9250   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9251   decq(length);
9252   jccb(Assembler::zero, SAME_TILL_END);
9253   incq(result);
9254   load_unsigned_byte(tmp1, Address(obja, result));
9255   load_unsigned_byte(tmp2, Address(objb, result));
9256   xorl(tmp1, tmp2);
9257   testl(tmp1, tmp1);
9258   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9259   decq(length);
9260   jccb(Assembler::zero, SAME_TILL_END);
9261   incq(result);
9262   load_unsigned_byte(tmp1, Address(obja, result));
9263   load_unsigned_byte(tmp2, Address(objb, result));
9264   xorl(tmp1, tmp2);
9265   testl(tmp1, tmp1);
9266   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9267   jmpb(SAME_TILL_END);
9268 
9269   if (UseAVX >= 2) {
9270     bind(VECTOR32_NOT_EQUAL);
9271     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9272     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9273     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9274     vpmovmskb(tmp1, rymm0);
9275     bsfq(tmp1, tmp1);
9276     addq(result, tmp1);
9277     shrq(result);
9278     jmpb(DONE);
9279   }
9280 
9281   bind(VECTOR16_NOT_EQUAL);
9282   if (UseAVX >= 2) {
9283     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9284     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9285     pxor(rymm0, rymm2);
9286   } else {
9287     pcmpeqb(rymm2, rymm2);
9288     pxor(rymm0, rymm1);
9289     pcmpeqb(rymm0, rymm1);
9290     pxor(rymm0, rymm2);
9291   }
9292   pmovmskb(tmp1, rymm0);
9293   bsfq(tmp1, tmp1);
9294   addq(result, tmp1);
9295   shrq(result);
9296   jmpb(DONE);
9297 
9298   bind(VECTOR8_NOT_EQUAL);
9299   bind(VECTOR4_NOT_EQUAL);
9300   bsfq(tmp1, tmp1);
9301   shrq(tmp1, 3);
9302   addq(result, tmp1);
9303   bind(BYTES_NOT_EQUAL);
9304   shrq(result);
9305   jmpb(DONE);
9306 
9307   bind(SAME_TILL_END);
9308   mov64(result, -1);
9309 
9310   bind(DONE);
9311 }
9312 
9313 //Helper functions for square_to_len()
9314 
9315 /**
9316  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9317  * Preserves x and z and modifies rest of the registers.
9318  */
9319 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9320   // Perform square and right shift by 1
9321   // Handle odd xlen case first, then for even xlen do the following
9322   // jlong carry = 0;
9323   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9324   //     huge_128 product = x[j:j+1] * x[j:j+1];
9325   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9326   //     z[i+2:i+3] = (jlong)(product >>> 1);
9327   //     carry = (jlong)product;
9328   // }
9329 
9330   xorq(tmp5, tmp5);     // carry
9331   xorq(rdxReg, rdxReg);
9332   xorl(tmp1, tmp1);     // index for x
9333   xorl(tmp4, tmp4);     // index for z
9334 
9335   Label L_first_loop, L_first_loop_exit;
9336 
9337   testl(xlen, 1);
9338   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9339 
9340   // Square and right shift by 1 the odd element using 32 bit multiply
9341   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9342   imulq(raxReg, raxReg);
9343   shrq(raxReg, 1);
9344   adcq(tmp5, 0);
9345   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9346   incrementl(tmp1);
9347   addl(tmp4, 2);
9348 
9349   // Square and  right shift by 1 the rest using 64 bit multiply
9350   bind(L_first_loop);
9351   cmpptr(tmp1, xlen);
9352   jccb(Assembler::equal, L_first_loop_exit);
9353 
9354   // Square
9355   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9356   rorq(raxReg, 32);    // convert big-endian to little-endian
9357   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9358 
9359   // Right shift by 1 and save carry
9360   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9361   rcrq(rdxReg, 1);
9362   rcrq(raxReg, 1);
9363   adcq(tmp5, 0);
9364 
9365   // Store result in z
9366   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9367   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9368 
9369   // Update indices for x and z
9370   addl(tmp1, 2);
9371   addl(tmp4, 4);
9372   jmp(L_first_loop);
9373 
9374   bind(L_first_loop_exit);
9375 }
9376 
9377 
9378 /**
9379  * Perform the following multiply add operation using BMI2 instructions
9380  * carry:sum = sum + op1*op2 + carry
9381  * op2 should be in rdx
9382  * op2 is preserved, all other registers are modified
9383  */
9384 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9385   // assert op2 is rdx
9386   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9387   addq(sum, carry);
9388   adcq(tmp2, 0);
9389   addq(sum, op1);
9390   adcq(tmp2, 0);
9391   movq(carry, tmp2);
9392 }
9393 
9394 /**
9395  * Perform the following multiply add operation:
9396  * carry:sum = sum + op1*op2 + carry
9397  * Preserves op1, op2 and modifies rest of registers
9398  */
9399 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9400   // rdx:rax = op1 * op2
9401   movq(raxReg, op2);
9402   mulq(op1);
9403 
9404   //  rdx:rax = sum + carry + rdx:rax
9405   addq(sum, carry);
9406   adcq(rdxReg, 0);
9407   addq(sum, raxReg);
9408   adcq(rdxReg, 0);
9409 
9410   // carry:sum = rdx:sum
9411   movq(carry, rdxReg);
9412 }
9413 
9414 /**
9415  * Add 64 bit long carry into z[] with carry propogation.
9416  * Preserves z and carry register values and modifies rest of registers.
9417  *
9418  */
9419 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9420   Label L_fourth_loop, L_fourth_loop_exit;
9421 
9422   movl(tmp1, 1);
9423   subl(zlen, 2);
9424   addq(Address(z, zlen, Address::times_4, 0), carry);
9425 
9426   bind(L_fourth_loop);
9427   jccb(Assembler::carryClear, L_fourth_loop_exit);
9428   subl(zlen, 2);
9429   jccb(Assembler::negative, L_fourth_loop_exit);
9430   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9431   jmp(L_fourth_loop);
9432   bind(L_fourth_loop_exit);
9433 }
9434 
9435 /**
9436  * Shift z[] left by 1 bit.
9437  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9438  *
9439  */
9440 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9441 
9442   Label L_fifth_loop, L_fifth_loop_exit;
9443 
9444   // Fifth loop
9445   // Perform primitiveLeftShift(z, zlen, 1)
9446 
9447   const Register prev_carry = tmp1;
9448   const Register new_carry = tmp4;
9449   const Register value = tmp2;
9450   const Register zidx = tmp3;
9451 
9452   // int zidx, carry;
9453   // long value;
9454   // carry = 0;
9455   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9456   //    (carry:value)  = (z[i] << 1) | carry ;
9457   //    z[i] = value;
9458   // }
9459 
9460   movl(zidx, zlen);
9461   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9462 
9463   bind(L_fifth_loop);
9464   decl(zidx);  // Use decl to preserve carry flag
9465   decl(zidx);
9466   jccb(Assembler::negative, L_fifth_loop_exit);
9467 
9468   if (UseBMI2Instructions) {
9469      movq(value, Address(z, zidx, Address::times_4, 0));
9470      rclq(value, 1);
9471      rorxq(value, value, 32);
9472      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9473   }
9474   else {
9475     // clear new_carry
9476     xorl(new_carry, new_carry);
9477 
9478     // Shift z[i] by 1, or in previous carry and save new carry
9479     movq(value, Address(z, zidx, Address::times_4, 0));
9480     shlq(value, 1);
9481     adcl(new_carry, 0);
9482 
9483     orq(value, prev_carry);
9484     rorq(value, 0x20);
9485     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9486 
9487     // Set previous carry = new carry
9488     movl(prev_carry, new_carry);
9489   }
9490   jmp(L_fifth_loop);
9491 
9492   bind(L_fifth_loop_exit);
9493 }
9494 
9495 
9496 /**
9497  * Code for BigInteger::squareToLen() intrinsic
9498  *
9499  * rdi: x
9500  * rsi: len
9501  * r8:  z
9502  * rcx: zlen
9503  * r12: tmp1
9504  * r13: tmp2
9505  * r14: tmp3
9506  * r15: tmp4
9507  * rbx: tmp5
9508  *
9509  */
9510 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) {
9511 
9512   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;
9513   push(tmp1);
9514   push(tmp2);
9515   push(tmp3);
9516   push(tmp4);
9517   push(tmp5);
9518 
9519   // First loop
9520   // Store the squares, right shifted one bit (i.e., divided by 2).
9521   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9522 
9523   // Add in off-diagonal sums.
9524   //
9525   // Second, third (nested) and fourth loops.
9526   // zlen +=2;
9527   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9528   //    carry = 0;
9529   //    long op2 = x[xidx:xidx+1];
9530   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9531   //       k -= 2;
9532   //       long op1 = x[j:j+1];
9533   //       long sum = z[k:k+1];
9534   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9535   //       z[k:k+1] = sum;
9536   //    }
9537   //    add_one_64(z, k, carry, tmp_regs);
9538   // }
9539 
9540   const Register carry = tmp5;
9541   const Register sum = tmp3;
9542   const Register op1 = tmp4;
9543   Register op2 = tmp2;
9544 
9545   push(zlen);
9546   push(len);
9547   addl(zlen,2);
9548   bind(L_second_loop);
9549   xorq(carry, carry);
9550   subl(zlen, 4);
9551   subl(len, 2);
9552   push(zlen);
9553   push(len);
9554   cmpl(len, 0);
9555   jccb(Assembler::lessEqual, L_second_loop_exit);
9556 
9557   // Multiply an array by one 64 bit long.
9558   if (UseBMI2Instructions) {
9559     op2 = rdxReg;
9560     movq(op2, Address(x, len, Address::times_4,  0));
9561     rorxq(op2, op2, 32);
9562   }
9563   else {
9564     movq(op2, Address(x, len, Address::times_4,  0));
9565     rorq(op2, 32);
9566   }
9567 
9568   bind(L_third_loop);
9569   decrementl(len);
9570   jccb(Assembler::negative, L_third_loop_exit);
9571   decrementl(len);
9572   jccb(Assembler::negative, L_last_x);
9573 
9574   movq(op1, Address(x, len, Address::times_4,  0));
9575   rorq(op1, 32);
9576 
9577   bind(L_multiply);
9578   subl(zlen, 2);
9579   movq(sum, Address(z, zlen, Address::times_4,  0));
9580 
9581   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9582   if (UseBMI2Instructions) {
9583     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9584   }
9585   else {
9586     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9587   }
9588 
9589   movq(Address(z, zlen, Address::times_4, 0), sum);
9590 
9591   jmp(L_third_loop);
9592   bind(L_third_loop_exit);
9593 
9594   // Fourth loop
9595   // Add 64 bit long carry into z with carry propogation.
9596   // Uses offsetted zlen.
9597   add_one_64(z, zlen, carry, tmp1);
9598 
9599   pop(len);
9600   pop(zlen);
9601   jmp(L_second_loop);
9602 
9603   // Next infrequent code is moved outside loops.
9604   bind(L_last_x);
9605   movl(op1, Address(x, 0));
9606   jmp(L_multiply);
9607 
9608   bind(L_second_loop_exit);
9609   pop(len);
9610   pop(zlen);
9611   pop(len);
9612   pop(zlen);
9613 
9614   // Fifth loop
9615   // Shift z left 1 bit.
9616   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9617 
9618   // z[zlen-1] |= x[len-1] & 1;
9619   movl(tmp3, Address(x, len, Address::times_4, -4));
9620   andl(tmp3, 1);
9621   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9622 
9623   pop(tmp5);
9624   pop(tmp4);
9625   pop(tmp3);
9626   pop(tmp2);
9627   pop(tmp1);
9628 }
9629 
9630 /**
9631  * Helper function for mul_add()
9632  * Multiply the in[] by int k and add to out[] starting at offset offs using
9633  * 128 bit by 32 bit multiply and return the carry in tmp5.
9634  * Only quad int aligned length of in[] is operated on in this function.
9635  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9636  * This function preserves out, in and k registers.
9637  * len and offset point to the appropriate index in "in" & "out" correspondingly
9638  * tmp5 has the carry.
9639  * other registers are temporary and are modified.
9640  *
9641  */
9642 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9643   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9644   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9645 
9646   Label L_first_loop, L_first_loop_exit;
9647 
9648   movl(tmp1, len);
9649   shrl(tmp1, 2);
9650 
9651   bind(L_first_loop);
9652   subl(tmp1, 1);
9653   jccb(Assembler::negative, L_first_loop_exit);
9654 
9655   subl(len, 4);
9656   subl(offset, 4);
9657 
9658   Register op2 = tmp2;
9659   const Register sum = tmp3;
9660   const Register op1 = tmp4;
9661   const Register carry = tmp5;
9662 
9663   if (UseBMI2Instructions) {
9664     op2 = rdxReg;
9665   }
9666 
9667   movq(op1, Address(in, len, Address::times_4,  8));
9668   rorq(op1, 32);
9669   movq(sum, Address(out, offset, Address::times_4,  8));
9670   rorq(sum, 32);
9671   if (UseBMI2Instructions) {
9672     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9673   }
9674   else {
9675     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9676   }
9677   // Store back in big endian from little endian
9678   rorq(sum, 0x20);
9679   movq(Address(out, offset, Address::times_4,  8), sum);
9680 
9681   movq(op1, Address(in, len, Address::times_4,  0));
9682   rorq(op1, 32);
9683   movq(sum, Address(out, offset, Address::times_4,  0));
9684   rorq(sum, 32);
9685   if (UseBMI2Instructions) {
9686     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9687   }
9688   else {
9689     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9690   }
9691   // Store back in big endian from little endian
9692   rorq(sum, 0x20);
9693   movq(Address(out, offset, Address::times_4,  0), sum);
9694 
9695   jmp(L_first_loop);
9696   bind(L_first_loop_exit);
9697 }
9698 
9699 /**
9700  * Code for BigInteger::mulAdd() intrinsic
9701  *
9702  * rdi: out
9703  * rsi: in
9704  * r11: offs (out.length - offset)
9705  * rcx: len
9706  * r8:  k
9707  * r12: tmp1
9708  * r13: tmp2
9709  * r14: tmp3
9710  * r15: tmp4
9711  * rbx: tmp5
9712  * Multiply the in[] by word k and add to out[], return the carry in rax
9713  */
9714 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9715    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9716    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9717 
9718   Label L_carry, L_last_in, L_done;
9719 
9720 // carry = 0;
9721 // for (int j=len-1; j >= 0; j--) {
9722 //    long product = (in[j] & LONG_MASK) * kLong +
9723 //                   (out[offs] & LONG_MASK) + carry;
9724 //    out[offs--] = (int)product;
9725 //    carry = product >>> 32;
9726 // }
9727 //
9728   push(tmp1);
9729   push(tmp2);
9730   push(tmp3);
9731   push(tmp4);
9732   push(tmp5);
9733 
9734   Register op2 = tmp2;
9735   const Register sum = tmp3;
9736   const Register op1 = tmp4;
9737   const Register carry =  tmp5;
9738 
9739   if (UseBMI2Instructions) {
9740     op2 = rdxReg;
9741     movl(op2, k);
9742   }
9743   else {
9744     movl(op2, k);
9745   }
9746 
9747   xorq(carry, carry);
9748 
9749   //First loop
9750 
9751   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9752   //The carry is in tmp5
9753   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9754 
9755   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9756   decrementl(len);
9757   jccb(Assembler::negative, L_carry);
9758   decrementl(len);
9759   jccb(Assembler::negative, L_last_in);
9760 
9761   movq(op1, Address(in, len, Address::times_4,  0));
9762   rorq(op1, 32);
9763 
9764   subl(offs, 2);
9765   movq(sum, Address(out, offs, Address::times_4,  0));
9766   rorq(sum, 32);
9767 
9768   if (UseBMI2Instructions) {
9769     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9770   }
9771   else {
9772     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9773   }
9774 
9775   // Store back in big endian from little endian
9776   rorq(sum, 0x20);
9777   movq(Address(out, offs, Address::times_4,  0), sum);
9778 
9779   testl(len, len);
9780   jccb(Assembler::zero, L_carry);
9781 
9782   //Multiply the last in[] entry, if any
9783   bind(L_last_in);
9784   movl(op1, Address(in, 0));
9785   movl(sum, Address(out, offs, Address::times_4,  -4));
9786 
9787   movl(raxReg, k);
9788   mull(op1); //tmp4 * eax -> edx:eax
9789   addl(sum, carry);
9790   adcl(rdxReg, 0);
9791   addl(sum, raxReg);
9792   adcl(rdxReg, 0);
9793   movl(carry, rdxReg);
9794 
9795   movl(Address(out, offs, Address::times_4,  -4), sum);
9796 
9797   bind(L_carry);
9798   //return tmp5/carry as carry in rax
9799   movl(rax, carry);
9800 
9801   bind(L_done);
9802   pop(tmp5);
9803   pop(tmp4);
9804   pop(tmp3);
9805   pop(tmp2);
9806   pop(tmp1);
9807 }
9808 #endif
9809 
9810 /**
9811  * Emits code to update CRC-32 with a byte value according to constants in table
9812  *
9813  * @param [in,out]crc   Register containing the crc.
9814  * @param [in]val       Register containing the byte to fold into the CRC.
9815  * @param [in]table     Register containing the table of crc constants.
9816  *
9817  * uint32_t crc;
9818  * val = crc_table[(val ^ crc) & 0xFF];
9819  * crc = val ^ (crc >> 8);
9820  *
9821  */
9822 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9823   xorl(val, crc);
9824   andl(val, 0xFF);
9825   shrl(crc, 8); // unsigned shift
9826   xorl(crc, Address(table, val, Address::times_4, 0));
9827 }
9828 
9829 /**
9830 * Fold four 128-bit data chunks
9831 */
9832 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9833   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9834   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9835   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9836   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9837 }
9838 
9839 /**
9840  * Fold 128-bit data chunk
9841  */
9842 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9843   if (UseAVX > 0) {
9844     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9845     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9846     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9847     pxor(xcrc, xtmp);
9848   } else {
9849     movdqa(xtmp, xcrc);
9850     pclmulhdq(xtmp, xK);   // [123:64]
9851     pclmulldq(xcrc, xK);   // [63:0]
9852     pxor(xcrc, xtmp);
9853     movdqu(xtmp, Address(buf, offset));
9854     pxor(xcrc, xtmp);
9855   }
9856 }
9857 
9858 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9859   if (UseAVX > 0) {
9860     vpclmulhdq(xtmp, xK, xcrc);
9861     vpclmulldq(xcrc, xK, xcrc);
9862     pxor(xcrc, xbuf);
9863     pxor(xcrc, xtmp);
9864   } else {
9865     movdqa(xtmp, xcrc);
9866     pclmulhdq(xtmp, xK);
9867     pclmulldq(xcrc, xK);
9868     pxor(xcrc, xbuf);
9869     pxor(xcrc, xtmp);
9870   }
9871 }
9872 
9873 /**
9874  * 8-bit folds to compute 32-bit CRC
9875  *
9876  * uint64_t xcrc;
9877  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9878  */
9879 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9880   movdl(tmp, xcrc);
9881   andl(tmp, 0xFF);
9882   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9883   psrldq(xcrc, 1); // unsigned shift one byte
9884   pxor(xcrc, xtmp);
9885 }
9886 
9887 /**
9888  * uint32_t crc;
9889  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9890  */
9891 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9892   movl(tmp, crc);
9893   andl(tmp, 0xFF);
9894   shrl(crc, 8);
9895   xorl(crc, Address(table, tmp, Address::times_4, 0));
9896 }
9897 
9898 /**
9899  * @param crc   register containing existing CRC (32-bit)
9900  * @param buf   register pointing to input byte buffer (byte*)
9901  * @param len   register containing number of bytes
9902  * @param table register that will contain address of CRC table
9903  * @param tmp   scratch register
9904  */
9905 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9906   assert_different_registers(crc, buf, len, table, tmp, rax);
9907 
9908   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9909   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9910 
9911   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9912   // context for the registers used, where all instructions below are using 128-bit mode
9913   // On EVEX without VL and BW, these instructions will all be AVX.
9914   if (VM_Version::supports_avx512vlbw()) {
9915     movl(tmp, 0xffff);
9916     kmovwl(k1, tmp);
9917   }
9918 
9919   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9920   notl(crc); // ~crc
9921   cmpl(len, 16);
9922   jcc(Assembler::less, L_tail);
9923 
9924   // Align buffer to 16 bytes
9925   movl(tmp, buf);
9926   andl(tmp, 0xF);
9927   jccb(Assembler::zero, L_aligned);
9928   subl(tmp,  16);
9929   addl(len, tmp);
9930 
9931   align(4);
9932   BIND(L_align_loop);
9933   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9934   update_byte_crc32(crc, rax, table);
9935   increment(buf);
9936   incrementl(tmp);
9937   jccb(Assembler::less, L_align_loop);
9938 
9939   BIND(L_aligned);
9940   movl(tmp, len); // save
9941   shrl(len, 4);
9942   jcc(Assembler::zero, L_tail_restore);
9943 
9944   // Fold total 512 bits of polynomial on each iteration
9945   if (VM_Version::supports_vpclmulqdq()) {
9946     Label Parallel_loop, L_No_Parallel;
9947 
9948     cmpl(len, 8);
9949     jccb(Assembler::less, L_No_Parallel);
9950 
9951     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9952     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9953     movdl(xmm5, crc);
9954     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9955     addptr(buf, 64);
9956     subl(len, 7);
9957     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9958 
9959     BIND(Parallel_loop);
9960     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9961     addptr(buf, 64);
9962     subl(len, 4);
9963     jcc(Assembler::greater, Parallel_loop);
9964 
9965     vextracti64x2(xmm2, xmm1, 0x01);
9966     vextracti64x2(xmm3, xmm1, 0x02);
9967     vextracti64x2(xmm4, xmm1, 0x03);
9968     jmp(L_fold_512b);
9969 
9970     BIND(L_No_Parallel);
9971   }
9972   // Fold crc into first bytes of vector
9973   movdqa(xmm1, Address(buf, 0));
9974   movdl(rax, xmm1);
9975   xorl(crc, rax);
9976   if (VM_Version::supports_sse4_1()) {
9977     pinsrd(xmm1, crc, 0);
9978   } else {
9979     pinsrw(xmm1, crc, 0);
9980     shrl(crc, 16);
9981     pinsrw(xmm1, crc, 1);
9982   }
9983   addptr(buf, 16);
9984   subl(len, 4); // len > 0
9985   jcc(Assembler::less, L_fold_tail);
9986 
9987   movdqa(xmm2, Address(buf,  0));
9988   movdqa(xmm3, Address(buf, 16));
9989   movdqa(xmm4, Address(buf, 32));
9990   addptr(buf, 48);
9991   subl(len, 3);
9992   jcc(Assembler::lessEqual, L_fold_512b);
9993 
9994   // Fold total 512 bits of polynomial on each iteration,
9995   // 128 bits per each of 4 parallel streams.
9996   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9997 
9998   align(32);
9999   BIND(L_fold_512b_loop);
10000   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10001   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10002   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10003   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10004   addptr(buf, 64);
10005   subl(len, 4);
10006   jcc(Assembler::greater, L_fold_512b_loop);
10007 
10008   // Fold 512 bits to 128 bits.
10009   BIND(L_fold_512b);
10010   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10011   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10012   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10013   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10014 
10015   // Fold the rest of 128 bits data chunks
10016   BIND(L_fold_tail);
10017   addl(len, 3);
10018   jccb(Assembler::lessEqual, L_fold_128b);
10019   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10020 
10021   BIND(L_fold_tail_loop);
10022   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10023   addptr(buf, 16);
10024   decrementl(len);
10025   jccb(Assembler::greater, L_fold_tail_loop);
10026 
10027   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10028   BIND(L_fold_128b);
10029   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10030   if (UseAVX > 0) {
10031     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10032     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10033     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10034   } else {
10035     movdqa(xmm2, xmm0);
10036     pclmulqdq(xmm2, xmm1, 0x1);
10037     movdqa(xmm3, xmm0);
10038     pand(xmm3, xmm2);
10039     pclmulqdq(xmm0, xmm3, 0x1);
10040   }
10041   psrldq(xmm1, 8);
10042   psrldq(xmm2, 4);
10043   pxor(xmm0, xmm1);
10044   pxor(xmm0, xmm2);
10045 
10046   // 8 8-bit folds to compute 32-bit CRC.
10047   for (int j = 0; j < 4; j++) {
10048     fold_8bit_crc32(xmm0, table, xmm1, rax);
10049   }
10050   movdl(crc, xmm0); // mov 32 bits to general register
10051   for (int j = 0; j < 4; j++) {
10052     fold_8bit_crc32(crc, table, rax);
10053   }
10054 
10055   BIND(L_tail_restore);
10056   movl(len, tmp); // restore
10057   BIND(L_tail);
10058   andl(len, 0xf);
10059   jccb(Assembler::zero, L_exit);
10060 
10061   // Fold the rest of bytes
10062   align(4);
10063   BIND(L_tail_loop);
10064   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10065   update_byte_crc32(crc, rax, table);
10066   increment(buf);
10067   decrementl(len);
10068   jccb(Assembler::greater, L_tail_loop);
10069 
10070   BIND(L_exit);
10071   notl(crc); // ~c
10072 }
10073 
10074 #ifdef _LP64
10075 // S. Gueron / Information Processing Letters 112 (2012) 184
10076 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10077 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10078 // Output: the 64-bit carry-less product of B * CONST
10079 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10080                                      Register tmp1, Register tmp2, Register tmp3) {
10081   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10082   if (n > 0) {
10083     addq(tmp3, n * 256 * 8);
10084   }
10085   //    Q1 = TABLEExt[n][B & 0xFF];
10086   movl(tmp1, in);
10087   andl(tmp1, 0x000000FF);
10088   shll(tmp1, 3);
10089   addq(tmp1, tmp3);
10090   movq(tmp1, Address(tmp1, 0));
10091 
10092   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10093   movl(tmp2, in);
10094   shrl(tmp2, 8);
10095   andl(tmp2, 0x000000FF);
10096   shll(tmp2, 3);
10097   addq(tmp2, tmp3);
10098   movq(tmp2, Address(tmp2, 0));
10099 
10100   shlq(tmp2, 8);
10101   xorq(tmp1, tmp2);
10102 
10103   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10104   movl(tmp2, in);
10105   shrl(tmp2, 16);
10106   andl(tmp2, 0x000000FF);
10107   shll(tmp2, 3);
10108   addq(tmp2, tmp3);
10109   movq(tmp2, Address(tmp2, 0));
10110 
10111   shlq(tmp2, 16);
10112   xorq(tmp1, tmp2);
10113 
10114   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10115   shrl(in, 24);
10116   andl(in, 0x000000FF);
10117   shll(in, 3);
10118   addq(in, tmp3);
10119   movq(in, Address(in, 0));
10120 
10121   shlq(in, 24);
10122   xorq(in, tmp1);
10123   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10124 }
10125 
10126 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10127                                       Register in_out,
10128                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10129                                       XMMRegister w_xtmp2,
10130                                       Register tmp1,
10131                                       Register n_tmp2, Register n_tmp3) {
10132   if (is_pclmulqdq_supported) {
10133     movdl(w_xtmp1, in_out); // modified blindly
10134 
10135     movl(tmp1, const_or_pre_comp_const_index);
10136     movdl(w_xtmp2, tmp1);
10137     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10138 
10139     movdq(in_out, w_xtmp1);
10140   } else {
10141     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10142   }
10143 }
10144 
10145 // Recombination Alternative 2: No bit-reflections
10146 // T1 = (CRC_A * U1) << 1
10147 // T2 = (CRC_B * U2) << 1
10148 // C1 = T1 >> 32
10149 // C2 = T2 >> 32
10150 // T1 = T1 & 0xFFFFFFFF
10151 // T2 = T2 & 0xFFFFFFFF
10152 // T1 = CRC32(0, T1)
10153 // T2 = CRC32(0, T2)
10154 // C1 = C1 ^ T1
10155 // C2 = C2 ^ T2
10156 // CRC = C1 ^ C2 ^ CRC_C
10157 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,
10158                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10159                                      Register tmp1, Register tmp2,
10160                                      Register n_tmp3) {
10161   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10162   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10163   shlq(in_out, 1);
10164   movl(tmp1, in_out);
10165   shrq(in_out, 32);
10166   xorl(tmp2, tmp2);
10167   crc32(tmp2, tmp1, 4);
10168   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10169   shlq(in1, 1);
10170   movl(tmp1, in1);
10171   shrq(in1, 32);
10172   xorl(tmp2, tmp2);
10173   crc32(tmp2, tmp1, 4);
10174   xorl(in1, tmp2);
10175   xorl(in_out, in1);
10176   xorl(in_out, in2);
10177 }
10178 
10179 // Set N to predefined value
10180 // Subtract from a lenght of a buffer
10181 // execute in a loop:
10182 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10183 // for i = 1 to N do
10184 //  CRC_A = CRC32(CRC_A, A[i])
10185 //  CRC_B = CRC32(CRC_B, B[i])
10186 //  CRC_C = CRC32(CRC_C, C[i])
10187 // end for
10188 // Recombine
10189 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,
10190                                        Register in_out1, Register in_out2, Register in_out3,
10191                                        Register tmp1, Register tmp2, Register tmp3,
10192                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10193                                        Register tmp4, Register tmp5,
10194                                        Register n_tmp6) {
10195   Label L_processPartitions;
10196   Label L_processPartition;
10197   Label L_exit;
10198 
10199   bind(L_processPartitions);
10200   cmpl(in_out1, 3 * size);
10201   jcc(Assembler::less, L_exit);
10202     xorl(tmp1, tmp1);
10203     xorl(tmp2, tmp2);
10204     movq(tmp3, in_out2);
10205     addq(tmp3, size);
10206 
10207     bind(L_processPartition);
10208       crc32(in_out3, Address(in_out2, 0), 8);
10209       crc32(tmp1, Address(in_out2, size), 8);
10210       crc32(tmp2, Address(in_out2, size * 2), 8);
10211       addq(in_out2, 8);
10212       cmpq(in_out2, tmp3);
10213       jcc(Assembler::less, L_processPartition);
10214     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10215             w_xtmp1, w_xtmp2, w_xtmp3,
10216             tmp4, tmp5,
10217             n_tmp6);
10218     addq(in_out2, 2 * size);
10219     subl(in_out1, 3 * size);
10220     jmp(L_processPartitions);
10221 
10222   bind(L_exit);
10223 }
10224 #else
10225 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10226                                      Register tmp1, Register tmp2, Register tmp3,
10227                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10228   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10229   if (n > 0) {
10230     addl(tmp3, n * 256 * 8);
10231   }
10232   //    Q1 = TABLEExt[n][B & 0xFF];
10233   movl(tmp1, in_out);
10234   andl(tmp1, 0x000000FF);
10235   shll(tmp1, 3);
10236   addl(tmp1, tmp3);
10237   movq(xtmp1, Address(tmp1, 0));
10238 
10239   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10240   movl(tmp2, in_out);
10241   shrl(tmp2, 8);
10242   andl(tmp2, 0x000000FF);
10243   shll(tmp2, 3);
10244   addl(tmp2, tmp3);
10245   movq(xtmp2, Address(tmp2, 0));
10246 
10247   psllq(xtmp2, 8);
10248   pxor(xtmp1, xtmp2);
10249 
10250   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10251   movl(tmp2, in_out);
10252   shrl(tmp2, 16);
10253   andl(tmp2, 0x000000FF);
10254   shll(tmp2, 3);
10255   addl(tmp2, tmp3);
10256   movq(xtmp2, Address(tmp2, 0));
10257 
10258   psllq(xtmp2, 16);
10259   pxor(xtmp1, xtmp2);
10260 
10261   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10262   shrl(in_out, 24);
10263   andl(in_out, 0x000000FF);
10264   shll(in_out, 3);
10265   addl(in_out, tmp3);
10266   movq(xtmp2, Address(in_out, 0));
10267 
10268   psllq(xtmp2, 24);
10269   pxor(xtmp1, xtmp2); // Result in CXMM
10270   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10271 }
10272 
10273 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10274                                       Register in_out,
10275                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10276                                       XMMRegister w_xtmp2,
10277                                       Register tmp1,
10278                                       Register n_tmp2, Register n_tmp3) {
10279   if (is_pclmulqdq_supported) {
10280     movdl(w_xtmp1, in_out);
10281 
10282     movl(tmp1, const_or_pre_comp_const_index);
10283     movdl(w_xtmp2, tmp1);
10284     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10285     // Keep result in XMM since GPR is 32 bit in length
10286   } else {
10287     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10288   }
10289 }
10290 
10291 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,
10292                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10293                                      Register tmp1, Register tmp2,
10294                                      Register n_tmp3) {
10295   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10296   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10297 
10298   psllq(w_xtmp1, 1);
10299   movdl(tmp1, w_xtmp1);
10300   psrlq(w_xtmp1, 32);
10301   movdl(in_out, w_xtmp1);
10302 
10303   xorl(tmp2, tmp2);
10304   crc32(tmp2, tmp1, 4);
10305   xorl(in_out, tmp2);
10306 
10307   psllq(w_xtmp2, 1);
10308   movdl(tmp1, w_xtmp2);
10309   psrlq(w_xtmp2, 32);
10310   movdl(in1, w_xtmp2);
10311 
10312   xorl(tmp2, tmp2);
10313   crc32(tmp2, tmp1, 4);
10314   xorl(in1, tmp2);
10315   xorl(in_out, in1);
10316   xorl(in_out, in2);
10317 }
10318 
10319 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,
10320                                        Register in_out1, Register in_out2, Register in_out3,
10321                                        Register tmp1, Register tmp2, Register tmp3,
10322                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10323                                        Register tmp4, Register tmp5,
10324                                        Register n_tmp6) {
10325   Label L_processPartitions;
10326   Label L_processPartition;
10327   Label L_exit;
10328 
10329   bind(L_processPartitions);
10330   cmpl(in_out1, 3 * size);
10331   jcc(Assembler::less, L_exit);
10332     xorl(tmp1, tmp1);
10333     xorl(tmp2, tmp2);
10334     movl(tmp3, in_out2);
10335     addl(tmp3, size);
10336 
10337     bind(L_processPartition);
10338       crc32(in_out3, Address(in_out2, 0), 4);
10339       crc32(tmp1, Address(in_out2, size), 4);
10340       crc32(tmp2, Address(in_out2, size*2), 4);
10341       crc32(in_out3, Address(in_out2, 0+4), 4);
10342       crc32(tmp1, Address(in_out2, size+4), 4);
10343       crc32(tmp2, Address(in_out2, size*2+4), 4);
10344       addl(in_out2, 8);
10345       cmpl(in_out2, tmp3);
10346       jcc(Assembler::less, L_processPartition);
10347 
10348         push(tmp3);
10349         push(in_out1);
10350         push(in_out2);
10351         tmp4 = tmp3;
10352         tmp5 = in_out1;
10353         n_tmp6 = in_out2;
10354 
10355       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10356             w_xtmp1, w_xtmp2, w_xtmp3,
10357             tmp4, tmp5,
10358             n_tmp6);
10359 
10360         pop(in_out2);
10361         pop(in_out1);
10362         pop(tmp3);
10363 
10364     addl(in_out2, 2 * size);
10365     subl(in_out1, 3 * size);
10366     jmp(L_processPartitions);
10367 
10368   bind(L_exit);
10369 }
10370 #endif //LP64
10371 
10372 #ifdef _LP64
10373 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10374 // Input: A buffer I of L bytes.
10375 // Output: the CRC32C value of the buffer.
10376 // Notations:
10377 // Write L = 24N + r, with N = floor (L/24).
10378 // r = L mod 24 (0 <= r < 24).
10379 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10380 // N quadwords, and R consists of r bytes.
10381 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10382 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10383 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10384 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10385 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10386                                           Register tmp1, Register tmp2, Register tmp3,
10387                                           Register tmp4, Register tmp5, Register tmp6,
10388                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10389                                           bool is_pclmulqdq_supported) {
10390   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10391   Label L_wordByWord;
10392   Label L_byteByByteProlog;
10393   Label L_byteByByte;
10394   Label L_exit;
10395 
10396   if (is_pclmulqdq_supported ) {
10397     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10398     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10399 
10400     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10401     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10402 
10403     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10404     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10405     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10406   } else {
10407     const_or_pre_comp_const_index[0] = 1;
10408     const_or_pre_comp_const_index[1] = 0;
10409 
10410     const_or_pre_comp_const_index[2] = 3;
10411     const_or_pre_comp_const_index[3] = 2;
10412 
10413     const_or_pre_comp_const_index[4] = 5;
10414     const_or_pre_comp_const_index[5] = 4;
10415    }
10416   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10417                     in2, in1, in_out,
10418                     tmp1, tmp2, tmp3,
10419                     w_xtmp1, w_xtmp2, w_xtmp3,
10420                     tmp4, tmp5,
10421                     tmp6);
10422   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10423                     in2, in1, in_out,
10424                     tmp1, tmp2, tmp3,
10425                     w_xtmp1, w_xtmp2, w_xtmp3,
10426                     tmp4, tmp5,
10427                     tmp6);
10428   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10429                     in2, in1, in_out,
10430                     tmp1, tmp2, tmp3,
10431                     w_xtmp1, w_xtmp2, w_xtmp3,
10432                     tmp4, tmp5,
10433                     tmp6);
10434   movl(tmp1, in2);
10435   andl(tmp1, 0x00000007);
10436   negl(tmp1);
10437   addl(tmp1, in2);
10438   addq(tmp1, in1);
10439 
10440   BIND(L_wordByWord);
10441   cmpq(in1, tmp1);
10442   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10443     crc32(in_out, Address(in1, 0), 4);
10444     addq(in1, 4);
10445     jmp(L_wordByWord);
10446 
10447   BIND(L_byteByByteProlog);
10448   andl(in2, 0x00000007);
10449   movl(tmp2, 1);
10450 
10451   BIND(L_byteByByte);
10452   cmpl(tmp2, in2);
10453   jccb(Assembler::greater, L_exit);
10454     crc32(in_out, Address(in1, 0), 1);
10455     incq(in1);
10456     incl(tmp2);
10457     jmp(L_byteByByte);
10458 
10459   BIND(L_exit);
10460 }
10461 #else
10462 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10463                                           Register tmp1, Register  tmp2, Register tmp3,
10464                                           Register tmp4, Register  tmp5, Register tmp6,
10465                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10466                                           bool is_pclmulqdq_supported) {
10467   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10468   Label L_wordByWord;
10469   Label L_byteByByteProlog;
10470   Label L_byteByByte;
10471   Label L_exit;
10472 
10473   if (is_pclmulqdq_supported) {
10474     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10475     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10476 
10477     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10478     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10479 
10480     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10481     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10482   } else {
10483     const_or_pre_comp_const_index[0] = 1;
10484     const_or_pre_comp_const_index[1] = 0;
10485 
10486     const_or_pre_comp_const_index[2] = 3;
10487     const_or_pre_comp_const_index[3] = 2;
10488 
10489     const_or_pre_comp_const_index[4] = 5;
10490     const_or_pre_comp_const_index[5] = 4;
10491   }
10492   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10493                     in2, in1, in_out,
10494                     tmp1, tmp2, tmp3,
10495                     w_xtmp1, w_xtmp2, w_xtmp3,
10496                     tmp4, tmp5,
10497                     tmp6);
10498   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10499                     in2, in1, in_out,
10500                     tmp1, tmp2, tmp3,
10501                     w_xtmp1, w_xtmp2, w_xtmp3,
10502                     tmp4, tmp5,
10503                     tmp6);
10504   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10505                     in2, in1, in_out,
10506                     tmp1, tmp2, tmp3,
10507                     w_xtmp1, w_xtmp2, w_xtmp3,
10508                     tmp4, tmp5,
10509                     tmp6);
10510   movl(tmp1, in2);
10511   andl(tmp1, 0x00000007);
10512   negl(tmp1);
10513   addl(tmp1, in2);
10514   addl(tmp1, in1);
10515 
10516   BIND(L_wordByWord);
10517   cmpl(in1, tmp1);
10518   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10519     crc32(in_out, Address(in1,0), 4);
10520     addl(in1, 4);
10521     jmp(L_wordByWord);
10522 
10523   BIND(L_byteByByteProlog);
10524   andl(in2, 0x00000007);
10525   movl(tmp2, 1);
10526 
10527   BIND(L_byteByByte);
10528   cmpl(tmp2, in2);
10529   jccb(Assembler::greater, L_exit);
10530     movb(tmp1, Address(in1, 0));
10531     crc32(in_out, tmp1, 1);
10532     incl(in1);
10533     incl(tmp2);
10534     jmp(L_byteByByte);
10535 
10536   BIND(L_exit);
10537 }
10538 #endif // LP64
10539 #undef BIND
10540 #undef BLOCK_COMMENT
10541 
10542 // Compress char[] array to byte[].
10543 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10544 //   @HotSpotIntrinsicCandidate
10545 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10546 //     for (int i = 0; i < len; i++) {
10547 //       int c = src[srcOff++];
10548 //       if (c >>> 8 != 0) {
10549 //         return 0;
10550 //       }
10551 //       dst[dstOff++] = (byte)c;
10552 //     }
10553 //     return len;
10554 //   }
10555 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10556   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10557   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10558   Register tmp5, Register result) {
10559   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10560 
10561   // rsi: src
10562   // rdi: dst
10563   // rdx: len
10564   // rcx: tmp5
10565   // rax: result
10566 
10567   // rsi holds start addr of source char[] to be compressed
10568   // rdi holds start addr of destination byte[]
10569   // rdx holds length
10570 
10571   assert(len != result, "");
10572 
10573   // save length for return
10574   push(len);
10575 
10576   if ((UseAVX > 2) && // AVX512
10577     VM_Version::supports_avx512vlbw() &&
10578     VM_Version::supports_bmi2()) {
10579 
10580     set_vector_masking();  // opening of the stub context for programming mask registers
10581 
10582     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10583 
10584     // alignement
10585     Label post_alignement;
10586 
10587     // if length of the string is less than 16, handle it in an old fashioned
10588     // way
10589     testl(len, -32);
10590     jcc(Assembler::zero, below_threshold);
10591 
10592     // First check whether a character is compressable ( <= 0xFF).
10593     // Create mask to test for Unicode chars inside zmm vector
10594     movl(result, 0x00FF);
10595     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10596 
10597     // Save k1
10598     kmovql(k3, k1);
10599 
10600     testl(len, -64);
10601     jcc(Assembler::zero, post_alignement);
10602 
10603     movl(tmp5, dst);
10604     andl(tmp5, (32 - 1));
10605     negl(tmp5);
10606     andl(tmp5, (32 - 1));
10607 
10608     // bail out when there is nothing to be done
10609     testl(tmp5, 0xFFFFFFFF);
10610     jcc(Assembler::zero, post_alignement);
10611 
10612     // ~(~0 << len), where len is the # of remaining elements to process
10613     movl(result, 0xFFFFFFFF);
10614     shlxl(result, result, tmp5);
10615     notl(result);
10616     kmovdl(k1, result);
10617 
10618     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10619     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10620     ktestd(k2, k1);
10621     jcc(Assembler::carryClear, restore_k1_return_zero);
10622 
10623     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10624 
10625     addptr(src, tmp5);
10626     addptr(src, tmp5);
10627     addptr(dst, tmp5);
10628     subl(len, tmp5);
10629 
10630     bind(post_alignement);
10631     // end of alignement
10632 
10633     movl(tmp5, len);
10634     andl(tmp5, (32 - 1));    // tail count (in chars)
10635     andl(len, ~(32 - 1));    // vector count (in chars)
10636     jcc(Assembler::zero, copy_loop_tail);
10637 
10638     lea(src, Address(src, len, Address::times_2));
10639     lea(dst, Address(dst, len, Address::times_1));
10640     negptr(len);
10641 
10642     bind(copy_32_loop);
10643     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10644     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10645     kortestdl(k2, k2);
10646     jcc(Assembler::carryClear, restore_k1_return_zero);
10647 
10648     // All elements in current processed chunk are valid candidates for
10649     // compression. Write a truncated byte elements to the memory.
10650     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10651     addptr(len, 32);
10652     jcc(Assembler::notZero, copy_32_loop);
10653 
10654     bind(copy_loop_tail);
10655     // bail out when there is nothing to be done
10656     testl(tmp5, 0xFFFFFFFF);
10657     // Restore k1
10658     kmovql(k1, k3);
10659     jcc(Assembler::zero, return_length);
10660 
10661     movl(len, tmp5);
10662 
10663     // ~(~0 << len), where len is the # of remaining elements to process
10664     movl(result, 0xFFFFFFFF);
10665     shlxl(result, result, len);
10666     notl(result);
10667 
10668     kmovdl(k1, result);
10669 
10670     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10671     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10672     ktestd(k2, k1);
10673     jcc(Assembler::carryClear, restore_k1_return_zero);
10674 
10675     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10676     // Restore k1
10677     kmovql(k1, k3);
10678     jmp(return_length);
10679 
10680     bind(restore_k1_return_zero);
10681     // Restore k1
10682     kmovql(k1, k3);
10683     jmp(return_zero);
10684 
10685     clear_vector_masking();   // closing of the stub context for programming mask registers
10686   }
10687   if (UseSSE42Intrinsics) {
10688     Label copy_32_loop, copy_16, copy_tail;
10689 
10690     bind(below_threshold);
10691 
10692     movl(result, len);
10693 
10694     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10695 
10696     // vectored compression
10697     andl(len, 0xfffffff0);    // vector count (in chars)
10698     andl(result, 0x0000000f);    // tail count (in chars)
10699     testl(len, len);
10700     jccb(Assembler::zero, copy_16);
10701 
10702     // compress 16 chars per iter
10703     movdl(tmp1Reg, tmp5);
10704     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10705     pxor(tmp4Reg, tmp4Reg);
10706 
10707     lea(src, Address(src, len, Address::times_2));
10708     lea(dst, Address(dst, len, Address::times_1));
10709     negptr(len);
10710 
10711     bind(copy_32_loop);
10712     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10713     por(tmp4Reg, tmp2Reg);
10714     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10715     por(tmp4Reg, tmp3Reg);
10716     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10717     jcc(Assembler::notZero, return_zero);
10718     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10719     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10720     addptr(len, 16);
10721     jcc(Assembler::notZero, copy_32_loop);
10722 
10723     // compress next vector of 8 chars (if any)
10724     bind(copy_16);
10725     movl(len, result);
10726     andl(len, 0xfffffff8);    // vector count (in chars)
10727     andl(result, 0x00000007);    // tail count (in chars)
10728     testl(len, len);
10729     jccb(Assembler::zero, copy_tail);
10730 
10731     movdl(tmp1Reg, tmp5);
10732     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10733     pxor(tmp3Reg, tmp3Reg);
10734 
10735     movdqu(tmp2Reg, Address(src, 0));
10736     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10737     jccb(Assembler::notZero, return_zero);
10738     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10739     movq(Address(dst, 0), tmp2Reg);
10740     addptr(src, 16);
10741     addptr(dst, 8);
10742 
10743     bind(copy_tail);
10744     movl(len, result);
10745   }
10746   // compress 1 char per iter
10747   testl(len, len);
10748   jccb(Assembler::zero, return_length);
10749   lea(src, Address(src, len, Address::times_2));
10750   lea(dst, Address(dst, len, Address::times_1));
10751   negptr(len);
10752 
10753   bind(copy_chars_loop);
10754   load_unsigned_short(result, Address(src, len, Address::times_2));
10755   testl(result, 0xff00);      // check if Unicode char
10756   jccb(Assembler::notZero, return_zero);
10757   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10758   increment(len);
10759   jcc(Assembler::notZero, copy_chars_loop);
10760 
10761   // if compression succeeded, return length
10762   bind(return_length);
10763   pop(result);
10764   jmpb(done);
10765 
10766   // if compression failed, return 0
10767   bind(return_zero);
10768   xorl(result, result);
10769   addptr(rsp, wordSize);
10770 
10771   bind(done);
10772 }
10773 
10774 // Inflate byte[] array to char[].
10775 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10776 //   @HotSpotIntrinsicCandidate
10777 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10778 //     for (int i = 0; i < len; i++) {
10779 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10780 //     }
10781 //   }
10782 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10783   XMMRegister tmp1, Register tmp2) {
10784   Label copy_chars_loop, done, below_threshold;
10785   // rsi: src
10786   // rdi: dst
10787   // rdx: len
10788   // rcx: tmp2
10789 
10790   // rsi holds start addr of source byte[] to be inflated
10791   // rdi holds start addr of destination char[]
10792   // rdx holds length
10793   assert_different_registers(src, dst, len, tmp2);
10794 
10795   if ((UseAVX > 2) && // AVX512
10796     VM_Version::supports_avx512vlbw() &&
10797     VM_Version::supports_bmi2()) {
10798 
10799     set_vector_masking();  // opening of the stub context for programming mask registers
10800 
10801     Label copy_32_loop, copy_tail;
10802     Register tmp3_aliased = len;
10803 
10804     // if length of the string is less than 16, handle it in an old fashioned
10805     // way
10806     testl(len, -16);
10807     jcc(Assembler::zero, below_threshold);
10808 
10809     // In order to use only one arithmetic operation for the main loop we use
10810     // this pre-calculation
10811     movl(tmp2, len);
10812     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10813     andl(len, -32);     // vector count
10814     jccb(Assembler::zero, copy_tail);
10815 
10816     lea(src, Address(src, len, Address::times_1));
10817     lea(dst, Address(dst, len, Address::times_2));
10818     negptr(len);
10819 
10820 
10821     // inflate 32 chars per iter
10822     bind(copy_32_loop);
10823     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10824     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10825     addptr(len, 32);
10826     jcc(Assembler::notZero, copy_32_loop);
10827 
10828     bind(copy_tail);
10829     // bail out when there is nothing to be done
10830     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10831     jcc(Assembler::zero, done);
10832 
10833     // Save k1
10834     kmovql(k2, k1);
10835 
10836     // ~(~0 << length), where length is the # of remaining elements to process
10837     movl(tmp3_aliased, -1);
10838     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10839     notl(tmp3_aliased);
10840     kmovdl(k1, tmp3_aliased);
10841     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10842     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10843 
10844     // Restore k1
10845     kmovql(k1, k2);
10846     jmp(done);
10847 
10848     clear_vector_masking();   // closing of the stub context for programming mask registers
10849   }
10850   if (UseSSE42Intrinsics) {
10851     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10852 
10853     movl(tmp2, len);
10854 
10855     if (UseAVX > 1) {
10856       andl(tmp2, (16 - 1));
10857       andl(len, -16);
10858       jccb(Assembler::zero, copy_new_tail);
10859     } else {
10860       andl(tmp2, 0x00000007);   // tail count (in chars)
10861       andl(len, 0xfffffff8);    // vector count (in chars)
10862       jccb(Assembler::zero, copy_tail);
10863     }
10864 
10865     // vectored inflation
10866     lea(src, Address(src, len, Address::times_1));
10867     lea(dst, Address(dst, len, Address::times_2));
10868     negptr(len);
10869 
10870     if (UseAVX > 1) {
10871       bind(copy_16_loop);
10872       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10873       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10874       addptr(len, 16);
10875       jcc(Assembler::notZero, copy_16_loop);
10876 
10877       bind(below_threshold);
10878       bind(copy_new_tail);
10879       if ((UseAVX > 2) &&
10880         VM_Version::supports_avx512vlbw() &&
10881         VM_Version::supports_bmi2()) {
10882         movl(tmp2, len);
10883       } else {
10884         movl(len, tmp2);
10885       }
10886       andl(tmp2, 0x00000007);
10887       andl(len, 0xFFFFFFF8);
10888       jccb(Assembler::zero, copy_tail);
10889 
10890       pmovzxbw(tmp1, Address(src, 0));
10891       movdqu(Address(dst, 0), tmp1);
10892       addptr(src, 8);
10893       addptr(dst, 2 * 8);
10894 
10895       jmp(copy_tail, true);
10896     }
10897 
10898     // inflate 8 chars per iter
10899     bind(copy_8_loop);
10900     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10901     movdqu(Address(dst, len, Address::times_2), tmp1);
10902     addptr(len, 8);
10903     jcc(Assembler::notZero, copy_8_loop);
10904 
10905     bind(copy_tail);
10906     movl(len, tmp2);
10907 
10908     cmpl(len, 4);
10909     jccb(Assembler::less, copy_bytes);
10910 
10911     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10912     pmovzxbw(tmp1, tmp1);
10913     movq(Address(dst, 0), tmp1);
10914     subptr(len, 4);
10915     addptr(src, 4);
10916     addptr(dst, 8);
10917 
10918     bind(copy_bytes);
10919   }
10920   testl(len, len);
10921   jccb(Assembler::zero, done);
10922   lea(src, Address(src, len, Address::times_1));
10923   lea(dst, Address(dst, len, Address::times_2));
10924   negptr(len);
10925 
10926   // inflate 1 char per iter
10927   bind(copy_chars_loop);
10928   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10929   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10930   increment(len);
10931   jcc(Assembler::notZero, copy_chars_loop);
10932 
10933   bind(done);
10934 }
10935 
10936 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10937   switch (cond) {
10938     // Note some conditions are synonyms for others
10939     case Assembler::zero:         return Assembler::notZero;
10940     case Assembler::notZero:      return Assembler::zero;
10941     case Assembler::less:         return Assembler::greaterEqual;
10942     case Assembler::lessEqual:    return Assembler::greater;
10943     case Assembler::greater:      return Assembler::lessEqual;
10944     case Assembler::greaterEqual: return Assembler::less;
10945     case Assembler::below:        return Assembler::aboveEqual;
10946     case Assembler::belowEqual:   return Assembler::above;
10947     case Assembler::above:        return Assembler::belowEqual;
10948     case Assembler::aboveEqual:   return Assembler::below;
10949     case Assembler::overflow:     return Assembler::noOverflow;
10950     case Assembler::noOverflow:   return Assembler::overflow;
10951     case Assembler::negative:     return Assembler::positive;
10952     case Assembler::positive:     return Assembler::negative;
10953     case Assembler::parity:       return Assembler::noParity;
10954     case Assembler::noParity:     return Assembler::parity;
10955   }
10956   ShouldNotReachHere(); return Assembler::overflow;
10957 }
10958 
10959 SkipIfEqual::SkipIfEqual(
10960     MacroAssembler* masm, const bool* flag_addr, bool value) {
10961   _masm = masm;
10962   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10963   _masm->jcc(Assembler::equal, _label);
10964 }
10965 
10966 SkipIfEqual::~SkipIfEqual() {
10967   _masm->bind(_label);
10968 }
10969 
10970 // 32-bit Windows has its own fast-path implementation
10971 // of get_thread
10972 #if !defined(WIN32) || defined(_LP64)
10973 
10974 // This is simply a call to Thread::current()
10975 void MacroAssembler::get_thread(Register thread) {
10976   if (thread != rax) {
10977     push(rax);
10978   }
10979   LP64_ONLY(push(rdi);)
10980   LP64_ONLY(push(rsi);)
10981   push(rdx);
10982   push(rcx);
10983 #ifdef _LP64
10984   push(r8);
10985   push(r9);
10986   push(r10);
10987   push(r11);
10988 #endif
10989 
10990   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10991 
10992 #ifdef _LP64
10993   pop(r11);
10994   pop(r10);
10995   pop(r9);
10996   pop(r8);
10997 #endif
10998   pop(rcx);
10999   pop(rdx);
11000   LP64_ONLY(pop(rsi);)
11001   LP64_ONLY(pop(rdi);)
11002   if (thread != rax) {
11003     mov(thread, rax);
11004     pop(rax);
11005   }
11006 }
11007 
11008 #endif