1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "utilities/macros.hpp"
  43 #if INCLUDE_ALL_GCS
  44 #include "gc/g1/g1CollectedHeap.inline.hpp"
  45 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  46 #include "gc/g1/heapRegion.hpp"
  47 #endif // INCLUDE_ALL_GCS
  48 #include "crc32c.h"
  49 #ifdef COMPILER2
  50 #include "opto/intrinsicnode.hpp"
  51 #endif
  52 
  53 #ifdef PRODUCT
  54 #define BLOCK_COMMENT(str) /* nothing */
  55 #define STOP(error) stop(error)
  56 #else
  57 #define BLOCK_COMMENT(str) block_comment(str)
  58 #define STOP(error) block_comment(error); stop(error)
  59 #endif
  60 
  61 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  62 
  63 #ifdef ASSERT
  64 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  65 #endif
  66 
  67 static Assembler::Condition reverse[] = {
  68     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  69     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  70     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  71     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  72     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  73     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  74     Assembler::above          /* belowEqual    = 0x6 */ ,
  75     Assembler::belowEqual     /* above         = 0x7 */ ,
  76     Assembler::positive       /* negative      = 0x8 */ ,
  77     Assembler::negative       /* positive      = 0x9 */ ,
  78     Assembler::noParity       /* parity        = 0xa */ ,
  79     Assembler::parity         /* noParity      = 0xb */ ,
  80     Assembler::greaterEqual   /* less          = 0xc */ ,
  81     Assembler::less           /* greaterEqual  = 0xd */ ,
  82     Assembler::greater        /* lessEqual     = 0xe */ ,
  83     Assembler::lessEqual      /* greater       = 0xf, */
  84 
  85 };
  86 
  87 
  88 // Implementation of MacroAssembler
  89 
  90 // First all the versions that have distinct versions depending on 32/64 bit
  91 // Unless the difference is trivial (1 line or so).
  92 
  93 #ifndef _LP64
  94 
  95 // 32bit versions
  96 
  97 Address MacroAssembler::as_Address(AddressLiteral adr) {
  98   return Address(adr.target(), adr.rspec());
  99 }
 100 
 101 Address MacroAssembler::as_Address(ArrayAddress adr) {
 102   return Address::make_array(adr);
 103 }
 104 
 105 void MacroAssembler::call_VM_leaf_base(address entry_point,
 106                                        int number_of_arguments) {
 107   call(RuntimeAddress(entry_point));
 108   increment(rsp, number_of_arguments * wordSize);
 109 }
 110 
 111 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 112   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 113 }
 114 
 115 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 116   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 117 }
 118 
 119 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 120   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 121 }
 122 
 123 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 124   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 125 }
 126 
 127 void MacroAssembler::extend_sign(Register hi, Register lo) {
 128   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 129   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 130     cdql();
 131   } else {
 132     movl(hi, lo);
 133     sarl(hi, 31);
 134   }
 135 }
 136 
 137 void MacroAssembler::jC2(Register tmp, Label& L) {
 138   // set parity bit if FPU flag C2 is set (via rax)
 139   save_rax(tmp);
 140   fwait(); fnstsw_ax();
 141   sahf();
 142   restore_rax(tmp);
 143   // branch
 144   jcc(Assembler::parity, L);
 145 }
 146 
 147 void MacroAssembler::jnC2(Register tmp, Label& L) {
 148   // set parity bit if FPU flag C2 is set (via rax)
 149   save_rax(tmp);
 150   fwait(); fnstsw_ax();
 151   sahf();
 152   restore_rax(tmp);
 153   // branch
 154   jcc(Assembler::noParity, L);
 155 }
 156 
 157 // 32bit can do a case table jump in one instruction but we no longer allow the base
 158 // to be installed in the Address class
 159 void MacroAssembler::jump(ArrayAddress entry) {
 160   jmp(as_Address(entry));
 161 }
 162 
 163 // Note: y_lo will be destroyed
 164 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 165   // Long compare for Java (semantics as described in JVM spec.)
 166   Label high, low, done;
 167 
 168   cmpl(x_hi, y_hi);
 169   jcc(Assembler::less, low);
 170   jcc(Assembler::greater, high);
 171   // x_hi is the return register
 172   xorl(x_hi, x_hi);
 173   cmpl(x_lo, y_lo);
 174   jcc(Assembler::below, low);
 175   jcc(Assembler::equal, done);
 176 
 177   bind(high);
 178   xorl(x_hi, x_hi);
 179   increment(x_hi);
 180   jmp(done);
 181 
 182   bind(low);
 183   xorl(x_hi, x_hi);
 184   decrementl(x_hi);
 185 
 186   bind(done);
 187 }
 188 
 189 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 190     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 191 }
 192 
 193 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 194   // leal(dst, as_Address(adr));
 195   // see note in movl as to why we must use a move
 196   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 197 }
 198 
 199 void MacroAssembler::leave() {
 200   mov(rsp, rbp);
 201   pop(rbp);
 202 }
 203 
 204 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 205   // Multiplication of two Java long values stored on the stack
 206   // as illustrated below. Result is in rdx:rax.
 207   //
 208   // rsp ---> [  ??  ] \               \
 209   //            ....    | y_rsp_offset  |
 210   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 211   //          [ y_hi ]                  | (in bytes)
 212   //            ....                    |
 213   //          [ x_lo ]                 /
 214   //          [ x_hi ]
 215   //            ....
 216   //
 217   // Basic idea: lo(result) = lo(x_lo * y_lo)
 218   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 219   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 220   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 221   Label quick;
 222   // load x_hi, y_hi and check if quick
 223   // multiplication is possible
 224   movl(rbx, x_hi);
 225   movl(rcx, y_hi);
 226   movl(rax, rbx);
 227   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 228   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 229   // do full multiplication
 230   // 1st step
 231   mull(y_lo);                                    // x_hi * y_lo
 232   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 233   // 2nd step
 234   movl(rax, x_lo);
 235   mull(rcx);                                     // x_lo * y_hi
 236   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 237   // 3rd step
 238   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 239   movl(rax, x_lo);
 240   mull(y_lo);                                    // x_lo * y_lo
 241   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 242 }
 243 
 244 void MacroAssembler::lneg(Register hi, Register lo) {
 245   negl(lo);
 246   adcl(hi, 0);
 247   negl(hi);
 248 }
 249 
 250 void MacroAssembler::lshl(Register hi, Register lo) {
 251   // Java shift left long support (semantics as described in JVM spec., p.305)
 252   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 253   // shift value is in rcx !
 254   assert(hi != rcx, "must not use rcx");
 255   assert(lo != rcx, "must not use rcx");
 256   const Register s = rcx;                        // shift count
 257   const int      n = BitsPerWord;
 258   Label L;
 259   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 260   cmpl(s, n);                                    // if (s < n)
 261   jcc(Assembler::less, L);                       // else (s >= n)
 262   movl(hi, lo);                                  // x := x << n
 263   xorl(lo, lo);
 264   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 265   bind(L);                                       // s (mod n) < n
 266   shldl(hi, lo);                                 // x := x << s
 267   shll(lo);
 268 }
 269 
 270 
 271 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 272   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 273   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 274   assert(hi != rcx, "must not use rcx");
 275   assert(lo != rcx, "must not use rcx");
 276   const Register s = rcx;                        // shift count
 277   const int      n = BitsPerWord;
 278   Label L;
 279   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 280   cmpl(s, n);                                    // if (s < n)
 281   jcc(Assembler::less, L);                       // else (s >= n)
 282   movl(lo, hi);                                  // x := x >> n
 283   if (sign_extension) sarl(hi, 31);
 284   else                xorl(hi, hi);
 285   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 286   bind(L);                                       // s (mod n) < n
 287   shrdl(lo, hi);                                 // x := x >> s
 288   if (sign_extension) sarl(hi);
 289   else                shrl(hi);
 290 }
 291 
 292 void MacroAssembler::movoop(Register dst, jobject obj) {
 293   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 294 }
 295 
 296 void MacroAssembler::movoop(Address dst, jobject obj) {
 297   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 298 }
 299 
 300 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 301   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 302 }
 303 
 304 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 305   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 306 }
 307 
 308 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 309   // scratch register is not used,
 310   // it is defined to match parameters of 64-bit version of this method.
 311   if (src.is_lval()) {
 312     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 313   } else {
 314     movl(dst, as_Address(src));
 315   }
 316 }
 317 
 318 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 319   movl(as_Address(dst), src);
 320 }
 321 
 322 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 323   movl(dst, as_Address(src));
 324 }
 325 
 326 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 327 void MacroAssembler::movptr(Address dst, intptr_t src) {
 328   movl(dst, src);
 329 }
 330 
 331 
 332 void MacroAssembler::pop_callee_saved_registers() {
 333   pop(rcx);
 334   pop(rdx);
 335   pop(rdi);
 336   pop(rsi);
 337 }
 338 
 339 void MacroAssembler::pop_fTOS() {
 340   fld_d(Address(rsp, 0));
 341   addl(rsp, 2 * wordSize);
 342 }
 343 
 344 void MacroAssembler::push_callee_saved_registers() {
 345   push(rsi);
 346   push(rdi);
 347   push(rdx);
 348   push(rcx);
 349 }
 350 
 351 void MacroAssembler::push_fTOS() {
 352   subl(rsp, 2 * wordSize);
 353   fstp_d(Address(rsp, 0));
 354 }
 355 
 356 
 357 void MacroAssembler::pushoop(jobject obj) {
 358   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 359 }
 360 
 361 void MacroAssembler::pushklass(Metadata* obj) {
 362   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 363 }
 364 
 365 void MacroAssembler::pushptr(AddressLiteral src) {
 366   if (src.is_lval()) {
 367     push_literal32((int32_t)src.target(), src.rspec());
 368   } else {
 369     pushl(as_Address(src));
 370   }
 371 }
 372 
 373 void MacroAssembler::set_word_if_not_zero(Register dst) {
 374   xorl(dst, dst);
 375   set_byte_if_not_zero(dst);
 376 }
 377 
 378 static void pass_arg0(MacroAssembler* masm, Register arg) {
 379   masm->push(arg);
 380 }
 381 
 382 static void pass_arg1(MacroAssembler* masm, Register arg) {
 383   masm->push(arg);
 384 }
 385 
 386 static void pass_arg2(MacroAssembler* masm, Register arg) {
 387   masm->push(arg);
 388 }
 389 
 390 static void pass_arg3(MacroAssembler* masm, Register arg) {
 391   masm->push(arg);
 392 }
 393 
 394 #ifndef PRODUCT
 395 extern "C" void findpc(intptr_t x);
 396 #endif
 397 
 398 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 399   // In order to get locks to work, we need to fake a in_VM state
 400   JavaThread* thread = JavaThread::current();
 401   JavaThreadState saved_state = thread->thread_state();
 402   thread->set_thread_state(_thread_in_vm);
 403   if (ShowMessageBoxOnError) {
 404     JavaThread* thread = JavaThread::current();
 405     JavaThreadState saved_state = thread->thread_state();
 406     thread->set_thread_state(_thread_in_vm);
 407     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 408       ttyLocker ttyl;
 409       BytecodeCounter::print();
 410     }
 411     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 412     // This is the value of eip which points to where verify_oop will return.
 413     if (os::message_box(msg, "Execution stopped, print registers?")) {
 414       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 415       BREAKPOINT;
 416     }
 417   } else {
 418     ttyLocker ttyl;
 419     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 420   }
 421   // Don't assert holding the ttyLock
 422     assert(false, "DEBUG MESSAGE: %s", msg);
 423   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 424 }
 425 
 426 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 427   ttyLocker ttyl;
 428   FlagSetting fs(Debugging, true);
 429   tty->print_cr("eip = 0x%08x", eip);
 430 #ifndef PRODUCT
 431   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 432     tty->cr();
 433     findpc(eip);
 434     tty->cr();
 435   }
 436 #endif
 437 #define PRINT_REG(rax) \
 438   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 439   PRINT_REG(rax);
 440   PRINT_REG(rbx);
 441   PRINT_REG(rcx);
 442   PRINT_REG(rdx);
 443   PRINT_REG(rdi);
 444   PRINT_REG(rsi);
 445   PRINT_REG(rbp);
 446   PRINT_REG(rsp);
 447 #undef PRINT_REG
 448   // Print some words near top of staack.
 449   int* dump_sp = (int*) rsp;
 450   for (int col1 = 0; col1 < 8; col1++) {
 451     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 452     os::print_location(tty, *dump_sp++);
 453   }
 454   for (int row = 0; row < 16; row++) {
 455     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 456     for (int col = 0; col < 8; col++) {
 457       tty->print(" 0x%08x", *dump_sp++);
 458     }
 459     tty->cr();
 460   }
 461   // Print some instructions around pc:
 462   Disassembler::decode((address)eip-64, (address)eip);
 463   tty->print_cr("--------");
 464   Disassembler::decode((address)eip, (address)eip+32);
 465 }
 466 
 467 void MacroAssembler::stop(const char* msg) {
 468   ExternalAddress message((address)msg);
 469   // push address of message
 470   pushptr(message.addr());
 471   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 472   pusha();                                            // push registers
 473   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 474   hlt();
 475 }
 476 
 477 void MacroAssembler::warn(const char* msg) {
 478   push_CPU_state();
 479 
 480   ExternalAddress message((address) msg);
 481   // push address of message
 482   pushptr(message.addr());
 483 
 484   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 485   addl(rsp, wordSize);       // discard argument
 486   pop_CPU_state();
 487 }
 488 
 489 void MacroAssembler::print_state() {
 490   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 491   pusha();                                            // push registers
 492 
 493   push_CPU_state();
 494   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 495   pop_CPU_state();
 496 
 497   popa();
 498   addl(rsp, wordSize);
 499 }
 500 
 501 #else // _LP64
 502 
 503 // 64 bit versions
 504 
 505 Address MacroAssembler::as_Address(AddressLiteral adr) {
 506   // amd64 always does this as a pc-rel
 507   // we can be absolute or disp based on the instruction type
 508   // jmp/call are displacements others are absolute
 509   assert(!adr.is_lval(), "must be rval");
 510   assert(reachable(adr), "must be");
 511   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 512 
 513 }
 514 
 515 Address MacroAssembler::as_Address(ArrayAddress adr) {
 516   AddressLiteral base = adr.base();
 517   lea(rscratch1, base);
 518   Address index = adr.index();
 519   assert(index._disp == 0, "must not have disp"); // maybe it can?
 520   Address array(rscratch1, index._index, index._scale, index._disp);
 521   return array;
 522 }
 523 
 524 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 525   Label L, E;
 526 
 527 #ifdef _WIN64
 528   // Windows always allocates space for it's register args
 529   assert(num_args <= 4, "only register arguments supported");
 530   subq(rsp,  frame::arg_reg_save_area_bytes);
 531 #endif
 532 
 533   // Align stack if necessary
 534   testl(rsp, 15);
 535   jcc(Assembler::zero, L);
 536 
 537   subq(rsp, 8);
 538   {
 539     call(RuntimeAddress(entry_point));
 540   }
 541   addq(rsp, 8);
 542   jmp(E);
 543 
 544   bind(L);
 545   {
 546     call(RuntimeAddress(entry_point));
 547   }
 548 
 549   bind(E);
 550 
 551 #ifdef _WIN64
 552   // restore stack pointer
 553   addq(rsp, frame::arg_reg_save_area_bytes);
 554 #endif
 555 
 556 }
 557 
 558 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 559   assert(!src2.is_lval(), "should use cmpptr");
 560 
 561   if (reachable(src2)) {
 562     cmpq(src1, as_Address(src2));
 563   } else {
 564     lea(rscratch1, src2);
 565     Assembler::cmpq(src1, Address(rscratch1, 0));
 566   }
 567 }
 568 
 569 int MacroAssembler::corrected_idivq(Register reg) {
 570   // Full implementation of Java ldiv and lrem; checks for special
 571   // case as described in JVM spec., p.243 & p.271.  The function
 572   // returns the (pc) offset of the idivl instruction - may be needed
 573   // for implicit exceptions.
 574   //
 575   //         normal case                           special case
 576   //
 577   // input : rax: dividend                         min_long
 578   //         reg: divisor   (may not be eax/edx)   -1
 579   //
 580   // output: rax: quotient  (= rax idiv reg)       min_long
 581   //         rdx: remainder (= rax irem reg)       0
 582   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 583   static const int64_t min_long = 0x8000000000000000;
 584   Label normal_case, special_case;
 585 
 586   // check for special case
 587   cmp64(rax, ExternalAddress((address) &min_long));
 588   jcc(Assembler::notEqual, normal_case);
 589   xorl(rdx, rdx); // prepare rdx for possible special case (where
 590                   // remainder = 0)
 591   cmpq(reg, -1);
 592   jcc(Assembler::equal, special_case);
 593 
 594   // handle normal case
 595   bind(normal_case);
 596   cdqq();
 597   int idivq_offset = offset();
 598   idivq(reg);
 599 
 600   // normal and special case exit
 601   bind(special_case);
 602 
 603   return idivq_offset;
 604 }
 605 
 606 void MacroAssembler::decrementq(Register reg, int value) {
 607   if (value == min_jint) { subq(reg, value); return; }
 608   if (value <  0) { incrementq(reg, -value); return; }
 609   if (value == 0) {                        ; return; }
 610   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 611   /* else */      { subq(reg, value)       ; return; }
 612 }
 613 
 614 void MacroAssembler::decrementq(Address dst, int value) {
 615   if (value == min_jint) { subq(dst, value); return; }
 616   if (value <  0) { incrementq(dst, -value); return; }
 617   if (value == 0) {                        ; return; }
 618   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 619   /* else */      { subq(dst, value)       ; return; }
 620 }
 621 
 622 void MacroAssembler::incrementq(AddressLiteral dst) {
 623   if (reachable(dst)) {
 624     incrementq(as_Address(dst));
 625   } else {
 626     lea(rscratch1, dst);
 627     incrementq(Address(rscratch1, 0));
 628   }
 629 }
 630 
 631 void MacroAssembler::incrementq(Register reg, int value) {
 632   if (value == min_jint) { addq(reg, value); return; }
 633   if (value <  0) { decrementq(reg, -value); return; }
 634   if (value == 0) {                        ; return; }
 635   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 636   /* else */      { addq(reg, value)       ; return; }
 637 }
 638 
 639 void MacroAssembler::incrementq(Address dst, int value) {
 640   if (value == min_jint) { addq(dst, value); return; }
 641   if (value <  0) { decrementq(dst, -value); return; }
 642   if (value == 0) {                        ; return; }
 643   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 644   /* else */      { addq(dst, value)       ; return; }
 645 }
 646 
 647 // 32bit can do a case table jump in one instruction but we no longer allow the base
 648 // to be installed in the Address class
 649 void MacroAssembler::jump(ArrayAddress entry) {
 650   lea(rscratch1, entry.base());
 651   Address dispatch = entry.index();
 652   assert(dispatch._base == noreg, "must be");
 653   dispatch._base = rscratch1;
 654   jmp(dispatch);
 655 }
 656 
 657 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 658   ShouldNotReachHere(); // 64bit doesn't use two regs
 659   cmpq(x_lo, y_lo);
 660 }
 661 
 662 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 663     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 664 }
 665 
 666 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 667   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 668   movptr(dst, rscratch1);
 669 }
 670 
 671 void MacroAssembler::leave() {
 672   // %%% is this really better? Why not on 32bit too?
 673   emit_int8((unsigned char)0xC9); // LEAVE
 674 }
 675 
 676 void MacroAssembler::lneg(Register hi, Register lo) {
 677   ShouldNotReachHere(); // 64bit doesn't use two regs
 678   negq(lo);
 679 }
 680 
 681 void MacroAssembler::movoop(Register dst, jobject obj) {
 682   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 683 }
 684 
 685 void MacroAssembler::movoop(Address dst, jobject obj) {
 686   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 687   movq(dst, rscratch1);
 688 }
 689 
 690 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 691   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 692 }
 693 
 694 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 695   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 696   movq(dst, rscratch1);
 697 }
 698 
 699 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 700   if (src.is_lval()) {
 701     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 702   } else {
 703     if (reachable(src)) {
 704       movq(dst, as_Address(src));
 705     } else {
 706       lea(scratch, src);
 707       movq(dst, Address(scratch, 0));
 708     }
 709   }
 710 }
 711 
 712 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 713   movq(as_Address(dst), src);
 714 }
 715 
 716 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 717   movq(dst, as_Address(src));
 718 }
 719 
 720 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 721 void MacroAssembler::movptr(Address dst, intptr_t src) {
 722   mov64(rscratch1, src);
 723   movq(dst, rscratch1);
 724 }
 725 
 726 // These are mostly for initializing NULL
 727 void MacroAssembler::movptr(Address dst, int32_t src) {
 728   movslq(dst, src);
 729 }
 730 
 731 void MacroAssembler::movptr(Register dst, int32_t src) {
 732   mov64(dst, (intptr_t)src);
 733 }
 734 
 735 void MacroAssembler::pushoop(jobject obj) {
 736   movoop(rscratch1, obj);
 737   push(rscratch1);
 738 }
 739 
 740 void MacroAssembler::pushklass(Metadata* obj) {
 741   mov_metadata(rscratch1, obj);
 742   push(rscratch1);
 743 }
 744 
 745 void MacroAssembler::pushptr(AddressLiteral src) {
 746   lea(rscratch1, src);
 747   if (src.is_lval()) {
 748     push(rscratch1);
 749   } else {
 750     pushq(Address(rscratch1, 0));
 751   }
 752 }
 753 
 754 void MacroAssembler::reset_last_Java_frame(bool clear_fp,
 755                                            bool clear_pc) {
 756   // we must set sp to zero to clear frame
 757   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 758   // must clear fp, so that compiled frames are not confused; it is
 759   // possible that we need it only for debugging
 760   if (clear_fp) {
 761     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 762   }
 763 
 764   if (clear_pc) {
 765     movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 766   }
 767 }
 768 
 769 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 770                                          Register last_java_fp,
 771                                          address  last_java_pc) {
 772   // determine last_java_sp register
 773   if (!last_java_sp->is_valid()) {
 774     last_java_sp = rsp;
 775   }
 776 
 777   // last_java_fp is optional
 778   if (last_java_fp->is_valid()) {
 779     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 780            last_java_fp);
 781   }
 782 
 783   // last_java_pc is optional
 784   if (last_java_pc != NULL) {
 785     Address java_pc(r15_thread,
 786                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 787     lea(rscratch1, InternalAddress(last_java_pc));
 788     movptr(java_pc, rscratch1);
 789   }
 790 
 791   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 792 }
 793 
 794 static void pass_arg0(MacroAssembler* masm, Register arg) {
 795   if (c_rarg0 != arg ) {
 796     masm->mov(c_rarg0, arg);
 797   }
 798 }
 799 
 800 static void pass_arg1(MacroAssembler* masm, Register arg) {
 801   if (c_rarg1 != arg ) {
 802     masm->mov(c_rarg1, arg);
 803   }
 804 }
 805 
 806 static void pass_arg2(MacroAssembler* masm, Register arg) {
 807   if (c_rarg2 != arg ) {
 808     masm->mov(c_rarg2, arg);
 809   }
 810 }
 811 
 812 static void pass_arg3(MacroAssembler* masm, Register arg) {
 813   if (c_rarg3 != arg ) {
 814     masm->mov(c_rarg3, arg);
 815   }
 816 }
 817 
 818 void MacroAssembler::stop(const char* msg) {
 819   address rip = pc();
 820   pusha(); // get regs on stack
 821   lea(c_rarg0, ExternalAddress((address) msg));
 822   lea(c_rarg1, InternalAddress(rip));
 823   movq(c_rarg2, rsp); // pass pointer to regs array
 824   andq(rsp, -16); // align stack as required by ABI
 825   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 826   hlt();
 827 }
 828 
 829 void MacroAssembler::warn(const char* msg) {
 830   push(rbp);
 831   movq(rbp, rsp);
 832   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 833   push_CPU_state();   // keeps alignment at 16 bytes
 834   lea(c_rarg0, ExternalAddress((address) msg));
 835   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 836   pop_CPU_state();
 837   mov(rsp, rbp);
 838   pop(rbp);
 839 }
 840 
 841 void MacroAssembler::print_state() {
 842   address rip = pc();
 843   pusha();            // get regs on stack
 844   push(rbp);
 845   movq(rbp, rsp);
 846   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 847   push_CPU_state();   // keeps alignment at 16 bytes
 848 
 849   lea(c_rarg0, InternalAddress(rip));
 850   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 851   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 852 
 853   pop_CPU_state();
 854   mov(rsp, rbp);
 855   pop(rbp);
 856   popa();
 857 }
 858 
 859 #ifndef PRODUCT
 860 extern "C" void findpc(intptr_t x);
 861 #endif
 862 
 863 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 864   // In order to get locks to work, we need to fake a in_VM state
 865   if (ShowMessageBoxOnError) {
 866     JavaThread* thread = JavaThread::current();
 867     JavaThreadState saved_state = thread->thread_state();
 868     thread->set_thread_state(_thread_in_vm);
 869 #ifndef PRODUCT
 870     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 871       ttyLocker ttyl;
 872       BytecodeCounter::print();
 873     }
 874 #endif
 875     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 876     // XXX correct this offset for amd64
 877     // This is the value of eip which points to where verify_oop will return.
 878     if (os::message_box(msg, "Execution stopped, print registers?")) {
 879       print_state64(pc, regs);
 880       BREAKPOINT;
 881       assert(false, "start up GDB");
 882     }
 883     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 884   } else {
 885     ttyLocker ttyl;
 886     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 887                     msg);
 888     assert(false, "DEBUG MESSAGE: %s", msg);
 889   }
 890 }
 891 
 892 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 893   ttyLocker ttyl;
 894   FlagSetting fs(Debugging, true);
 895   tty->print_cr("rip = 0x%016lx", pc);
 896 #ifndef PRODUCT
 897   tty->cr();
 898   findpc(pc);
 899   tty->cr();
 900 #endif
 901 #define PRINT_REG(rax, value) \
 902   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 903   PRINT_REG(rax, regs[15]);
 904   PRINT_REG(rbx, regs[12]);
 905   PRINT_REG(rcx, regs[14]);
 906   PRINT_REG(rdx, regs[13]);
 907   PRINT_REG(rdi, regs[8]);
 908   PRINT_REG(rsi, regs[9]);
 909   PRINT_REG(rbp, regs[10]);
 910   PRINT_REG(rsp, regs[11]);
 911   PRINT_REG(r8 , regs[7]);
 912   PRINT_REG(r9 , regs[6]);
 913   PRINT_REG(r10, regs[5]);
 914   PRINT_REG(r11, regs[4]);
 915   PRINT_REG(r12, regs[3]);
 916   PRINT_REG(r13, regs[2]);
 917   PRINT_REG(r14, regs[1]);
 918   PRINT_REG(r15, regs[0]);
 919 #undef PRINT_REG
 920   // Print some words near top of staack.
 921   int64_t* rsp = (int64_t*) regs[11];
 922   int64_t* dump_sp = rsp;
 923   for (int col1 = 0; col1 < 8; col1++) {
 924     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 925     os::print_location(tty, *dump_sp++);
 926   }
 927   for (int row = 0; row < 25; row++) {
 928     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 929     for (int col = 0; col < 4; col++) {
 930       tty->print(" 0x%016lx", *dump_sp++);
 931     }
 932     tty->cr();
 933   }
 934   // Print some instructions around pc:
 935   Disassembler::decode((address)pc-64, (address)pc);
 936   tty->print_cr("--------");
 937   Disassembler::decode((address)pc, (address)pc+32);
 938 }
 939 
 940 #endif // _LP64
 941 
 942 // Now versions that are common to 32/64 bit
 943 
 944 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 945   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 946 }
 947 
 948 void MacroAssembler::addptr(Register dst, Register src) {
 949   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 950 }
 951 
 952 void MacroAssembler::addptr(Address dst, Register src) {
 953   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 954 }
 955 
 956 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 957   if (reachable(src)) {
 958     Assembler::addsd(dst, as_Address(src));
 959   } else {
 960     lea(rscratch1, src);
 961     Assembler::addsd(dst, Address(rscratch1, 0));
 962   }
 963 }
 964 
 965 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 966   if (reachable(src)) {
 967     addss(dst, as_Address(src));
 968   } else {
 969     lea(rscratch1, src);
 970     addss(dst, Address(rscratch1, 0));
 971   }
 972 }
 973 
 974 void MacroAssembler::align(int modulus) {
 975   align(modulus, offset());
 976 }
 977 
 978 void MacroAssembler::align(int modulus, int target) {
 979   if (target % modulus != 0) {
 980     nop(modulus - (target % modulus));
 981   }
 982 }
 983 
 984 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 985   // Used in sign-masking with aligned address.
 986   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 987   if (reachable(src)) {
 988     Assembler::andpd(dst, as_Address(src));
 989   } else {
 990     lea(rscratch1, src);
 991     Assembler::andpd(dst, Address(rscratch1, 0));
 992   }
 993 }
 994 
 995 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
 996   // Used in sign-masking with aligned address.
 997   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 998   if (reachable(src)) {
 999     Assembler::andps(dst, as_Address(src));
1000   } else {
1001     lea(rscratch1, src);
1002     Assembler::andps(dst, Address(rscratch1, 0));
1003   }
1004 }
1005 
1006 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1007   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1008 }
1009 
1010 void MacroAssembler::atomic_incl(Address counter_addr) {
1011   if (os::is_MP())
1012     lock();
1013   incrementl(counter_addr);
1014 }
1015 
1016 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1017   if (reachable(counter_addr)) {
1018     atomic_incl(as_Address(counter_addr));
1019   } else {
1020     lea(scr, counter_addr);
1021     atomic_incl(Address(scr, 0));
1022   }
1023 }
1024 
1025 #ifdef _LP64
1026 void MacroAssembler::atomic_incq(Address counter_addr) {
1027   if (os::is_MP())
1028     lock();
1029   incrementq(counter_addr);
1030 }
1031 
1032 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1033   if (reachable(counter_addr)) {
1034     atomic_incq(as_Address(counter_addr));
1035   } else {
1036     lea(scr, counter_addr);
1037     atomic_incq(Address(scr, 0));
1038   }
1039 }
1040 #endif
1041 
1042 // Writes to stack successive pages until offset reached to check for
1043 // stack overflow + shadow pages.  This clobbers tmp.
1044 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1045   movptr(tmp, rsp);
1046   // Bang stack for total size given plus shadow page size.
1047   // Bang one page at a time because large size can bang beyond yellow and
1048   // red zones.
1049   Label loop;
1050   bind(loop);
1051   movl(Address(tmp, (-os::vm_page_size())), size );
1052   subptr(tmp, os::vm_page_size());
1053   subl(size, os::vm_page_size());
1054   jcc(Assembler::greater, loop);
1055 
1056   // Bang down shadow pages too.
1057   // At this point, (tmp-0) is the last address touched, so don't
1058   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1059   // was post-decremented.)  Skip this address by starting at i=1, and
1060   // touch a few more pages below.  N.B.  It is important to touch all
1061   // the way down to and including i=StackShadowPages.
1062   for (int i = 1; i < StackShadowPages; i++) {
1063     // this could be any sized move but this is can be a debugging crumb
1064     // so the bigger the better.
1065     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1066   }
1067 }
1068 
1069 int MacroAssembler::biased_locking_enter(Register lock_reg,
1070                                          Register obj_reg,
1071                                          Register swap_reg,
1072                                          Register tmp_reg,
1073                                          bool swap_reg_contains_mark,
1074                                          Label& done,
1075                                          Label* slow_case,
1076                                          BiasedLockingCounters* counters) {
1077   assert(UseBiasedLocking, "why call this otherwise?");
1078   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1079   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1080   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1081   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1082   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1083   Address saved_mark_addr(lock_reg, 0);
1084 
1085   if (PrintBiasedLockingStatistics && counters == NULL) {
1086     counters = BiasedLocking::counters();
1087   }
1088   // Biased locking
1089   // See whether the lock is currently biased toward our thread and
1090   // whether the epoch is still valid
1091   // Note that the runtime guarantees sufficient alignment of JavaThread
1092   // pointers to allow age to be placed into low bits
1093   // First check to see whether biasing is even enabled for this object
1094   Label cas_label;
1095   int null_check_offset = -1;
1096   if (!swap_reg_contains_mark) {
1097     null_check_offset = offset();
1098     movptr(swap_reg, mark_addr);
1099   }
1100   movptr(tmp_reg, swap_reg);
1101   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1102   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1103   jcc(Assembler::notEqual, cas_label);
1104   // The bias pattern is present in the object's header. Need to check
1105   // whether the bias owner and the epoch are both still current.
1106 #ifndef _LP64
1107   // Note that because there is no current thread register on x86_32 we
1108   // need to store off the mark word we read out of the object to
1109   // avoid reloading it and needing to recheck invariants below. This
1110   // store is unfortunate but it makes the overall code shorter and
1111   // simpler.
1112   movptr(saved_mark_addr, swap_reg);
1113 #endif
1114   if (swap_reg_contains_mark) {
1115     null_check_offset = offset();
1116   }
1117   load_prototype_header(tmp_reg, obj_reg);
1118 #ifdef _LP64
1119   orptr(tmp_reg, r15_thread);
1120   xorptr(tmp_reg, swap_reg);
1121   Register header_reg = tmp_reg;
1122 #else
1123   xorptr(tmp_reg, swap_reg);
1124   get_thread(swap_reg);
1125   xorptr(swap_reg, tmp_reg);
1126   Register header_reg = swap_reg;
1127 #endif
1128   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1129   if (counters != NULL) {
1130     cond_inc32(Assembler::zero,
1131                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1132   }
1133   jcc(Assembler::equal, done);
1134 
1135   Label try_revoke_bias;
1136   Label try_rebias;
1137 
1138   // At this point we know that the header has the bias pattern and
1139   // that we are not the bias owner in the current epoch. We need to
1140   // figure out more details about the state of the header in order to
1141   // know what operations can be legally performed on the object's
1142   // header.
1143 
1144   // If the low three bits in the xor result aren't clear, that means
1145   // the prototype header is no longer biased and we have to revoke
1146   // the bias on this object.
1147   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1148   jccb(Assembler::notZero, try_revoke_bias);
1149 
1150   // Biasing is still enabled for this data type. See whether the
1151   // epoch of the current bias is still valid, meaning that the epoch
1152   // bits of the mark word are equal to the epoch bits of the
1153   // prototype header. (Note that the prototype header's epoch bits
1154   // only change at a safepoint.) If not, attempt to rebias the object
1155   // toward the current thread. Note that we must be absolutely sure
1156   // that the current epoch is invalid in order to do this because
1157   // otherwise the manipulations it performs on the mark word are
1158   // illegal.
1159   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1160   jccb(Assembler::notZero, try_rebias);
1161 
1162   // The epoch of the current bias is still valid but we know nothing
1163   // about the owner; it might be set or it might be clear. Try to
1164   // acquire the bias of the object using an atomic operation. If this
1165   // fails we will go in to the runtime to revoke the object's bias.
1166   // Note that we first construct the presumed unbiased header so we
1167   // don't accidentally blow away another thread's valid bias.
1168   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1169   andptr(swap_reg,
1170          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1171 #ifdef _LP64
1172   movptr(tmp_reg, swap_reg);
1173   orptr(tmp_reg, r15_thread);
1174 #else
1175   get_thread(tmp_reg);
1176   orptr(tmp_reg, swap_reg);
1177 #endif
1178   if (os::is_MP()) {
1179     lock();
1180   }
1181   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1182   // If the biasing toward our thread failed, this means that
1183   // another thread succeeded in biasing it toward itself and we
1184   // need to revoke that bias. The revocation will occur in the
1185   // interpreter runtime in the slow case.
1186   if (counters != NULL) {
1187     cond_inc32(Assembler::zero,
1188                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1189   }
1190   if (slow_case != NULL) {
1191     jcc(Assembler::notZero, *slow_case);
1192   }
1193   jmp(done);
1194 
1195   bind(try_rebias);
1196   // At this point we know the epoch has expired, meaning that the
1197   // current "bias owner", if any, is actually invalid. Under these
1198   // circumstances _only_, we are allowed to use the current header's
1199   // value as the comparison value when doing the cas to acquire the
1200   // bias in the current epoch. In other words, we allow transfer of
1201   // the bias from one thread to another directly in this situation.
1202   //
1203   // FIXME: due to a lack of registers we currently blow away the age
1204   // bits in this situation. Should attempt to preserve them.
1205   load_prototype_header(tmp_reg, obj_reg);
1206 #ifdef _LP64
1207   orptr(tmp_reg, r15_thread);
1208 #else
1209   get_thread(swap_reg);
1210   orptr(tmp_reg, swap_reg);
1211   movptr(swap_reg, saved_mark_addr);
1212 #endif
1213   if (os::is_MP()) {
1214     lock();
1215   }
1216   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1217   // If the biasing toward our thread failed, then another thread
1218   // succeeded in biasing it toward itself and we need to revoke that
1219   // bias. The revocation will occur in the runtime in the slow case.
1220   if (counters != NULL) {
1221     cond_inc32(Assembler::zero,
1222                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1223   }
1224   if (slow_case != NULL) {
1225     jcc(Assembler::notZero, *slow_case);
1226   }
1227   jmp(done);
1228 
1229   bind(try_revoke_bias);
1230   // The prototype mark in the klass doesn't have the bias bit set any
1231   // more, indicating that objects of this data type are not supposed
1232   // to be biased any more. We are going to try to reset the mark of
1233   // this object to the prototype value and fall through to the
1234   // CAS-based locking scheme. Note that if our CAS fails, it means
1235   // that another thread raced us for the privilege of revoking the
1236   // bias of this particular object, so it's okay to continue in the
1237   // normal locking code.
1238   //
1239   // FIXME: due to a lack of registers we currently blow away the age
1240   // bits in this situation. Should attempt to preserve them.
1241   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1242   load_prototype_header(tmp_reg, obj_reg);
1243   if (os::is_MP()) {
1244     lock();
1245   }
1246   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1247   // Fall through to the normal CAS-based lock, because no matter what
1248   // the result of the above CAS, some thread must have succeeded in
1249   // removing the bias bit from the object's header.
1250   if (counters != NULL) {
1251     cond_inc32(Assembler::zero,
1252                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1253   }
1254 
1255   bind(cas_label);
1256 
1257   return null_check_offset;
1258 }
1259 
1260 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1261   assert(UseBiasedLocking, "why call this otherwise?");
1262 
1263   // Check for biased locking unlock case, which is a no-op
1264   // Note: we do not have to check the thread ID for two reasons.
1265   // First, the interpreter checks for IllegalMonitorStateException at
1266   // a higher level. Second, if the bias was revoked while we held the
1267   // lock, the object could not be rebiased toward another thread, so
1268   // the bias bit would be clear.
1269   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1270   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1271   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1272   jcc(Assembler::equal, done);
1273 }
1274 
1275 #ifdef COMPILER2
1276 
1277 #if INCLUDE_RTM_OPT
1278 
1279 // Update rtm_counters based on abort status
1280 // input: abort_status
1281 //        rtm_counters (RTMLockingCounters*)
1282 // flags are killed
1283 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1284 
1285   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1286   if (PrintPreciseRTMLockingStatistics) {
1287     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1288       Label check_abort;
1289       testl(abort_status, (1<<i));
1290       jccb(Assembler::equal, check_abort);
1291       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1292       bind(check_abort);
1293     }
1294   }
1295 }
1296 
1297 // Branch if (random & (count-1) != 0), count is 2^n
1298 // tmp, scr and flags are killed
1299 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1300   assert(tmp == rax, "");
1301   assert(scr == rdx, "");
1302   rdtsc(); // modifies EDX:EAX
1303   andptr(tmp, count-1);
1304   jccb(Assembler::notZero, brLabel);
1305 }
1306 
1307 // Perform abort ratio calculation, set no_rtm bit if high ratio
1308 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1309 // tmpReg, rtm_counters_Reg and flags are killed
1310 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1311                                                  Register rtm_counters_Reg,
1312                                                  RTMLockingCounters* rtm_counters,
1313                                                  Metadata* method_data) {
1314   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1315 
1316   if (RTMLockingCalculationDelay > 0) {
1317     // Delay calculation
1318     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1319     testptr(tmpReg, tmpReg);
1320     jccb(Assembler::equal, L_done);
1321   }
1322   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1323   //   Aborted transactions = abort_count * 100
1324   //   All transactions = total_count *  RTMTotalCountIncrRate
1325   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1326 
1327   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1328   cmpptr(tmpReg, RTMAbortThreshold);
1329   jccb(Assembler::below, L_check_always_rtm2);
1330   imulptr(tmpReg, tmpReg, 100);
1331 
1332   Register scrReg = rtm_counters_Reg;
1333   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1334   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1335   imulptr(scrReg, scrReg, RTMAbortRatio);
1336   cmpptr(tmpReg, scrReg);
1337   jccb(Assembler::below, L_check_always_rtm1);
1338   if (method_data != NULL) {
1339     // set rtm_state to "no rtm" in MDO
1340     mov_metadata(tmpReg, method_data);
1341     if (os::is_MP()) {
1342       lock();
1343     }
1344     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1345   }
1346   jmpb(L_done);
1347   bind(L_check_always_rtm1);
1348   // Reload RTMLockingCounters* address
1349   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1350   bind(L_check_always_rtm2);
1351   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1352   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1353   jccb(Assembler::below, L_done);
1354   if (method_data != NULL) {
1355     // set rtm_state to "always rtm" in MDO
1356     mov_metadata(tmpReg, method_data);
1357     if (os::is_MP()) {
1358       lock();
1359     }
1360     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1361   }
1362   bind(L_done);
1363 }
1364 
1365 // Update counters and perform abort ratio calculation
1366 // input:  abort_status_Reg
1367 // rtm_counters_Reg, flags are killed
1368 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1369                                    Register rtm_counters_Reg,
1370                                    RTMLockingCounters* rtm_counters,
1371                                    Metadata* method_data,
1372                                    bool profile_rtm) {
1373 
1374   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1375   // update rtm counters based on rax value at abort
1376   // reads abort_status_Reg, updates flags
1377   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1378   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1379   if (profile_rtm) {
1380     // Save abort status because abort_status_Reg is used by following code.
1381     if (RTMRetryCount > 0) {
1382       push(abort_status_Reg);
1383     }
1384     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1385     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1386     // restore abort status
1387     if (RTMRetryCount > 0) {
1388       pop(abort_status_Reg);
1389     }
1390   }
1391 }
1392 
1393 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1394 // inputs: retry_count_Reg
1395 //       : abort_status_Reg
1396 // output: retry_count_Reg decremented by 1
1397 // flags are killed
1398 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1399   Label doneRetry;
1400   assert(abort_status_Reg == rax, "");
1401   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1402   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1403   // if reason is in 0x6 and retry count != 0 then retry
1404   andptr(abort_status_Reg, 0x6);
1405   jccb(Assembler::zero, doneRetry);
1406   testl(retry_count_Reg, retry_count_Reg);
1407   jccb(Assembler::zero, doneRetry);
1408   pause();
1409   decrementl(retry_count_Reg);
1410   jmp(retryLabel);
1411   bind(doneRetry);
1412 }
1413 
1414 // Spin and retry if lock is busy,
1415 // inputs: box_Reg (monitor address)
1416 //       : retry_count_Reg
1417 // output: retry_count_Reg decremented by 1
1418 //       : clear z flag if retry count exceeded
1419 // tmp_Reg, scr_Reg, flags are killed
1420 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1421                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1422   Label SpinLoop, SpinExit, doneRetry;
1423   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1424 
1425   testl(retry_count_Reg, retry_count_Reg);
1426   jccb(Assembler::zero, doneRetry);
1427   decrementl(retry_count_Reg);
1428   movptr(scr_Reg, RTMSpinLoopCount);
1429 
1430   bind(SpinLoop);
1431   pause();
1432   decrementl(scr_Reg);
1433   jccb(Assembler::lessEqual, SpinExit);
1434   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1435   testptr(tmp_Reg, tmp_Reg);
1436   jccb(Assembler::notZero, SpinLoop);
1437 
1438   bind(SpinExit);
1439   jmp(retryLabel);
1440   bind(doneRetry);
1441   incrementl(retry_count_Reg); // clear z flag
1442 }
1443 
1444 // Use RTM for normal stack locks
1445 // Input: objReg (object to lock)
1446 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1447                                        Register retry_on_abort_count_Reg,
1448                                        RTMLockingCounters* stack_rtm_counters,
1449                                        Metadata* method_data, bool profile_rtm,
1450                                        Label& DONE_LABEL, Label& IsInflated) {
1451   assert(UseRTMForStackLocks, "why call this otherwise?");
1452   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1453   assert(tmpReg == rax, "");
1454   assert(scrReg == rdx, "");
1455   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1456 
1457   if (RTMRetryCount > 0) {
1458     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1459     bind(L_rtm_retry);
1460   }
1461   movptr(tmpReg, Address(objReg, 0));
1462   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1463   jcc(Assembler::notZero, IsInflated);
1464 
1465   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1466     Label L_noincrement;
1467     if (RTMTotalCountIncrRate > 1) {
1468       // tmpReg, scrReg and flags are killed
1469       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1470     }
1471     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1472     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1473     bind(L_noincrement);
1474   }
1475   xbegin(L_on_abort);
1476   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1477   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1478   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1479   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1480 
1481   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1482   if (UseRTMXendForLockBusy) {
1483     xend();
1484     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1485     jmp(L_decrement_retry);
1486   }
1487   else {
1488     xabort(0);
1489   }
1490   bind(L_on_abort);
1491   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1492     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1493   }
1494   bind(L_decrement_retry);
1495   if (RTMRetryCount > 0) {
1496     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1497     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1498   }
1499 }
1500 
1501 // Use RTM for inflating locks
1502 // inputs: objReg (object to lock)
1503 //         boxReg (on-stack box address (displaced header location) - KILLED)
1504 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1505 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1506                                           Register scrReg, Register retry_on_busy_count_Reg,
1507                                           Register retry_on_abort_count_Reg,
1508                                           RTMLockingCounters* rtm_counters,
1509                                           Metadata* method_data, bool profile_rtm,
1510                                           Label& DONE_LABEL) {
1511   assert(UseRTMLocking, "why call this otherwise?");
1512   assert(tmpReg == rax, "");
1513   assert(scrReg == rdx, "");
1514   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1515   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1516 
1517   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1518   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1519   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1520 
1521   if (RTMRetryCount > 0) {
1522     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1523     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1524     bind(L_rtm_retry);
1525   }
1526   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1527     Label L_noincrement;
1528     if (RTMTotalCountIncrRate > 1) {
1529       // tmpReg, scrReg and flags are killed
1530       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1531     }
1532     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1533     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1534     bind(L_noincrement);
1535   }
1536   xbegin(L_on_abort);
1537   movptr(tmpReg, Address(objReg, 0));
1538   movptr(tmpReg, Address(tmpReg, owner_offset));
1539   testptr(tmpReg, tmpReg);
1540   jcc(Assembler::zero, DONE_LABEL);
1541   if (UseRTMXendForLockBusy) {
1542     xend();
1543     jmp(L_decrement_retry);
1544   }
1545   else {
1546     xabort(0);
1547   }
1548   bind(L_on_abort);
1549   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1550   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1551     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1552   }
1553   if (RTMRetryCount > 0) {
1554     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1555     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1556   }
1557 
1558   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1559   testptr(tmpReg, tmpReg) ;
1560   jccb(Assembler::notZero, L_decrement_retry) ;
1561 
1562   // Appears unlocked - try to swing _owner from null to non-null.
1563   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1564 #ifdef _LP64
1565   Register threadReg = r15_thread;
1566 #else
1567   get_thread(scrReg);
1568   Register threadReg = scrReg;
1569 #endif
1570   if (os::is_MP()) {
1571     lock();
1572   }
1573   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1574 
1575   if (RTMRetryCount > 0) {
1576     // success done else retry
1577     jccb(Assembler::equal, DONE_LABEL) ;
1578     bind(L_decrement_retry);
1579     // Spin and retry if lock is busy.
1580     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1581   }
1582   else {
1583     bind(L_decrement_retry);
1584   }
1585 }
1586 
1587 #endif //  INCLUDE_RTM_OPT
1588 
1589 // Fast_Lock and Fast_Unlock used by C2
1590 
1591 // Because the transitions from emitted code to the runtime
1592 // monitorenter/exit helper stubs are so slow it's critical that
1593 // we inline both the stack-locking fast-path and the inflated fast path.
1594 //
1595 // See also: cmpFastLock and cmpFastUnlock.
1596 //
1597 // What follows is a specialized inline transliteration of the code
1598 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1599 // another option would be to emit TrySlowEnter and TrySlowExit methods
1600 // at startup-time.  These methods would accept arguments as
1601 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1602 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1603 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1604 // In practice, however, the # of lock sites is bounded and is usually small.
1605 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1606 // if the processor uses simple bimodal branch predictors keyed by EIP
1607 // Since the helper routines would be called from multiple synchronization
1608 // sites.
1609 //
1610 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1611 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1612 // to those specialized methods.  That'd give us a mostly platform-independent
1613 // implementation that the JITs could optimize and inline at their pleasure.
1614 // Done correctly, the only time we'd need to cross to native could would be
1615 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1616 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1617 // (b) explicit barriers or fence operations.
1618 //
1619 // TODO:
1620 //
1621 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1622 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1623 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1624 //    the lock operators would typically be faster than reifying Self.
1625 //
1626 // *  Ideally I'd define the primitives as:
1627 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1628 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1629 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1630 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1631 //    Furthermore the register assignments are overconstrained, possibly resulting in
1632 //    sub-optimal code near the synchronization site.
1633 //
1634 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1635 //    Alternately, use a better sp-proximity test.
1636 //
1637 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1638 //    Either one is sufficient to uniquely identify a thread.
1639 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1640 //
1641 // *  Intrinsify notify() and notifyAll() for the common cases where the
1642 //    object is locked by the calling thread but the waitlist is empty.
1643 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1644 //
1645 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1646 //    But beware of excessive branch density on AMD Opterons.
1647 //
1648 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1649 //    or failure of the fast-path.  If the fast-path fails then we pass
1650 //    control to the slow-path, typically in C.  In Fast_Lock and
1651 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1652 //    will emit a conditional branch immediately after the node.
1653 //    So we have branches to branches and lots of ICC.ZF games.
1654 //    Instead, it might be better to have C2 pass a "FailureLabel"
1655 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1656 //    will drop through the node.  ICC.ZF is undefined at exit.
1657 //    In the case of failure, the node will branch directly to the
1658 //    FailureLabel
1659 
1660 
1661 // obj: object to lock
1662 // box: on-stack box address (displaced header location) - KILLED
1663 // rax,: tmp -- KILLED
1664 // scr: tmp -- KILLED
1665 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1666                                Register scrReg, Register cx1Reg, Register cx2Reg,
1667                                BiasedLockingCounters* counters,
1668                                RTMLockingCounters* rtm_counters,
1669                                RTMLockingCounters* stack_rtm_counters,
1670                                Metadata* method_data,
1671                                bool use_rtm, bool profile_rtm) {
1672   // Ensure the register assignents are disjoint
1673   assert(tmpReg == rax, "");
1674 
1675   if (use_rtm) {
1676     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1677   } else {
1678     assert(cx1Reg == noreg, "");
1679     assert(cx2Reg == noreg, "");
1680     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1681   }
1682 
1683   if (counters != NULL) {
1684     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1685   }
1686   if (EmitSync & 1) {
1687       // set box->dhw = markOopDesc::unused_mark()
1688       // Force all sync thru slow-path: slow_enter() and slow_exit()
1689       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1690       cmpptr (rsp, (int32_t)NULL_WORD);
1691   } else {
1692     // Possible cases that we'll encounter in fast_lock
1693     // ------------------------------------------------
1694     // * Inflated
1695     //    -- unlocked
1696     //    -- Locked
1697     //       = by self
1698     //       = by other
1699     // * biased
1700     //    -- by Self
1701     //    -- by other
1702     // * neutral
1703     // * stack-locked
1704     //    -- by self
1705     //       = sp-proximity test hits
1706     //       = sp-proximity test generates false-negative
1707     //    -- by other
1708     //
1709 
1710     Label IsInflated, DONE_LABEL;
1711 
1712     // it's stack-locked, biased or neutral
1713     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1714     // order to reduce the number of conditional branches in the most common cases.
1715     // Beware -- there's a subtle invariant that fetch of the markword
1716     // at [FETCH], below, will never observe a biased encoding (*101b).
1717     // If this invariant is not held we risk exclusion (safety) failure.
1718     if (UseBiasedLocking && !UseOptoBiasInlining) {
1719       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1720     }
1721 
1722 #if INCLUDE_RTM_OPT
1723     if (UseRTMForStackLocks && use_rtm) {
1724       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1725                         stack_rtm_counters, method_data, profile_rtm,
1726                         DONE_LABEL, IsInflated);
1727     }
1728 #endif // INCLUDE_RTM_OPT
1729 
1730     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1731     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1732     jccb(Assembler::notZero, IsInflated);
1733 
1734     // Attempt stack-locking ...
1735     orptr (tmpReg, markOopDesc::unlocked_value);
1736     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1737     if (os::is_MP()) {
1738       lock();
1739     }
1740     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1741     if (counters != NULL) {
1742       cond_inc32(Assembler::equal,
1743                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1744     }
1745     jcc(Assembler::equal, DONE_LABEL);           // Success
1746 
1747     // Recursive locking.
1748     // The object is stack-locked: markword contains stack pointer to BasicLock.
1749     // Locked by current thread if difference with current SP is less than one page.
1750     subptr(tmpReg, rsp);
1751     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1752     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1753     movptr(Address(boxReg, 0), tmpReg);
1754     if (counters != NULL) {
1755       cond_inc32(Assembler::equal,
1756                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1757     }
1758     jmp(DONE_LABEL);
1759 
1760     bind(IsInflated);
1761     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1762 
1763 #if INCLUDE_RTM_OPT
1764     // Use the same RTM locking code in 32- and 64-bit VM.
1765     if (use_rtm) {
1766       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1767                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1768     } else {
1769 #endif // INCLUDE_RTM_OPT
1770 
1771 #ifndef _LP64
1772     // The object is inflated.
1773 
1774     // boxReg refers to the on-stack BasicLock in the current frame.
1775     // We'd like to write:
1776     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1777     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1778     // additional latency as we have another ST in the store buffer that must drain.
1779 
1780     if (EmitSync & 8192) {
1781        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1782        get_thread (scrReg);
1783        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1784        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1785        if (os::is_MP()) {
1786          lock();
1787        }
1788        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1789     } else
1790     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1791        // register juggle because we need tmpReg for cmpxchgptr below
1792        movptr(scrReg, boxReg);
1793        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1794 
1795        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1796        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1797           // prefetchw [eax + Offset(_owner)-2]
1798           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1799        }
1800 
1801        if ((EmitSync & 64) == 0) {
1802          // Optimistic form: consider XORL tmpReg,tmpReg
1803          movptr(tmpReg, NULL_WORD);
1804        } else {
1805          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1806          // Test-And-CAS instead of CAS
1807          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1808          testptr(tmpReg, tmpReg);                   // Locked ?
1809          jccb  (Assembler::notZero, DONE_LABEL);
1810        }
1811 
1812        // Appears unlocked - try to swing _owner from null to non-null.
1813        // Ideally, I'd manifest "Self" with get_thread and then attempt
1814        // to CAS the register containing Self into m->Owner.
1815        // But we don't have enough registers, so instead we can either try to CAS
1816        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1817        // we later store "Self" into m->Owner.  Transiently storing a stack address
1818        // (rsp or the address of the box) into  m->owner is harmless.
1819        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1820        if (os::is_MP()) {
1821          lock();
1822        }
1823        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1824        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1825        // If we weren't able to swing _owner from NULL to the BasicLock
1826        // then take the slow path.
1827        jccb  (Assembler::notZero, DONE_LABEL);
1828        // update _owner from BasicLock to thread
1829        get_thread (scrReg);                    // beware: clobbers ICCs
1830        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1831        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1832 
1833        // If the CAS fails we can either retry or pass control to the slow-path.
1834        // We use the latter tactic.
1835        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1836        // If the CAS was successful ...
1837        //   Self has acquired the lock
1838        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1839        // Intentional fall-through into DONE_LABEL ...
1840     } else {
1841        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1842        movptr(boxReg, tmpReg);
1843 
1844        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1845        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1846           // prefetchw [eax + Offset(_owner)-2]
1847           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1848        }
1849 
1850        if ((EmitSync & 64) == 0) {
1851          // Optimistic form
1852          xorptr  (tmpReg, tmpReg);
1853        } else {
1854          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1855          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1856          testptr(tmpReg, tmpReg);                   // Locked ?
1857          jccb  (Assembler::notZero, DONE_LABEL);
1858        }
1859 
1860        // Appears unlocked - try to swing _owner from null to non-null.
1861        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1862        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1863        get_thread (scrReg);
1864        if (os::is_MP()) {
1865          lock();
1866        }
1867        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1868 
1869        // If the CAS fails we can either retry or pass control to the slow-path.
1870        // We use the latter tactic.
1871        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1872        // If the CAS was successful ...
1873        //   Self has acquired the lock
1874        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1875        // Intentional fall-through into DONE_LABEL ...
1876     }
1877 #else // _LP64
1878     // It's inflated
1879     movq(scrReg, tmpReg);
1880     xorq(tmpReg, tmpReg);
1881 
1882     if (os::is_MP()) {
1883       lock();
1884     }
1885     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1886     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1887     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1888     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1889     // Intentional fall-through into DONE_LABEL ...
1890     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1891 #endif // _LP64
1892 #if INCLUDE_RTM_OPT
1893     } // use_rtm()
1894 #endif
1895     // DONE_LABEL is a hot target - we'd really like to place it at the
1896     // start of cache line by padding with NOPs.
1897     // See the AMD and Intel software optimization manuals for the
1898     // most efficient "long" NOP encodings.
1899     // Unfortunately none of our alignment mechanisms suffice.
1900     bind(DONE_LABEL);
1901 
1902     // At DONE_LABEL the icc ZFlag is set as follows ...
1903     // Fast_Unlock uses the same protocol.
1904     // ZFlag == 1 -> Success
1905     // ZFlag == 0 -> Failure - force control through the slow-path
1906   }
1907 }
1908 
1909 // obj: object to unlock
1910 // box: box address (displaced header location), killed.  Must be EAX.
1911 // tmp: killed, cannot be obj nor box.
1912 //
1913 // Some commentary on balanced locking:
1914 //
1915 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1916 // Methods that don't have provably balanced locking are forced to run in the
1917 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1918 // The interpreter provides two properties:
1919 // I1:  At return-time the interpreter automatically and quietly unlocks any
1920 //      objects acquired the current activation (frame).  Recall that the
1921 //      interpreter maintains an on-stack list of locks currently held by
1922 //      a frame.
1923 // I2:  If a method attempts to unlock an object that is not held by the
1924 //      the frame the interpreter throws IMSX.
1925 //
1926 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1927 // B() doesn't have provably balanced locking so it runs in the interpreter.
1928 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1929 // is still locked by A().
1930 //
1931 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1932 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1933 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1934 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1935 // Arguably given that the spec legislates the JNI case as undefined our implementation
1936 // could reasonably *avoid* checking owner in Fast_Unlock().
1937 // In the interest of performance we elide m->Owner==Self check in unlock.
1938 // A perfectly viable alternative is to elide the owner check except when
1939 // Xcheck:jni is enabled.
1940 
1941 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1942   assert(boxReg == rax, "");
1943   assert_different_registers(objReg, boxReg, tmpReg);
1944 
1945   if (EmitSync & 4) {
1946     // Disable - inhibit all inlining.  Force control through the slow-path
1947     cmpptr (rsp, 0);
1948   } else {
1949     Label DONE_LABEL, Stacked, CheckSucc;
1950 
1951     // Critically, the biased locking test must have precedence over
1952     // and appear before the (box->dhw == 0) recursive stack-lock test.
1953     if (UseBiasedLocking && !UseOptoBiasInlining) {
1954        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1955     }
1956 
1957 #if INCLUDE_RTM_OPT
1958     if (UseRTMForStackLocks && use_rtm) {
1959       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1960       Label L_regular_unlock;
1961       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1962       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1963       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1964       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1965       xend();                                       // otherwise end...
1966       jmp(DONE_LABEL);                              // ... and we're done
1967       bind(L_regular_unlock);
1968     }
1969 #endif
1970 
1971     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1972     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1973     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
1974     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1975     jccb  (Assembler::zero, Stacked);
1976 
1977     // It's inflated.
1978 #if INCLUDE_RTM_OPT
1979     if (use_rtm) {
1980       Label L_regular_inflated_unlock;
1981       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1982       movptr(boxReg, Address(tmpReg, owner_offset));
1983       testptr(boxReg, boxReg);
1984       jccb(Assembler::notZero, L_regular_inflated_unlock);
1985       xend();
1986       jmpb(DONE_LABEL);
1987       bind(L_regular_inflated_unlock);
1988     }
1989 #endif
1990 
1991     // Despite our balanced locking property we still check that m->_owner == Self
1992     // as java routines or native JNI code called by this thread might
1993     // have released the lock.
1994     // Refer to the comments in synchronizer.cpp for how we might encode extra
1995     // state in _succ so we can avoid fetching EntryList|cxq.
1996     //
1997     // I'd like to add more cases in fast_lock() and fast_unlock() --
1998     // such as recursive enter and exit -- but we have to be wary of
1999     // I$ bloat, T$ effects and BP$ effects.
2000     //
2001     // If there's no contention try a 1-0 exit.  That is, exit without
2002     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2003     // we detect and recover from the race that the 1-0 exit admits.
2004     //
2005     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2006     // before it STs null into _owner, releasing the lock.  Updates
2007     // to data protected by the critical section must be visible before
2008     // we drop the lock (and thus before any other thread could acquire
2009     // the lock and observe the fields protected by the lock).
2010     // IA32's memory-model is SPO, so STs are ordered with respect to
2011     // each other and there's no need for an explicit barrier (fence).
2012     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2013 #ifndef _LP64
2014     get_thread (boxReg);
2015     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2016       // prefetchw [ebx + Offset(_owner)-2]
2017       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2018     }
2019 
2020     // Note that we could employ various encoding schemes to reduce
2021     // the number of loads below (currently 4) to just 2 or 3.
2022     // Refer to the comments in synchronizer.cpp.
2023     // In practice the chain of fetches doesn't seem to impact performance, however.
2024     xorptr(boxReg, boxReg);
2025     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2026        // Attempt to reduce branch density - AMD's branch predictor.
2027        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2028        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2029        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2030        jccb  (Assembler::notZero, DONE_LABEL);
2031        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2032        jmpb  (DONE_LABEL);
2033     } else {
2034        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2035        jccb  (Assembler::notZero, DONE_LABEL);
2036        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2037        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2038        jccb  (Assembler::notZero, CheckSucc);
2039        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2040        jmpb  (DONE_LABEL);
2041     }
2042 
2043     // The Following code fragment (EmitSync & 65536) improves the performance of
2044     // contended applications and contended synchronization microbenchmarks.
2045     // Unfortunately the emission of the code - even though not executed - causes regressions
2046     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2047     // with an equal number of never-executed NOPs results in the same regression.
2048     // We leave it off by default.
2049 
2050     if ((EmitSync & 65536) != 0) {
2051        Label LSuccess, LGoSlowPath ;
2052 
2053        bind  (CheckSucc);
2054 
2055        // Optional pre-test ... it's safe to elide this
2056        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2057        jccb(Assembler::zero, LGoSlowPath);
2058 
2059        // We have a classic Dekker-style idiom:
2060        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2061        // There are a number of ways to implement the barrier:
2062        // (1) lock:andl &m->_owner, 0
2063        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2064        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2065        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2066        // (2) If supported, an explicit MFENCE is appealing.
2067        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2068        //     particularly if the write-buffer is full as might be the case if
2069        //     if stores closely precede the fence or fence-equivalent instruction.
2070        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2071        //     as the situation has changed with Nehalem and Shanghai.
2072        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2073        //     The $lines underlying the top-of-stack should be in M-state.
2074        //     The locked add instruction is serializing, of course.
2075        // (4) Use xchg, which is serializing
2076        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2077        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2078        //     The integer condition codes will tell us if succ was 0.
2079        //     Since _succ and _owner should reside in the same $line and
2080        //     we just stored into _owner, it's likely that the $line
2081        //     remains in M-state for the lock:orl.
2082        //
2083        // We currently use (3), although it's likely that switching to (2)
2084        // is correct for the future.
2085 
2086        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2087        if (os::is_MP()) {
2088          lock(); addptr(Address(rsp, 0), 0);
2089        }
2090        // Ratify _succ remains non-null
2091        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2092        jccb  (Assembler::notZero, LSuccess);
2093 
2094        xorptr(boxReg, boxReg);                  // box is really EAX
2095        if (os::is_MP()) { lock(); }
2096        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2097        // There's no successor so we tried to regrab the lock with the
2098        // placeholder value. If that didn't work, then another thread
2099        // grabbed the lock so we're done (and exit was a success).
2100        jccb  (Assembler::notEqual, LSuccess);
2101        // Since we're low on registers we installed rsp as a placeholding in _owner.
2102        // Now install Self over rsp.  This is safe as we're transitioning from
2103        // non-null to non=null
2104        get_thread (boxReg);
2105        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2106        // Intentional fall-through into LGoSlowPath ...
2107 
2108        bind  (LGoSlowPath);
2109        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2110        jmpb  (DONE_LABEL);
2111 
2112        bind  (LSuccess);
2113        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2114        jmpb  (DONE_LABEL);
2115     }
2116 
2117     bind (Stacked);
2118     // It's not inflated and it's not recursively stack-locked and it's not biased.
2119     // It must be stack-locked.
2120     // Try to reset the header to displaced header.
2121     // The "box" value on the stack is stable, so we can reload
2122     // and be assured we observe the same value as above.
2123     movptr(tmpReg, Address(boxReg, 0));
2124     if (os::is_MP()) {
2125       lock();
2126     }
2127     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2128     // Intention fall-thru into DONE_LABEL
2129 
2130     // DONE_LABEL is a hot target - we'd really like to place it at the
2131     // start of cache line by padding with NOPs.
2132     // See the AMD and Intel software optimization manuals for the
2133     // most efficient "long" NOP encodings.
2134     // Unfortunately none of our alignment mechanisms suffice.
2135     if ((EmitSync & 65536) == 0) {
2136        bind (CheckSucc);
2137     }
2138 #else // _LP64
2139     // It's inflated
2140     if (EmitSync & 1024) {
2141       // Emit code to check that _owner == Self
2142       // We could fold the _owner test into subsequent code more efficiently
2143       // than using a stand-alone check, but since _owner checking is off by
2144       // default we don't bother. We also might consider predicating the
2145       // _owner==Self check on Xcheck:jni or running on a debug build.
2146       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2147       xorptr(boxReg, r15_thread);
2148     } else {
2149       xorptr(boxReg, boxReg);
2150     }
2151     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2152     jccb  (Assembler::notZero, DONE_LABEL);
2153     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2154     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2155     jccb  (Assembler::notZero, CheckSucc);
2156     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2157     jmpb  (DONE_LABEL);
2158 
2159     if ((EmitSync & 65536) == 0) {
2160       // Try to avoid passing control into the slow_path ...
2161       Label LSuccess, LGoSlowPath ;
2162       bind  (CheckSucc);
2163 
2164       // The following optional optimization can be elided if necessary
2165       // Effectively: if (succ == null) goto SlowPath
2166       // The code reduces the window for a race, however,
2167       // and thus benefits performance.
2168       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2169       jccb  (Assembler::zero, LGoSlowPath);
2170 
2171       if ((EmitSync & 16) && os::is_MP()) {
2172         orptr(boxReg, boxReg);
2173         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2174       } else {
2175         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2176         if (os::is_MP()) {
2177           // Memory barrier/fence
2178           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2179           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2180           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2181           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2182           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2183           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2184           lock(); addl(Address(rsp, 0), 0);
2185         }
2186       }
2187       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2188       jccb  (Assembler::notZero, LSuccess);
2189 
2190       // Rare inopportune interleaving - race.
2191       // The successor vanished in the small window above.
2192       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2193       // We need to ensure progress and succession.
2194       // Try to reacquire the lock.
2195       // If that fails then the new owner is responsible for succession and this
2196       // thread needs to take no further action and can exit via the fast path (success).
2197       // If the re-acquire succeeds then pass control into the slow path.
2198       // As implemented, this latter mode is horrible because we generated more
2199       // coherence traffic on the lock *and* artifically extended the critical section
2200       // length while by virtue of passing control into the slow path.
2201 
2202       // box is really RAX -- the following CMPXCHG depends on that binding
2203       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2204       movptr(boxReg, (int32_t)NULL_WORD);
2205       if (os::is_MP()) { lock(); }
2206       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2207       // There's no successor so we tried to regrab the lock.
2208       // If that didn't work, then another thread grabbed the
2209       // lock so we're done (and exit was a success).
2210       jccb  (Assembler::notEqual, LSuccess);
2211       // Intentional fall-through into slow-path
2212 
2213       bind  (LGoSlowPath);
2214       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2215       jmpb  (DONE_LABEL);
2216 
2217       bind  (LSuccess);
2218       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2219       jmpb  (DONE_LABEL);
2220     }
2221 
2222     bind  (Stacked);
2223     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2224     if (os::is_MP()) { lock(); }
2225     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2226 
2227     if (EmitSync & 65536) {
2228        bind (CheckSucc);
2229     }
2230 #endif
2231     bind(DONE_LABEL);
2232   }
2233 }
2234 #endif // COMPILER2
2235 
2236 void MacroAssembler::c2bool(Register x) {
2237   // implements x == 0 ? 0 : 1
2238   // note: must only look at least-significant byte of x
2239   //       since C-style booleans are stored in one byte
2240   //       only! (was bug)
2241   andl(x, 0xFF);
2242   setb(Assembler::notZero, x);
2243 }
2244 
2245 // Wouldn't need if AddressLiteral version had new name
2246 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2247   Assembler::call(L, rtype);
2248 }
2249 
2250 void MacroAssembler::call(Register entry) {
2251   Assembler::call(entry);
2252 }
2253 
2254 void MacroAssembler::call(AddressLiteral entry) {
2255   if (reachable(entry)) {
2256     Assembler::call_literal(entry.target(), entry.rspec());
2257   } else {
2258     lea(rscratch1, entry);
2259     Assembler::call(rscratch1);
2260   }
2261 }
2262 
2263 void MacroAssembler::ic_call(address entry) {
2264   RelocationHolder rh = virtual_call_Relocation::spec(pc());
2265   movptr(rax, (intptr_t)Universe::non_oop_word());
2266   call(AddressLiteral(entry, rh));
2267 }
2268 
2269 // Implementation of call_VM versions
2270 
2271 void MacroAssembler::call_VM(Register oop_result,
2272                              address entry_point,
2273                              bool check_exceptions) {
2274   Label C, E;
2275   call(C, relocInfo::none);
2276   jmp(E);
2277 
2278   bind(C);
2279   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2280   ret(0);
2281 
2282   bind(E);
2283 }
2284 
2285 void MacroAssembler::call_VM(Register oop_result,
2286                              address entry_point,
2287                              Register arg_1,
2288                              bool check_exceptions) {
2289   Label C, E;
2290   call(C, relocInfo::none);
2291   jmp(E);
2292 
2293   bind(C);
2294   pass_arg1(this, arg_1);
2295   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2296   ret(0);
2297 
2298   bind(E);
2299 }
2300 
2301 void MacroAssembler::call_VM(Register oop_result,
2302                              address entry_point,
2303                              Register arg_1,
2304                              Register arg_2,
2305                              bool check_exceptions) {
2306   Label C, E;
2307   call(C, relocInfo::none);
2308   jmp(E);
2309 
2310   bind(C);
2311 
2312   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2313 
2314   pass_arg2(this, arg_2);
2315   pass_arg1(this, arg_1);
2316   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2317   ret(0);
2318 
2319   bind(E);
2320 }
2321 
2322 void MacroAssembler::call_VM(Register oop_result,
2323                              address entry_point,
2324                              Register arg_1,
2325                              Register arg_2,
2326                              Register arg_3,
2327                              bool check_exceptions) {
2328   Label C, E;
2329   call(C, relocInfo::none);
2330   jmp(E);
2331 
2332   bind(C);
2333 
2334   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2335   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2336   pass_arg3(this, arg_3);
2337 
2338   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2339   pass_arg2(this, arg_2);
2340 
2341   pass_arg1(this, arg_1);
2342   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2343   ret(0);
2344 
2345   bind(E);
2346 }
2347 
2348 void MacroAssembler::call_VM(Register oop_result,
2349                              Register last_java_sp,
2350                              address entry_point,
2351                              int number_of_arguments,
2352                              bool check_exceptions) {
2353   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2354   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2355 }
2356 
2357 void MacroAssembler::call_VM(Register oop_result,
2358                              Register last_java_sp,
2359                              address entry_point,
2360                              Register arg_1,
2361                              bool check_exceptions) {
2362   pass_arg1(this, arg_1);
2363   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2364 }
2365 
2366 void MacroAssembler::call_VM(Register oop_result,
2367                              Register last_java_sp,
2368                              address entry_point,
2369                              Register arg_1,
2370                              Register arg_2,
2371                              bool check_exceptions) {
2372 
2373   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2374   pass_arg2(this, arg_2);
2375   pass_arg1(this, arg_1);
2376   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2377 }
2378 
2379 void MacroAssembler::call_VM(Register oop_result,
2380                              Register last_java_sp,
2381                              address entry_point,
2382                              Register arg_1,
2383                              Register arg_2,
2384                              Register arg_3,
2385                              bool check_exceptions) {
2386   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2387   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2388   pass_arg3(this, arg_3);
2389   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2390   pass_arg2(this, arg_2);
2391   pass_arg1(this, arg_1);
2392   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2393 }
2394 
2395 void MacroAssembler::super_call_VM(Register oop_result,
2396                                    Register last_java_sp,
2397                                    address entry_point,
2398                                    int number_of_arguments,
2399                                    bool check_exceptions) {
2400   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2401   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2402 }
2403 
2404 void MacroAssembler::super_call_VM(Register oop_result,
2405                                    Register last_java_sp,
2406                                    address entry_point,
2407                                    Register arg_1,
2408                                    bool check_exceptions) {
2409   pass_arg1(this, arg_1);
2410   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2411 }
2412 
2413 void MacroAssembler::super_call_VM(Register oop_result,
2414                                    Register last_java_sp,
2415                                    address entry_point,
2416                                    Register arg_1,
2417                                    Register arg_2,
2418                                    bool check_exceptions) {
2419 
2420   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2421   pass_arg2(this, arg_2);
2422   pass_arg1(this, arg_1);
2423   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2424 }
2425 
2426 void MacroAssembler::super_call_VM(Register oop_result,
2427                                    Register last_java_sp,
2428                                    address entry_point,
2429                                    Register arg_1,
2430                                    Register arg_2,
2431                                    Register arg_3,
2432                                    bool check_exceptions) {
2433   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2434   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2435   pass_arg3(this, arg_3);
2436   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2437   pass_arg2(this, arg_2);
2438   pass_arg1(this, arg_1);
2439   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2440 }
2441 
2442 void MacroAssembler::call_VM_base(Register oop_result,
2443                                   Register java_thread,
2444                                   Register last_java_sp,
2445                                   address  entry_point,
2446                                   int      number_of_arguments,
2447                                   bool     check_exceptions) {
2448   // determine java_thread register
2449   if (!java_thread->is_valid()) {
2450 #ifdef _LP64
2451     java_thread = r15_thread;
2452 #else
2453     java_thread = rdi;
2454     get_thread(java_thread);
2455 #endif // LP64
2456   }
2457   // determine last_java_sp register
2458   if (!last_java_sp->is_valid()) {
2459     last_java_sp = rsp;
2460   }
2461   // debugging support
2462   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2463   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2464 #ifdef ASSERT
2465   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2466   // r12 is the heapbase.
2467   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2468 #endif // ASSERT
2469 
2470   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2471   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2472 
2473   // push java thread (becomes first argument of C function)
2474 
2475   NOT_LP64(push(java_thread); number_of_arguments++);
2476   LP64_ONLY(mov(c_rarg0, r15_thread));
2477 
2478   // set last Java frame before call
2479   assert(last_java_sp != rbp, "can't use ebp/rbp");
2480 
2481   // Only interpreter should have to set fp
2482   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2483 
2484   // do the call, remove parameters
2485   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2486 
2487   // restore the thread (cannot use the pushed argument since arguments
2488   // may be overwritten by C code generated by an optimizing compiler);
2489   // however can use the register value directly if it is callee saved.
2490   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2491     // rdi & rsi (also r15) are callee saved -> nothing to do
2492 #ifdef ASSERT
2493     guarantee(java_thread != rax, "change this code");
2494     push(rax);
2495     { Label L;
2496       get_thread(rax);
2497       cmpptr(java_thread, rax);
2498       jcc(Assembler::equal, L);
2499       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2500       bind(L);
2501     }
2502     pop(rax);
2503 #endif
2504   } else {
2505     get_thread(java_thread);
2506   }
2507   // reset last Java frame
2508   // Only interpreter should have to clear fp
2509   reset_last_Java_frame(java_thread, true, false);
2510 
2511 #ifndef CC_INTERP
2512    // C++ interp handles this in the interpreter
2513   check_and_handle_popframe(java_thread);
2514   check_and_handle_earlyret(java_thread);
2515 #endif /* CC_INTERP */
2516 
2517   if (check_exceptions) {
2518     // check for pending exceptions (java_thread is set upon return)
2519     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2520 #ifndef _LP64
2521     jump_cc(Assembler::notEqual,
2522             RuntimeAddress(StubRoutines::forward_exception_entry()));
2523 #else
2524     // This used to conditionally jump to forward_exception however it is
2525     // possible if we relocate that the branch will not reach. So we must jump
2526     // around so we can always reach
2527 
2528     Label ok;
2529     jcc(Assembler::equal, ok);
2530     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2531     bind(ok);
2532 #endif // LP64
2533   }
2534 
2535   // get oop result if there is one and reset the value in the thread
2536   if (oop_result->is_valid()) {
2537     get_vm_result(oop_result, java_thread);
2538   }
2539 }
2540 
2541 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2542 
2543   // Calculate the value for last_Java_sp
2544   // somewhat subtle. call_VM does an intermediate call
2545   // which places a return address on the stack just under the
2546   // stack pointer as the user finsihed with it. This allows
2547   // use to retrieve last_Java_pc from last_Java_sp[-1].
2548   // On 32bit we then have to push additional args on the stack to accomplish
2549   // the actual requested call. On 64bit call_VM only can use register args
2550   // so the only extra space is the return address that call_VM created.
2551   // This hopefully explains the calculations here.
2552 
2553 #ifdef _LP64
2554   // We've pushed one address, correct last_Java_sp
2555   lea(rax, Address(rsp, wordSize));
2556 #else
2557   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2558 #endif // LP64
2559 
2560   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2561 
2562 }
2563 
2564 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2565   call_VM_leaf_base(entry_point, number_of_arguments);
2566 }
2567 
2568 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2569   pass_arg0(this, arg_0);
2570   call_VM_leaf(entry_point, 1);
2571 }
2572 
2573 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2574 
2575   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2576   pass_arg1(this, arg_1);
2577   pass_arg0(this, arg_0);
2578   call_VM_leaf(entry_point, 2);
2579 }
2580 
2581 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2582   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2583   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2584   pass_arg2(this, arg_2);
2585   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2586   pass_arg1(this, arg_1);
2587   pass_arg0(this, arg_0);
2588   call_VM_leaf(entry_point, 3);
2589 }
2590 
2591 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2592   pass_arg0(this, arg_0);
2593   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2594 }
2595 
2596 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2597 
2598   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2599   pass_arg1(this, arg_1);
2600   pass_arg0(this, arg_0);
2601   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2602 }
2603 
2604 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2605   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2606   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2607   pass_arg2(this, arg_2);
2608   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2609   pass_arg1(this, arg_1);
2610   pass_arg0(this, arg_0);
2611   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2612 }
2613 
2614 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2615   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2616   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2617   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2618   pass_arg3(this, arg_3);
2619   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2620   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2621   pass_arg2(this, arg_2);
2622   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2623   pass_arg1(this, arg_1);
2624   pass_arg0(this, arg_0);
2625   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2626 }
2627 
2628 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2629   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2630   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2631   verify_oop(oop_result, "broken oop in call_VM_base");
2632 }
2633 
2634 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2635   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2636   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2637 }
2638 
2639 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2640 }
2641 
2642 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2643 }
2644 
2645 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2646   if (reachable(src1)) {
2647     cmpl(as_Address(src1), imm);
2648   } else {
2649     lea(rscratch1, src1);
2650     cmpl(Address(rscratch1, 0), imm);
2651   }
2652 }
2653 
2654 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2655   assert(!src2.is_lval(), "use cmpptr");
2656   if (reachable(src2)) {
2657     cmpl(src1, as_Address(src2));
2658   } else {
2659     lea(rscratch1, src2);
2660     cmpl(src1, Address(rscratch1, 0));
2661   }
2662 }
2663 
2664 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2665   Assembler::cmpl(src1, imm);
2666 }
2667 
2668 void MacroAssembler::cmp32(Register src1, Address src2) {
2669   Assembler::cmpl(src1, src2);
2670 }
2671 
2672 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2673   ucomisd(opr1, opr2);
2674 
2675   Label L;
2676   if (unordered_is_less) {
2677     movl(dst, -1);
2678     jcc(Assembler::parity, L);
2679     jcc(Assembler::below , L);
2680     movl(dst, 0);
2681     jcc(Assembler::equal , L);
2682     increment(dst);
2683   } else { // unordered is greater
2684     movl(dst, 1);
2685     jcc(Assembler::parity, L);
2686     jcc(Assembler::above , L);
2687     movl(dst, 0);
2688     jcc(Assembler::equal , L);
2689     decrementl(dst);
2690   }
2691   bind(L);
2692 }
2693 
2694 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2695   ucomiss(opr1, opr2);
2696 
2697   Label L;
2698   if (unordered_is_less) {
2699     movl(dst, -1);
2700     jcc(Assembler::parity, L);
2701     jcc(Assembler::below , L);
2702     movl(dst, 0);
2703     jcc(Assembler::equal , L);
2704     increment(dst);
2705   } else { // unordered is greater
2706     movl(dst, 1);
2707     jcc(Assembler::parity, L);
2708     jcc(Assembler::above , L);
2709     movl(dst, 0);
2710     jcc(Assembler::equal , L);
2711     decrementl(dst);
2712   }
2713   bind(L);
2714 }
2715 
2716 
2717 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2718   if (reachable(src1)) {
2719     cmpb(as_Address(src1), imm);
2720   } else {
2721     lea(rscratch1, src1);
2722     cmpb(Address(rscratch1, 0), imm);
2723   }
2724 }
2725 
2726 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2727 #ifdef _LP64
2728   if (src2.is_lval()) {
2729     movptr(rscratch1, src2);
2730     Assembler::cmpq(src1, rscratch1);
2731   } else if (reachable(src2)) {
2732     cmpq(src1, as_Address(src2));
2733   } else {
2734     lea(rscratch1, src2);
2735     Assembler::cmpq(src1, Address(rscratch1, 0));
2736   }
2737 #else
2738   if (src2.is_lval()) {
2739     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2740   } else {
2741     cmpl(src1, as_Address(src2));
2742   }
2743 #endif // _LP64
2744 }
2745 
2746 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2747   assert(src2.is_lval(), "not a mem-mem compare");
2748 #ifdef _LP64
2749   // moves src2's literal address
2750   movptr(rscratch1, src2);
2751   Assembler::cmpq(src1, rscratch1);
2752 #else
2753   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2754 #endif // _LP64
2755 }
2756 
2757 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2758   if (reachable(adr)) {
2759     if (os::is_MP())
2760       lock();
2761     cmpxchgptr(reg, as_Address(adr));
2762   } else {
2763     lea(rscratch1, adr);
2764     if (os::is_MP())
2765       lock();
2766     cmpxchgptr(reg, Address(rscratch1, 0));
2767   }
2768 }
2769 
2770 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2771   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2772 }
2773 
2774 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2775   if (reachable(src)) {
2776     Assembler::comisd(dst, as_Address(src));
2777   } else {
2778     lea(rscratch1, src);
2779     Assembler::comisd(dst, Address(rscratch1, 0));
2780   }
2781 }
2782 
2783 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2784   if (reachable(src)) {
2785     Assembler::comiss(dst, as_Address(src));
2786   } else {
2787     lea(rscratch1, src);
2788     Assembler::comiss(dst, Address(rscratch1, 0));
2789   }
2790 }
2791 
2792 
2793 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2794   Condition negated_cond = negate_condition(cond);
2795   Label L;
2796   jcc(negated_cond, L);
2797   pushf(); // Preserve flags
2798   atomic_incl(counter_addr);
2799   popf();
2800   bind(L);
2801 }
2802 
2803 int MacroAssembler::corrected_idivl(Register reg) {
2804   // Full implementation of Java idiv and irem; checks for
2805   // special case as described in JVM spec., p.243 & p.271.
2806   // The function returns the (pc) offset of the idivl
2807   // instruction - may be needed for implicit exceptions.
2808   //
2809   //         normal case                           special case
2810   //
2811   // input : rax,: dividend                         min_int
2812   //         reg: divisor   (may not be rax,/rdx)   -1
2813   //
2814   // output: rax,: quotient  (= rax, idiv reg)       min_int
2815   //         rdx: remainder (= rax, irem reg)       0
2816   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2817   const int min_int = 0x80000000;
2818   Label normal_case, special_case;
2819 
2820   // check for special case
2821   cmpl(rax, min_int);
2822   jcc(Assembler::notEqual, normal_case);
2823   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2824   cmpl(reg, -1);
2825   jcc(Assembler::equal, special_case);
2826 
2827   // handle normal case
2828   bind(normal_case);
2829   cdql();
2830   int idivl_offset = offset();
2831   idivl(reg);
2832 
2833   // normal and special case exit
2834   bind(special_case);
2835 
2836   return idivl_offset;
2837 }
2838 
2839 
2840 
2841 void MacroAssembler::decrementl(Register reg, int value) {
2842   if (value == min_jint) {subl(reg, value) ; return; }
2843   if (value <  0) { incrementl(reg, -value); return; }
2844   if (value == 0) {                        ; return; }
2845   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2846   /* else */      { subl(reg, value)       ; return; }
2847 }
2848 
2849 void MacroAssembler::decrementl(Address dst, int value) {
2850   if (value == min_jint) {subl(dst, value) ; return; }
2851   if (value <  0) { incrementl(dst, -value); return; }
2852   if (value == 0) {                        ; return; }
2853   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2854   /* else */      { subl(dst, value)       ; return; }
2855 }
2856 
2857 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2858   assert (shift_value > 0, "illegal shift value");
2859   Label _is_positive;
2860   testl (reg, reg);
2861   jcc (Assembler::positive, _is_positive);
2862   int offset = (1 << shift_value) - 1 ;
2863 
2864   if (offset == 1) {
2865     incrementl(reg);
2866   } else {
2867     addl(reg, offset);
2868   }
2869 
2870   bind (_is_positive);
2871   sarl(reg, shift_value);
2872 }
2873 
2874 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2875   if (reachable(src)) {
2876     Assembler::divsd(dst, as_Address(src));
2877   } else {
2878     lea(rscratch1, src);
2879     Assembler::divsd(dst, Address(rscratch1, 0));
2880   }
2881 }
2882 
2883 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2884   if (reachable(src)) {
2885     Assembler::divss(dst, as_Address(src));
2886   } else {
2887     lea(rscratch1, src);
2888     Assembler::divss(dst, Address(rscratch1, 0));
2889   }
2890 }
2891 
2892 // !defined(COMPILER2) is because of stupid core builds
2893 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2894 void MacroAssembler::empty_FPU_stack() {
2895   if (VM_Version::supports_mmx()) {
2896     emms();
2897   } else {
2898     for (int i = 8; i-- > 0; ) ffree(i);
2899   }
2900 }
2901 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2902 
2903 
2904 // Defines obj, preserves var_size_in_bytes
2905 void MacroAssembler::eden_allocate(Register obj,
2906                                    Register var_size_in_bytes,
2907                                    int con_size_in_bytes,
2908                                    Register t1,
2909                                    Label& slow_case) {
2910   assert(obj == rax, "obj must be in rax, for cmpxchg");
2911   assert_different_registers(obj, var_size_in_bytes, t1);
2912   if (!Universe::heap()->supports_inline_contig_alloc()) {
2913     jmp(slow_case);
2914   } else {
2915     Register end = t1;
2916     Label retry;
2917     bind(retry);
2918     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2919     movptr(obj, heap_top);
2920     if (var_size_in_bytes == noreg) {
2921       lea(end, Address(obj, con_size_in_bytes));
2922     } else {
2923       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2924     }
2925     // if end < obj then we wrapped around => object too long => slow case
2926     cmpptr(end, obj);
2927     jcc(Assembler::below, slow_case);
2928     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2929     jcc(Assembler::above, slow_case);
2930     // Compare obj with the top addr, and if still equal, store the new top addr in
2931     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2932     // it otherwise. Use lock prefix for atomicity on MPs.
2933     locked_cmpxchgptr(end, heap_top);
2934     jcc(Assembler::notEqual, retry);
2935   }
2936 }
2937 
2938 void MacroAssembler::enter() {
2939   push(rbp);
2940   mov(rbp, rsp);
2941 }
2942 
2943 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2944 void MacroAssembler::fat_nop() {
2945   if (UseAddressNop) {
2946     addr_nop_5();
2947   } else {
2948     emit_int8(0x26); // es:
2949     emit_int8(0x2e); // cs:
2950     emit_int8(0x64); // fs:
2951     emit_int8(0x65); // gs:
2952     emit_int8((unsigned char)0x90);
2953   }
2954 }
2955 
2956 void MacroAssembler::fcmp(Register tmp) {
2957   fcmp(tmp, 1, true, true);
2958 }
2959 
2960 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2961   assert(!pop_right || pop_left, "usage error");
2962   if (VM_Version::supports_cmov()) {
2963     assert(tmp == noreg, "unneeded temp");
2964     if (pop_left) {
2965       fucomip(index);
2966     } else {
2967       fucomi(index);
2968     }
2969     if (pop_right) {
2970       fpop();
2971     }
2972   } else {
2973     assert(tmp != noreg, "need temp");
2974     if (pop_left) {
2975       if (pop_right) {
2976         fcompp();
2977       } else {
2978         fcomp(index);
2979       }
2980     } else {
2981       fcom(index);
2982     }
2983     // convert FPU condition into eflags condition via rax,
2984     save_rax(tmp);
2985     fwait(); fnstsw_ax();
2986     sahf();
2987     restore_rax(tmp);
2988   }
2989   // condition codes set as follows:
2990   //
2991   // CF (corresponds to C0) if x < y
2992   // PF (corresponds to C2) if unordered
2993   // ZF (corresponds to C3) if x = y
2994 }
2995 
2996 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
2997   fcmp2int(dst, unordered_is_less, 1, true, true);
2998 }
2999 
3000 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3001   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3002   Label L;
3003   if (unordered_is_less) {
3004     movl(dst, -1);
3005     jcc(Assembler::parity, L);
3006     jcc(Assembler::below , L);
3007     movl(dst, 0);
3008     jcc(Assembler::equal , L);
3009     increment(dst);
3010   } else { // unordered is greater
3011     movl(dst, 1);
3012     jcc(Assembler::parity, L);
3013     jcc(Assembler::above , L);
3014     movl(dst, 0);
3015     jcc(Assembler::equal , L);
3016     decrementl(dst);
3017   }
3018   bind(L);
3019 }
3020 
3021 void MacroAssembler::fld_d(AddressLiteral src) {
3022   fld_d(as_Address(src));
3023 }
3024 
3025 void MacroAssembler::fld_s(AddressLiteral src) {
3026   fld_s(as_Address(src));
3027 }
3028 
3029 void MacroAssembler::fld_x(AddressLiteral src) {
3030   Assembler::fld_x(as_Address(src));
3031 }
3032 
3033 void MacroAssembler::fldcw(AddressLiteral src) {
3034   Assembler::fldcw(as_Address(src));
3035 }
3036 
3037 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3038   if (reachable(src)) {
3039     Assembler::mulpd(dst, as_Address(src));
3040   } else {
3041     lea(rscratch1, src);
3042     Assembler::mulpd(dst, Address(rscratch1, 0));
3043   }
3044 }
3045 
3046 void MacroAssembler::pow_exp_core_encoding() {
3047   // kills rax, rcx, rdx
3048   subptr(rsp,sizeof(jdouble));
3049   // computes 2^X. Stack: X ...
3050   // f2xm1 computes 2^X-1 but only operates on -1<=X<=1. Get int(X) and
3051   // keep it on the thread's stack to compute 2^int(X) later
3052   // then compute 2^(X-int(X)) as (2^(X-int(X)-1+1)
3053   // final result is obtained with: 2^X = 2^int(X) * 2^(X-int(X))
3054   fld_s(0);                 // Stack: X X ...
3055   frndint();                // Stack: int(X) X ...
3056   fsuba(1);                 // Stack: int(X) X-int(X) ...
3057   fistp_s(Address(rsp,0));  // move int(X) as integer to thread's stack. Stack: X-int(X) ...
3058   f2xm1();                  // Stack: 2^(X-int(X))-1 ...
3059   fld1();                   // Stack: 1 2^(X-int(X))-1 ...
3060   faddp(1);                 // Stack: 2^(X-int(X))
3061   // computes 2^(int(X)): add exponent bias (1023) to int(X), then
3062   // shift int(X)+1023 to exponent position.
3063   // Exponent is limited to 11 bits if int(X)+1023 does not fit in 11
3064   // bits, set result to NaN. 0x000 and 0x7FF are reserved exponent
3065   // values so detect them and set result to NaN.
3066   movl(rax,Address(rsp,0));
3067   movl(rcx, -2048); // 11 bit mask and valid NaN binary encoding
3068   addl(rax, 1023);
3069   movl(rdx,rax);
3070   shll(rax,20);
3071   // Check that 0 < int(X)+1023 < 2047. Otherwise set rax to NaN.
3072   addl(rdx,1);
3073   // Check that 1 < int(X)+1023+1 < 2048
3074   // in 3 steps:
3075   // 1- (int(X)+1023+1)&-2048 == 0 => 0 <= int(X)+1023+1 < 2048
3076   // 2- (int(X)+1023+1)&-2048 != 0
3077   // 3- (int(X)+1023+1)&-2048 != 1
3078   // Do 2- first because addl just updated the flags.
3079   cmov32(Assembler::equal,rax,rcx);
3080   cmpl(rdx,1);
3081   cmov32(Assembler::equal,rax,rcx);
3082   testl(rdx,rcx);
3083   cmov32(Assembler::notEqual,rax,rcx);
3084   movl(Address(rsp,4),rax);
3085   movl(Address(rsp,0),0);
3086   fmul_d(Address(rsp,0));   // Stack: 2^X ...
3087   addptr(rsp,sizeof(jdouble));
3088 }
3089 
3090 void MacroAssembler::increase_precision() {
3091   subptr(rsp, BytesPerWord);
3092   fnstcw(Address(rsp, 0));
3093   movl(rax, Address(rsp, 0));
3094   orl(rax, 0x300);
3095   push(rax);
3096   fldcw(Address(rsp, 0));
3097   pop(rax);
3098 }
3099 
3100 void MacroAssembler::restore_precision() {
3101   fldcw(Address(rsp, 0));
3102   addptr(rsp, BytesPerWord);
3103 }
3104 
3105 void MacroAssembler::fast_pow() {
3106   // computes X^Y = 2^(Y * log2(X))
3107   // if fast computation is not possible, result is NaN. Requires
3108   // fallback from user of this macro.
3109   // increase precision for intermediate steps of the computation
3110   BLOCK_COMMENT("fast_pow {");
3111   increase_precision();
3112   fyl2x();                 // Stack: (Y*log2(X)) ...
3113   pow_exp_core_encoding(); // Stack: exp(X) ...
3114   restore_precision();
3115   BLOCK_COMMENT("} fast_pow");
3116 }
3117 
3118 void MacroAssembler::pow_or_exp(int num_fpu_regs_in_use) {
3119   // kills rax, rcx, rdx
3120   // pow and exp needs 2 extra registers on the fpu stack.
3121   Label slow_case, done;
3122   Register tmp = noreg;
3123   if (!VM_Version::supports_cmov()) {
3124     // fcmp needs a temporary so preserve rdx,
3125     tmp = rdx;
3126   }
3127   Register tmp2 = rax;
3128   Register tmp3 = rcx;
3129 
3130   // Stack: X Y
3131   Label x_negative, y_not_2;
3132 
3133   static double two = 2.0;
3134   ExternalAddress two_addr((address)&two);
3135 
3136   // constant maybe too far on 64 bit
3137   lea(tmp2, two_addr);
3138   fld_d(Address(tmp2, 0));    // Stack: 2 X Y
3139   fcmp(tmp, 2, true, false);  // Stack: X Y
3140   jcc(Assembler::parity, y_not_2);
3141   jcc(Assembler::notEqual, y_not_2);
3142 
3143   fxch(); fpop();             // Stack: X
3144   fmul(0);                    // Stack: X*X
3145 
3146   jmp(done);
3147 
3148   bind(y_not_2);
3149 
3150   fldz();                     // Stack: 0 X Y
3151   fcmp(tmp, 1, true, false);  // Stack: X Y
3152   jcc(Assembler::above, x_negative);
3153 
3154   // X >= 0
3155 
3156   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3157   fld_s(1);                   // Stack: X Y X Y
3158   fast_pow();                 // Stack: X^Y X Y
3159   fcmp(tmp, 0, false, false); // Stack: X^Y X Y
3160   // X^Y not equal to itself: X^Y is NaN go to slow case.
3161   jcc(Assembler::parity, slow_case);
3162   // get rid of duplicate arguments. Stack: X^Y
3163   if (num_fpu_regs_in_use > 0) {
3164     fxch(); fpop();
3165     fxch(); fpop();
3166   } else {
3167     ffree(2);
3168     ffree(1);
3169   }
3170   jmp(done);
3171 
3172   // X <= 0
3173   bind(x_negative);
3174 
3175   fld_s(1);                   // Stack: Y X Y
3176   frndint();                  // Stack: int(Y) X Y
3177   fcmp(tmp, 2, false, false); // Stack: int(Y) X Y
3178   jcc(Assembler::notEqual, slow_case);
3179 
3180   subptr(rsp, 8);
3181 
3182   // For X^Y, when X < 0, Y has to be an integer and the final
3183   // result depends on whether it's odd or even. We just checked
3184   // that int(Y) == Y.  We move int(Y) to gp registers as a 64 bit
3185   // integer to test its parity. If int(Y) is huge and doesn't fit
3186   // in the 64 bit integer range, the integer indefinite value will
3187   // end up in the gp registers. Huge numbers are all even, the
3188   // integer indefinite number is even so it's fine.
3189 
3190 #ifdef ASSERT
3191   // Let's check we don't end up with an integer indefinite number
3192   // when not expected. First test for huge numbers: check whether
3193   // int(Y)+1 == int(Y) which is true for very large numbers and
3194   // those are all even. A 64 bit integer is guaranteed to not
3195   // overflow for numbers where y+1 != y (when precision is set to
3196   // double precision).
3197   Label y_not_huge;
3198 
3199   fld1();                     // Stack: 1 int(Y) X Y
3200   fadd(1);                    // Stack: 1+int(Y) int(Y) X Y
3201 
3202 #ifdef _LP64
3203   // trip to memory to force the precision down from double extended
3204   // precision
3205   fstp_d(Address(rsp, 0));
3206   fld_d(Address(rsp, 0));
3207 #endif
3208 
3209   fcmp(tmp, 1, true, false);  // Stack: int(Y) X Y
3210 #endif
3211 
3212   // move int(Y) as 64 bit integer to thread's stack
3213   fistp_d(Address(rsp,0));    // Stack: X Y
3214 
3215 #ifdef ASSERT
3216   jcc(Assembler::notEqual, y_not_huge);
3217 
3218   // Y is huge so we know it's even. It may not fit in a 64 bit
3219   // integer and we don't want the debug code below to see the
3220   // integer indefinite value so overwrite int(Y) on the thread's
3221   // stack with 0.
3222   movl(Address(rsp, 0), 0);
3223   movl(Address(rsp, 4), 0);
3224 
3225   bind(y_not_huge);
3226 #endif
3227 
3228   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3229   fld_s(1);                   // Stack: X Y X Y
3230   fabs();                     // Stack: abs(X) Y X Y
3231   fast_pow();                 // Stack: abs(X)^Y X Y
3232   fcmp(tmp, 0, false, false); // Stack: abs(X)^Y X Y
3233   // abs(X)^Y not equal to itself: abs(X)^Y is NaN go to slow case.
3234 
3235   pop(tmp2);
3236   NOT_LP64(pop(tmp3));
3237   jcc(Assembler::parity, slow_case);
3238 
3239 #ifdef ASSERT
3240   // Check that int(Y) is not integer indefinite value (int
3241   // overflow). Shouldn't happen because for values that would
3242   // overflow, 1+int(Y)==Y which was tested earlier.
3243 #ifndef _LP64
3244   {
3245     Label integer;
3246     testl(tmp2, tmp2);
3247     jcc(Assembler::notZero, integer);
3248     cmpl(tmp3, 0x80000000);
3249     jcc(Assembler::notZero, integer);
3250     STOP("integer indefinite value shouldn't be seen here");
3251     bind(integer);
3252   }
3253 #else
3254   {
3255     Label integer;
3256     mov(tmp3, tmp2); // preserve tmp2 for parity check below
3257     shlq(tmp3, 1);
3258     jcc(Assembler::carryClear, integer);
3259     jcc(Assembler::notZero, integer);
3260     STOP("integer indefinite value shouldn't be seen here");
3261     bind(integer);
3262   }
3263 #endif
3264 #endif
3265 
3266   // get rid of duplicate arguments. Stack: X^Y
3267   if (num_fpu_regs_in_use > 0) {
3268     fxch(); fpop();
3269     fxch(); fpop();
3270   } else {
3271     ffree(2);
3272     ffree(1);
3273   }
3274 
3275   testl(tmp2, 1);
3276   jcc(Assembler::zero, done); // X <= 0, Y even: X^Y = abs(X)^Y
3277   // X <= 0, Y even: X^Y = -abs(X)^Y
3278 
3279   fchs();                     // Stack: -abs(X)^Y Y
3280   jmp(done);
3281 
3282   // slow case: runtime call
3283   bind(slow_case);
3284 
3285   fpop();                       // pop incorrect result or int(Y)
3286 
3287   fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dpow), 2, num_fpu_regs_in_use);
3288 
3289   // Come here with result in F-TOS
3290   bind(done);
3291 }
3292 
3293 void MacroAssembler::fpop() {
3294   ffree();
3295   fincstp();
3296 }
3297 
3298 void MacroAssembler::load_float(Address src) {
3299   if (UseSSE >= 1) {
3300     movflt(xmm0, src);
3301   } else {
3302     LP64_ONLY(ShouldNotReachHere());
3303     NOT_LP64(fld_s(src));
3304   }
3305 }
3306 
3307 void MacroAssembler::store_float(Address dst) {
3308   if (UseSSE >= 1) {
3309     movflt(dst, xmm0);
3310   } else {
3311     LP64_ONLY(ShouldNotReachHere());
3312     NOT_LP64(fstp_s(dst));
3313   }
3314 }
3315 
3316 void MacroAssembler::load_double(Address src) {
3317   if (UseSSE >= 2) {
3318     movdbl(xmm0, src);
3319   } else {
3320     LP64_ONLY(ShouldNotReachHere());
3321     NOT_LP64(fld_d(src));
3322   }
3323 }
3324 
3325 void MacroAssembler::store_double(Address dst) {
3326   if (UseSSE >= 2) {
3327     movdbl(dst, xmm0);
3328   } else {
3329     LP64_ONLY(ShouldNotReachHere());
3330     NOT_LP64(fstp_d(dst));
3331   }
3332 }
3333 
3334 void MacroAssembler::fremr(Register tmp) {
3335   save_rax(tmp);
3336   { Label L;
3337     bind(L);
3338     fprem();
3339     fwait(); fnstsw_ax();
3340 #ifdef _LP64
3341     testl(rax, 0x400);
3342     jcc(Assembler::notEqual, L);
3343 #else
3344     sahf();
3345     jcc(Assembler::parity, L);
3346 #endif // _LP64
3347   }
3348   restore_rax(tmp);
3349   // Result is in ST0.
3350   // Note: fxch & fpop to get rid of ST1
3351   // (otherwise FPU stack could overflow eventually)
3352   fxch(1);
3353   fpop();
3354 }
3355 
3356 
3357 void MacroAssembler::incrementl(AddressLiteral dst) {
3358   if (reachable(dst)) {
3359     incrementl(as_Address(dst));
3360   } else {
3361     lea(rscratch1, dst);
3362     incrementl(Address(rscratch1, 0));
3363   }
3364 }
3365 
3366 void MacroAssembler::incrementl(ArrayAddress dst) {
3367   incrementl(as_Address(dst));
3368 }
3369 
3370 void MacroAssembler::incrementl(Register reg, int value) {
3371   if (value == min_jint) {addl(reg, value) ; return; }
3372   if (value <  0) { decrementl(reg, -value); return; }
3373   if (value == 0) {                        ; return; }
3374   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3375   /* else */      { addl(reg, value)       ; return; }
3376 }
3377 
3378 void MacroAssembler::incrementl(Address dst, int value) {
3379   if (value == min_jint) {addl(dst, value) ; return; }
3380   if (value <  0) { decrementl(dst, -value); return; }
3381   if (value == 0) {                        ; return; }
3382   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3383   /* else */      { addl(dst, value)       ; return; }
3384 }
3385 
3386 void MacroAssembler::jump(AddressLiteral dst) {
3387   if (reachable(dst)) {
3388     jmp_literal(dst.target(), dst.rspec());
3389   } else {
3390     lea(rscratch1, dst);
3391     jmp(rscratch1);
3392   }
3393 }
3394 
3395 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3396   if (reachable(dst)) {
3397     InstructionMark im(this);
3398     relocate(dst.reloc());
3399     const int short_size = 2;
3400     const int long_size = 6;
3401     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3402     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3403       // 0111 tttn #8-bit disp
3404       emit_int8(0x70 | cc);
3405       emit_int8((offs - short_size) & 0xFF);
3406     } else {
3407       // 0000 1111 1000 tttn #32-bit disp
3408       emit_int8(0x0F);
3409       emit_int8((unsigned char)(0x80 | cc));
3410       emit_int32(offs - long_size);
3411     }
3412   } else {
3413 #ifdef ASSERT
3414     warning("reversing conditional branch");
3415 #endif /* ASSERT */
3416     Label skip;
3417     jccb(reverse[cc], skip);
3418     lea(rscratch1, dst);
3419     Assembler::jmp(rscratch1);
3420     bind(skip);
3421   }
3422 }
3423 
3424 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3425   if (reachable(src)) {
3426     Assembler::ldmxcsr(as_Address(src));
3427   } else {
3428     lea(rscratch1, src);
3429     Assembler::ldmxcsr(Address(rscratch1, 0));
3430   }
3431 }
3432 
3433 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3434   int off;
3435   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3436     off = offset();
3437     movsbl(dst, src); // movsxb
3438   } else {
3439     off = load_unsigned_byte(dst, src);
3440     shll(dst, 24);
3441     sarl(dst, 24);
3442   }
3443   return off;
3444 }
3445 
3446 // Note: load_signed_short used to be called load_signed_word.
3447 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3448 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3449 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3450 int MacroAssembler::load_signed_short(Register dst, Address src) {
3451   int off;
3452   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3453     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3454     // version but this is what 64bit has always done. This seems to imply
3455     // that users are only using 32bits worth.
3456     off = offset();
3457     movswl(dst, src); // movsxw
3458   } else {
3459     off = load_unsigned_short(dst, src);
3460     shll(dst, 16);
3461     sarl(dst, 16);
3462   }
3463   return off;
3464 }
3465 
3466 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3467   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3468   // and "3.9 Partial Register Penalties", p. 22).
3469   int off;
3470   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3471     off = offset();
3472     movzbl(dst, src); // movzxb
3473   } else {
3474     xorl(dst, dst);
3475     off = offset();
3476     movb(dst, src);
3477   }
3478   return off;
3479 }
3480 
3481 // Note: load_unsigned_short used to be called load_unsigned_word.
3482 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3483   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3484   // and "3.9 Partial Register Penalties", p. 22).
3485   int off;
3486   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3487     off = offset();
3488     movzwl(dst, src); // movzxw
3489   } else {
3490     xorl(dst, dst);
3491     off = offset();
3492     movw(dst, src);
3493   }
3494   return off;
3495 }
3496 
3497 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3498   switch (size_in_bytes) {
3499 #ifndef _LP64
3500   case  8:
3501     assert(dst2 != noreg, "second dest register required");
3502     movl(dst,  src);
3503     movl(dst2, src.plus_disp(BytesPerInt));
3504     break;
3505 #else
3506   case  8:  movq(dst, src); break;
3507 #endif
3508   case  4:  movl(dst, src); break;
3509   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3510   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3511   default:  ShouldNotReachHere();
3512   }
3513 }
3514 
3515 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3516   switch (size_in_bytes) {
3517 #ifndef _LP64
3518   case  8:
3519     assert(src2 != noreg, "second source register required");
3520     movl(dst,                        src);
3521     movl(dst.plus_disp(BytesPerInt), src2);
3522     break;
3523 #else
3524   case  8:  movq(dst, src); break;
3525 #endif
3526   case  4:  movl(dst, src); break;
3527   case  2:  movw(dst, src); break;
3528   case  1:  movb(dst, src); break;
3529   default:  ShouldNotReachHere();
3530   }
3531 }
3532 
3533 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3534   if (reachable(dst)) {
3535     movl(as_Address(dst), src);
3536   } else {
3537     lea(rscratch1, dst);
3538     movl(Address(rscratch1, 0), src);
3539   }
3540 }
3541 
3542 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3543   if (reachable(src)) {
3544     movl(dst, as_Address(src));
3545   } else {
3546     lea(rscratch1, src);
3547     movl(dst, Address(rscratch1, 0));
3548   }
3549 }
3550 
3551 // C++ bool manipulation
3552 
3553 void MacroAssembler::movbool(Register dst, Address src) {
3554   if(sizeof(bool) == 1)
3555     movb(dst, src);
3556   else if(sizeof(bool) == 2)
3557     movw(dst, src);
3558   else if(sizeof(bool) == 4)
3559     movl(dst, src);
3560   else
3561     // unsupported
3562     ShouldNotReachHere();
3563 }
3564 
3565 void MacroAssembler::movbool(Address dst, bool boolconst) {
3566   if(sizeof(bool) == 1)
3567     movb(dst, (int) boolconst);
3568   else if(sizeof(bool) == 2)
3569     movw(dst, (int) boolconst);
3570   else if(sizeof(bool) == 4)
3571     movl(dst, (int) boolconst);
3572   else
3573     // unsupported
3574     ShouldNotReachHere();
3575 }
3576 
3577 void MacroAssembler::movbool(Address dst, Register src) {
3578   if(sizeof(bool) == 1)
3579     movb(dst, src);
3580   else if(sizeof(bool) == 2)
3581     movw(dst, src);
3582   else if(sizeof(bool) == 4)
3583     movl(dst, src);
3584   else
3585     // unsupported
3586     ShouldNotReachHere();
3587 }
3588 
3589 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3590   movb(as_Address(dst), src);
3591 }
3592 
3593 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3594   if (reachable(src)) {
3595     movdl(dst, as_Address(src));
3596   } else {
3597     lea(rscratch1, src);
3598     movdl(dst, Address(rscratch1, 0));
3599   }
3600 }
3601 
3602 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3603   if (reachable(src)) {
3604     movq(dst, as_Address(src));
3605   } else {
3606     lea(rscratch1, src);
3607     movq(dst, Address(rscratch1, 0));
3608   }
3609 }
3610 
3611 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3612   if (reachable(src)) {
3613     if (UseXmmLoadAndClearUpper) {
3614       movsd (dst, as_Address(src));
3615     } else {
3616       movlpd(dst, as_Address(src));
3617     }
3618   } else {
3619     lea(rscratch1, src);
3620     if (UseXmmLoadAndClearUpper) {
3621       movsd (dst, Address(rscratch1, 0));
3622     } else {
3623       movlpd(dst, Address(rscratch1, 0));
3624     }
3625   }
3626 }
3627 
3628 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3629   if (reachable(src)) {
3630     movss(dst, as_Address(src));
3631   } else {
3632     lea(rscratch1, src);
3633     movss(dst, Address(rscratch1, 0));
3634   }
3635 }
3636 
3637 void MacroAssembler::movptr(Register dst, Register src) {
3638   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3639 }
3640 
3641 void MacroAssembler::movptr(Register dst, Address src) {
3642   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3643 }
3644 
3645 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3646 void MacroAssembler::movptr(Register dst, intptr_t src) {
3647   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3648 }
3649 
3650 void MacroAssembler::movptr(Address dst, Register src) {
3651   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3652 }
3653 
3654 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3655   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3656     Assembler::vextractf32x4h(dst, src, 0);
3657   } else {
3658     Assembler::movdqu(dst, src);
3659   }
3660 }
3661 
3662 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3663   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3664     Assembler::vinsertf32x4h(dst, src, 0);
3665   } else {
3666     Assembler::movdqu(dst, src);
3667   }
3668 }
3669 
3670 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3671   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3672     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3673   } else {
3674     Assembler::movdqu(dst, src);
3675   }
3676 }
3677 
3678 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3679   if (reachable(src)) {
3680     movdqu(dst, as_Address(src));
3681   } else {
3682     lea(rscratch1, src);
3683     movdqu(dst, Address(rscratch1, 0));
3684   }
3685 }
3686 
3687 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3688   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3689     Assembler::vextractf64x4h(dst, src, 0);
3690   } else {
3691     Assembler::vmovdqu(dst, src);
3692   }
3693 }
3694 
3695 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3696   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3697     Assembler::vinsertf64x4h(dst, src, 0);
3698   } else {
3699     Assembler::vmovdqu(dst, src);
3700   }
3701 }
3702 
3703 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3704   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3705     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3706   }
3707   else {
3708     Assembler::vmovdqu(dst, src);
3709   }
3710 }
3711 
3712 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3713   if (reachable(src)) {
3714     vmovdqu(dst, as_Address(src));
3715   }
3716   else {
3717     lea(rscratch1, src);
3718     vmovdqu(dst, Address(rscratch1, 0));
3719   }
3720 }
3721 
3722 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3723   if (reachable(src)) {
3724     Assembler::movdqa(dst, as_Address(src));
3725   } else {
3726     lea(rscratch1, src);
3727     Assembler::movdqa(dst, Address(rscratch1, 0));
3728   }
3729 }
3730 
3731 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3732   if (reachable(src)) {
3733     Assembler::movsd(dst, as_Address(src));
3734   } else {
3735     lea(rscratch1, src);
3736     Assembler::movsd(dst, Address(rscratch1, 0));
3737   }
3738 }
3739 
3740 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3741   if (reachable(src)) {
3742     Assembler::movss(dst, as_Address(src));
3743   } else {
3744     lea(rscratch1, src);
3745     Assembler::movss(dst, Address(rscratch1, 0));
3746   }
3747 }
3748 
3749 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3750   if (reachable(src)) {
3751     Assembler::mulsd(dst, as_Address(src));
3752   } else {
3753     lea(rscratch1, src);
3754     Assembler::mulsd(dst, Address(rscratch1, 0));
3755   }
3756 }
3757 
3758 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3759   if (reachable(src)) {
3760     Assembler::mulss(dst, as_Address(src));
3761   } else {
3762     lea(rscratch1, src);
3763     Assembler::mulss(dst, Address(rscratch1, 0));
3764   }
3765 }
3766 
3767 void MacroAssembler::null_check(Register reg, int offset) {
3768   if (needs_explicit_null_check(offset)) {
3769     // provoke OS NULL exception if reg = NULL by
3770     // accessing M[reg] w/o changing any (non-CC) registers
3771     // NOTE: cmpl is plenty here to provoke a segv
3772     cmpptr(rax, Address(reg, 0));
3773     // Note: should probably use testl(rax, Address(reg, 0));
3774     //       may be shorter code (however, this version of
3775     //       testl needs to be implemented first)
3776   } else {
3777     // nothing to do, (later) access of M[reg + offset]
3778     // will provoke OS NULL exception if reg = NULL
3779   }
3780 }
3781 
3782 void MacroAssembler::os_breakpoint() {
3783   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3784   // (e.g., MSVC can't call ps() otherwise)
3785   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3786 }
3787 
3788 #ifdef _LP64
3789 #define XSTATE_BV 0x200
3790 #endif
3791 
3792 void MacroAssembler::pop_CPU_state() {
3793   pop_FPU_state();
3794   pop_IU_state();
3795 }
3796 
3797 void MacroAssembler::pop_FPU_state() {
3798 #ifndef _LP64
3799   frstor(Address(rsp, 0));
3800 #else
3801   fxrstor(Address(rsp, 0));
3802 #endif
3803   addptr(rsp, FPUStateSizeInWords * wordSize);
3804 }
3805 
3806 void MacroAssembler::pop_IU_state() {
3807   popa();
3808   LP64_ONLY(addq(rsp, 8));
3809   popf();
3810 }
3811 
3812 // Save Integer and Float state
3813 // Warning: Stack must be 16 byte aligned (64bit)
3814 void MacroAssembler::push_CPU_state() {
3815   push_IU_state();
3816   push_FPU_state();
3817 }
3818 
3819 void MacroAssembler::push_FPU_state() {
3820   subptr(rsp, FPUStateSizeInWords * wordSize);
3821 #ifndef _LP64
3822   fnsave(Address(rsp, 0));
3823   fwait();
3824 #else
3825   fxsave(Address(rsp, 0));
3826 #endif // LP64
3827 }
3828 
3829 void MacroAssembler::push_IU_state() {
3830   // Push flags first because pusha kills them
3831   pushf();
3832   // Make sure rsp stays 16-byte aligned
3833   LP64_ONLY(subq(rsp, 8));
3834   pusha();
3835 }
3836 
3837 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3838   // determine java_thread register
3839   if (!java_thread->is_valid()) {
3840     java_thread = rdi;
3841     get_thread(java_thread);
3842   }
3843   // we must set sp to zero to clear frame
3844   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3845   if (clear_fp) {
3846     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3847   }
3848 
3849   if (clear_pc)
3850     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3851 
3852 }
3853 
3854 void MacroAssembler::restore_rax(Register tmp) {
3855   if (tmp == noreg) pop(rax);
3856   else if (tmp != rax) mov(rax, tmp);
3857 }
3858 
3859 void MacroAssembler::round_to(Register reg, int modulus) {
3860   addptr(reg, modulus - 1);
3861   andptr(reg, -modulus);
3862 }
3863 
3864 void MacroAssembler::save_rax(Register tmp) {
3865   if (tmp == noreg) push(rax);
3866   else if (tmp != rax) mov(tmp, rax);
3867 }
3868 
3869 // Write serialization page so VM thread can do a pseudo remote membar.
3870 // We use the current thread pointer to calculate a thread specific
3871 // offset to write to within the page. This minimizes bus traffic
3872 // due to cache line collision.
3873 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3874   movl(tmp, thread);
3875   shrl(tmp, os::get_serialize_page_shift_count());
3876   andl(tmp, (os::vm_page_size() - sizeof(int)));
3877 
3878   Address index(noreg, tmp, Address::times_1);
3879   ExternalAddress page(os::get_memory_serialize_page());
3880 
3881   // Size of store must match masking code above
3882   movl(as_Address(ArrayAddress(page, index)), tmp);
3883 }
3884 
3885 // Calls to C land
3886 //
3887 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3888 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3889 // has to be reset to 0. This is required to allow proper stack traversal.
3890 void MacroAssembler::set_last_Java_frame(Register java_thread,
3891                                          Register last_java_sp,
3892                                          Register last_java_fp,
3893                                          address  last_java_pc) {
3894   // determine java_thread register
3895   if (!java_thread->is_valid()) {
3896     java_thread = rdi;
3897     get_thread(java_thread);
3898   }
3899   // determine last_java_sp register
3900   if (!last_java_sp->is_valid()) {
3901     last_java_sp = rsp;
3902   }
3903 
3904   // last_java_fp is optional
3905 
3906   if (last_java_fp->is_valid()) {
3907     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3908   }
3909 
3910   // last_java_pc is optional
3911 
3912   if (last_java_pc != NULL) {
3913     lea(Address(java_thread,
3914                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3915         InternalAddress(last_java_pc));
3916 
3917   }
3918   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3919 }
3920 
3921 void MacroAssembler::shlptr(Register dst, int imm8) {
3922   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3923 }
3924 
3925 void MacroAssembler::shrptr(Register dst, int imm8) {
3926   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3927 }
3928 
3929 void MacroAssembler::sign_extend_byte(Register reg) {
3930   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3931     movsbl(reg, reg); // movsxb
3932   } else {
3933     shll(reg, 24);
3934     sarl(reg, 24);
3935   }
3936 }
3937 
3938 void MacroAssembler::sign_extend_short(Register reg) {
3939   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3940     movswl(reg, reg); // movsxw
3941   } else {
3942     shll(reg, 16);
3943     sarl(reg, 16);
3944   }
3945 }
3946 
3947 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3948   assert(reachable(src), "Address should be reachable");
3949   testl(dst, as_Address(src));
3950 }
3951 
3952 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3953   int dst_enc = dst->encoding();
3954   int src_enc = src->encoding();
3955   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3956     Assembler::pcmpeqb(dst, src);
3957   } else if ((dst_enc < 16) && (src_enc < 16)) {
3958     Assembler::pcmpeqb(dst, src);
3959   } else if (src_enc < 16) {
3960     subptr(rsp, 64);
3961     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3962     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3963     Assembler::pcmpeqb(xmm0, src);
3964     movdqu(dst, xmm0);
3965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3966     addptr(rsp, 64);
3967   } else if (dst_enc < 16) {
3968     subptr(rsp, 64);
3969     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3970     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3971     Assembler::pcmpeqb(dst, xmm0);
3972     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3973     addptr(rsp, 64);
3974   } else {
3975     subptr(rsp, 64);
3976     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3977     subptr(rsp, 64);
3978     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3979     movdqu(xmm0, src);
3980     movdqu(xmm1, dst);
3981     Assembler::pcmpeqb(xmm1, xmm0);
3982     movdqu(dst, xmm1);
3983     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3986     addptr(rsp, 64);
3987   }
3988 }
3989 
3990 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3991   int dst_enc = dst->encoding();
3992   int src_enc = src->encoding();
3993   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3994     Assembler::pcmpeqw(dst, src);
3995   } else if ((dst_enc < 16) && (src_enc < 16)) {
3996     Assembler::pcmpeqw(dst, src);
3997   } else if (src_enc < 16) {
3998     subptr(rsp, 64);
3999     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4000     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4001     Assembler::pcmpeqw(xmm0, src);
4002     movdqu(dst, xmm0);
4003     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4004     addptr(rsp, 64);
4005   } else if (dst_enc < 16) {
4006     subptr(rsp, 64);
4007     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4008     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4009     Assembler::pcmpeqw(dst, xmm0);
4010     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4011     addptr(rsp, 64);
4012   } else {
4013     subptr(rsp, 64);
4014     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4015     subptr(rsp, 64);
4016     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4017     movdqu(xmm0, src);
4018     movdqu(xmm1, dst);
4019     Assembler::pcmpeqw(xmm1, xmm0);
4020     movdqu(dst, xmm1);
4021     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4022     addptr(rsp, 64);
4023     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4024     addptr(rsp, 64);
4025   }
4026 }
4027 
4028 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
4029   int dst_enc = dst->encoding();
4030   if (dst_enc < 16) {
4031     Assembler::pcmpestri(dst, src, imm8);
4032   } else {
4033     subptr(rsp, 64);
4034     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4035     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4036     Assembler::pcmpestri(xmm0, src, imm8);
4037     movdqu(dst, xmm0);
4038     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4039     addptr(rsp, 64);
4040   }
4041 }
4042 
4043 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
4044   int dst_enc = dst->encoding();
4045   int src_enc = src->encoding();
4046   if ((dst_enc < 16) && (src_enc < 16)) {
4047     Assembler::pcmpestri(dst, src, imm8);
4048   } else if (src_enc < 16) {
4049     subptr(rsp, 64);
4050     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4051     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4052     Assembler::pcmpestri(xmm0, src, imm8);
4053     movdqu(dst, xmm0);
4054     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4055     addptr(rsp, 64);
4056   } else if (dst_enc < 16) {
4057     subptr(rsp, 64);
4058     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4059     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4060     Assembler::pcmpestri(dst, xmm0, imm8);
4061     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4062     addptr(rsp, 64);
4063   } else {
4064     subptr(rsp, 64);
4065     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4066     subptr(rsp, 64);
4067     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4068     movdqu(xmm0, src);
4069     movdqu(xmm1, dst);
4070     Assembler::pcmpestri(xmm1, xmm0, imm8);
4071     movdqu(dst, xmm1);
4072     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4073     addptr(rsp, 64);
4074     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4075     addptr(rsp, 64);
4076   }
4077 }
4078 
4079 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4080   int dst_enc = dst->encoding();
4081   int src_enc = src->encoding();
4082   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4083     Assembler::pmovzxbw(dst, src);
4084   } else if ((dst_enc < 16) && (src_enc < 16)) {
4085     Assembler::pmovzxbw(dst, src);
4086   } else if (src_enc < 16) {
4087     subptr(rsp, 64);
4088     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4089     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4090     Assembler::pmovzxbw(xmm0, src);
4091     movdqu(dst, xmm0);
4092     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4093     addptr(rsp, 64);
4094   } else if (dst_enc < 16) {
4095     subptr(rsp, 64);
4096     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4097     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4098     Assembler::pmovzxbw(dst, xmm0);
4099     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4100     addptr(rsp, 64);
4101   } else {
4102     subptr(rsp, 64);
4103     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4104     subptr(rsp, 64);
4105     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4106     movdqu(xmm0, src);
4107     movdqu(xmm1, dst);
4108     Assembler::pmovzxbw(xmm1, xmm0);
4109     movdqu(dst, xmm1);
4110     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4111     addptr(rsp, 64);
4112     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4113     addptr(rsp, 64);
4114   }
4115 }
4116 
4117 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4118   int dst_enc = dst->encoding();
4119   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4120     Assembler::pmovzxbw(dst, src);
4121   } else if (dst_enc < 16) {
4122     Assembler::pmovzxbw(dst, src);
4123   } else {
4124     subptr(rsp, 64);
4125     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4126     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4127     Assembler::pmovzxbw(xmm0, src);
4128     movdqu(dst, xmm0);
4129     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4130     addptr(rsp, 64);
4131   }
4132 }
4133 
4134 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4135   int src_enc = src->encoding();
4136   if (src_enc < 16) {
4137     Assembler::pmovmskb(dst, src);
4138   } else {
4139     subptr(rsp, 64);
4140     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4141     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4142     Assembler::pmovmskb(dst, xmm0);
4143     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4144     addptr(rsp, 64);
4145   }
4146 }
4147 
4148 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4149   int dst_enc = dst->encoding();
4150   int src_enc = src->encoding();
4151   if ((dst_enc < 16) && (src_enc < 16)) {
4152     Assembler::ptest(dst, src);
4153   } else if (src_enc < 16) {
4154     subptr(rsp, 64);
4155     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4156     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4157     Assembler::ptest(xmm0, src);
4158     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4159     addptr(rsp, 64);
4160   } else if (dst_enc < 16) {
4161     subptr(rsp, 64);
4162     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4163     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4164     Assembler::ptest(dst, xmm0);
4165     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4166     addptr(rsp, 64);
4167   } else {
4168     subptr(rsp, 64);
4169     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4170     subptr(rsp, 64);
4171     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4172     movdqu(xmm0, src);
4173     movdqu(xmm1, dst);
4174     Assembler::ptest(xmm1, xmm0);
4175     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4176     addptr(rsp, 64);
4177     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4178     addptr(rsp, 64);
4179   }
4180 }
4181 
4182 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4183   if (reachable(src)) {
4184     Assembler::sqrtsd(dst, as_Address(src));
4185   } else {
4186     lea(rscratch1, src);
4187     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4188   }
4189 }
4190 
4191 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4192   if (reachable(src)) {
4193     Assembler::sqrtss(dst, as_Address(src));
4194   } else {
4195     lea(rscratch1, src);
4196     Assembler::sqrtss(dst, Address(rscratch1, 0));
4197   }
4198 }
4199 
4200 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4201   if (reachable(src)) {
4202     Assembler::subsd(dst, as_Address(src));
4203   } else {
4204     lea(rscratch1, src);
4205     Assembler::subsd(dst, Address(rscratch1, 0));
4206   }
4207 }
4208 
4209 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4210   if (reachable(src)) {
4211     Assembler::subss(dst, as_Address(src));
4212   } else {
4213     lea(rscratch1, src);
4214     Assembler::subss(dst, Address(rscratch1, 0));
4215   }
4216 }
4217 
4218 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4219   if (reachable(src)) {
4220     Assembler::ucomisd(dst, as_Address(src));
4221   } else {
4222     lea(rscratch1, src);
4223     Assembler::ucomisd(dst, Address(rscratch1, 0));
4224   }
4225 }
4226 
4227 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4228   if (reachable(src)) {
4229     Assembler::ucomiss(dst, as_Address(src));
4230   } else {
4231     lea(rscratch1, src);
4232     Assembler::ucomiss(dst, Address(rscratch1, 0));
4233   }
4234 }
4235 
4236 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4237   // Used in sign-bit flipping with aligned address.
4238   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4239   if (reachable(src)) {
4240     Assembler::xorpd(dst, as_Address(src));
4241   } else {
4242     lea(rscratch1, src);
4243     Assembler::xorpd(dst, Address(rscratch1, 0));
4244   }
4245 }
4246 
4247 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4248   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4249     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4250   }
4251   else {
4252     Assembler::xorpd(dst, src);
4253   }
4254 }
4255 
4256 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4257   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4258     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4259   } else {
4260     Assembler::xorps(dst, src);
4261   }
4262 }
4263 
4264 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4265   // Used in sign-bit flipping with aligned address.
4266   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4267   if (reachable(src)) {
4268     Assembler::xorps(dst, as_Address(src));
4269   } else {
4270     lea(rscratch1, src);
4271     Assembler::xorps(dst, Address(rscratch1, 0));
4272   }
4273 }
4274 
4275 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4276   // Used in sign-bit flipping with aligned address.
4277   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4278   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4279   if (reachable(src)) {
4280     Assembler::pshufb(dst, as_Address(src));
4281   } else {
4282     lea(rscratch1, src);
4283     Assembler::pshufb(dst, Address(rscratch1, 0));
4284   }
4285 }
4286 
4287 // AVX 3-operands instructions
4288 
4289 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4290   if (reachable(src)) {
4291     vaddsd(dst, nds, as_Address(src));
4292   } else {
4293     lea(rscratch1, src);
4294     vaddsd(dst, nds, Address(rscratch1, 0));
4295   }
4296 }
4297 
4298 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4299   if (reachable(src)) {
4300     vaddss(dst, nds, as_Address(src));
4301   } else {
4302     lea(rscratch1, src);
4303     vaddss(dst, nds, Address(rscratch1, 0));
4304   }
4305 }
4306 
4307 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4308   int dst_enc = dst->encoding();
4309   int nds_enc = nds->encoding();
4310   int src_enc = src->encoding();
4311   if ((dst_enc < 16) && (nds_enc < 16)) {
4312     vandps(dst, nds, negate_field, vector_len);
4313   } else if ((src_enc < 16) && (dst_enc < 16)) {
4314     movss(src, nds);
4315     vandps(dst, src, negate_field, vector_len);
4316   } else if (src_enc < 16) {
4317     movss(src, nds);
4318     vandps(src, src, negate_field, vector_len);
4319     movss(dst, src);
4320   } else if (dst_enc < 16) {
4321     movdqu(src, xmm0);
4322     movss(xmm0, nds);
4323     vandps(dst, xmm0, negate_field, vector_len);
4324     movdqu(xmm0, src);
4325   } else if (nds_enc < 16) {
4326     movdqu(src, xmm0);
4327     vandps(xmm0, nds, negate_field, vector_len);
4328     movss(dst, xmm0);
4329     movdqu(xmm0, src);
4330   } else {
4331     movdqu(src, xmm0);
4332     movss(xmm0, nds);
4333     vandps(xmm0, xmm0, negate_field, vector_len);
4334     movss(dst, xmm0);
4335     movdqu(xmm0, src);
4336   }
4337 }
4338 
4339 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4340   int dst_enc = dst->encoding();
4341   int nds_enc = nds->encoding();
4342   int src_enc = src->encoding();
4343   if ((dst_enc < 16) && (nds_enc < 16)) {
4344     vandpd(dst, nds, negate_field, vector_len);
4345   } else if ((src_enc < 16) && (dst_enc < 16)) {
4346     movsd(src, nds);
4347     vandpd(dst, src, negate_field, vector_len);
4348   } else if (src_enc < 16) {
4349     movsd(src, nds);
4350     vandpd(src, src, negate_field, vector_len);
4351     movsd(dst, src);
4352   } else if (dst_enc < 16) {
4353     movdqu(src, xmm0);
4354     movsd(xmm0, nds);
4355     vandpd(dst, xmm0, negate_field, vector_len);
4356     movdqu(xmm0, src);
4357   } else if (nds_enc < 16) {
4358     movdqu(src, xmm0);
4359     vandpd(xmm0, nds, negate_field, vector_len);
4360     movsd(dst, xmm0);
4361     movdqu(xmm0, src);
4362   } else {
4363     movdqu(src, xmm0);
4364     movsd(xmm0, nds);
4365     vandpd(xmm0, xmm0, negate_field, vector_len);
4366     movsd(dst, xmm0);
4367     movdqu(xmm0, src);
4368   }
4369 }
4370 
4371 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4372   int dst_enc = dst->encoding();
4373   int nds_enc = nds->encoding();
4374   int src_enc = src->encoding();
4375   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4376     Assembler::vpaddb(dst, nds, src, vector_len);
4377   } else if ((dst_enc < 16) && (src_enc < 16)) {
4378     Assembler::vpaddb(dst, dst, src, vector_len);
4379   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4380     // use nds as scratch for src
4381     evmovdqul(nds, src, Assembler::AVX_512bit);
4382     Assembler::vpaddb(dst, dst, nds, vector_len);
4383   } else if ((src_enc < 16) && (nds_enc < 16)) {
4384     // use nds as scratch for dst
4385     evmovdqul(nds, dst, Assembler::AVX_512bit);
4386     Assembler::vpaddb(nds, nds, src, vector_len);
4387     evmovdqul(dst, nds, Assembler::AVX_512bit);
4388   } else if (dst_enc < 16) {
4389     // use nds as scatch for xmm0 to hold src
4390     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4391     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4392     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4393     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4394   } else {
4395     // worse case scenario, all regs are in the upper bank
4396     subptr(rsp, 64);
4397     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4398     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4399     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4400     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4401     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4402     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4403     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4404     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4405     addptr(rsp, 64);
4406   }
4407 }
4408 
4409 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4410   int dst_enc = dst->encoding();
4411   int nds_enc = nds->encoding();
4412   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4413     Assembler::vpaddb(dst, nds, src, vector_len);
4414   } else if (dst_enc < 16) {
4415     Assembler::vpaddb(dst, dst, src, vector_len);
4416   } else if (nds_enc < 16) {
4417     // implies dst_enc in upper bank with src as scratch
4418     evmovdqul(nds, dst, Assembler::AVX_512bit);
4419     Assembler::vpaddb(nds, nds, src, vector_len);
4420     evmovdqul(dst, nds, Assembler::AVX_512bit);
4421   } else {
4422     // worse case scenario, all regs in upper bank
4423     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4424     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4425     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4426     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4427   }
4428 }
4429 
4430 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4431   int dst_enc = dst->encoding();
4432   int nds_enc = nds->encoding();
4433   int src_enc = src->encoding();
4434   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4435     Assembler::vpaddw(dst, nds, src, vector_len);
4436   } else if ((dst_enc < 16) && (src_enc < 16)) {
4437     Assembler::vpaddw(dst, dst, src, vector_len);
4438   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4439     // use nds as scratch for src
4440     evmovdqul(nds, src, Assembler::AVX_512bit);
4441     Assembler::vpaddw(dst, dst, nds, vector_len);
4442   } else if ((src_enc < 16) && (nds_enc < 16)) {
4443     // use nds as scratch for dst
4444     evmovdqul(nds, dst, Assembler::AVX_512bit);
4445     Assembler::vpaddw(nds, nds, src, vector_len);
4446     evmovdqul(dst, nds, Assembler::AVX_512bit);
4447   } else if (dst_enc < 16) {
4448     // use nds as scatch for xmm0 to hold src
4449     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4450     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4451     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4452     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4453   } else {
4454     // worse case scenario, all regs are in the upper bank
4455     subptr(rsp, 64);
4456     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4457     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4458     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4459     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4460     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4461     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4462     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4463     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4464     addptr(rsp, 64);
4465   }
4466 }
4467 
4468 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4469   int dst_enc = dst->encoding();
4470   int nds_enc = nds->encoding();
4471   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4472     Assembler::vpaddw(dst, nds, src, vector_len);
4473   } else if (dst_enc < 16) {
4474     Assembler::vpaddw(dst, dst, src, vector_len);
4475   } else if (nds_enc < 16) {
4476     // implies dst_enc in upper bank with src as scratch
4477     evmovdqul(nds, dst, Assembler::AVX_512bit);
4478     Assembler::vpaddw(nds, nds, src, vector_len);
4479     evmovdqul(dst, nds, Assembler::AVX_512bit);
4480   } else {
4481     // worse case scenario, all regs in upper bank
4482     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4483     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4484     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4485     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4486   }
4487 }
4488 
4489 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4490   int dst_enc = dst->encoding();
4491   int src_enc = src->encoding();
4492   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4493     Assembler::vpbroadcastw(dst, src);
4494   } else if ((dst_enc < 16) && (src_enc < 16)) {
4495     Assembler::vpbroadcastw(dst, src);
4496   } else if (src_enc < 16) {
4497     subptr(rsp, 64);
4498     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4499     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4500     Assembler::vpbroadcastw(xmm0, src);
4501     movdqu(dst, xmm0);
4502     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4503     addptr(rsp, 64);
4504   } else if (dst_enc < 16) {
4505     subptr(rsp, 64);
4506     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4507     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4508     Assembler::vpbroadcastw(dst, xmm0);
4509     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4510     addptr(rsp, 64);
4511   } else {
4512     subptr(rsp, 64);
4513     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4514     subptr(rsp, 64);
4515     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4516     movdqu(xmm0, src);
4517     movdqu(xmm1, dst);
4518     Assembler::vpbroadcastw(xmm1, xmm0);
4519     movdqu(dst, xmm1);
4520     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4521     addptr(rsp, 64);
4522     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4523     addptr(rsp, 64);
4524   }
4525 }
4526 
4527 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4528   int dst_enc = dst->encoding();
4529   int nds_enc = nds->encoding();
4530   int src_enc = src->encoding();
4531   assert(dst_enc == nds_enc, "");
4532   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4533     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4534   } else if ((dst_enc < 16) && (src_enc < 16)) {
4535     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4536   } else if (src_enc < 16) {
4537     subptr(rsp, 64);
4538     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4539     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4540     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4541     movdqu(dst, xmm0);
4542     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4543     addptr(rsp, 64);
4544   } else if (dst_enc < 16) {
4545     subptr(rsp, 64);
4546     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4547     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4548     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4549     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4550     addptr(rsp, 64);
4551   } else {
4552     subptr(rsp, 64);
4553     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4554     subptr(rsp, 64);
4555     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4556     movdqu(xmm0, src);
4557     movdqu(xmm1, dst);
4558     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4559     movdqu(dst, xmm1);
4560     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4561     addptr(rsp, 64);
4562     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4563     addptr(rsp, 64);
4564   }
4565 }
4566 
4567 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4568   int dst_enc = dst->encoding();
4569   int nds_enc = nds->encoding();
4570   int src_enc = src->encoding();
4571   assert(dst_enc == nds_enc, "");
4572   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4573     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4574   } else if ((dst_enc < 16) && (src_enc < 16)) {
4575     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4576   } else if (src_enc < 16) {
4577     subptr(rsp, 64);
4578     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4579     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4580     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4581     movdqu(dst, xmm0);
4582     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4583     addptr(rsp, 64);
4584   } else if (dst_enc < 16) {
4585     subptr(rsp, 64);
4586     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4587     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4588     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4589     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4590     addptr(rsp, 64);
4591   } else {
4592     subptr(rsp, 64);
4593     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4594     subptr(rsp, 64);
4595     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4596     movdqu(xmm0, src);
4597     movdqu(xmm1, dst);
4598     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4599     movdqu(dst, xmm1);
4600     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4601     addptr(rsp, 64);
4602     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4603     addptr(rsp, 64);
4604   }
4605 }
4606 
4607 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4608   int dst_enc = dst->encoding();
4609   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4610     Assembler::vpmovzxbw(dst, src, vector_len);
4611   } else if (dst_enc < 16) {
4612     Assembler::vpmovzxbw(dst, src, vector_len);
4613   } else {
4614     subptr(rsp, 64);
4615     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4616     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4617     Assembler::vpmovzxbw(xmm0, src, vector_len);
4618     movdqu(dst, xmm0);
4619     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4620     addptr(rsp, 64);
4621   }
4622 }
4623 
4624 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4625   int src_enc = src->encoding();
4626   if (src_enc < 16) {
4627     Assembler::vpmovmskb(dst, src);
4628   } else {
4629     subptr(rsp, 64);
4630     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4631     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4632     Assembler::vpmovmskb(dst, xmm0);
4633     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4634     addptr(rsp, 64);
4635   }
4636 }
4637 
4638 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4639   int dst_enc = dst->encoding();
4640   int nds_enc = nds->encoding();
4641   int src_enc = src->encoding();
4642   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4643     Assembler::vpmullw(dst, nds, src, vector_len);
4644   } else if ((dst_enc < 16) && (src_enc < 16)) {
4645     Assembler::vpmullw(dst, dst, src, vector_len);
4646   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4647     // use nds as scratch for src
4648     evmovdqul(nds, src, Assembler::AVX_512bit);
4649     Assembler::vpmullw(dst, dst, nds, vector_len);
4650   } else if ((src_enc < 16) && (nds_enc < 16)) {
4651     // use nds as scratch for dst
4652     evmovdqul(nds, dst, Assembler::AVX_512bit);
4653     Assembler::vpmullw(nds, nds, src, vector_len);
4654     evmovdqul(dst, nds, Assembler::AVX_512bit);
4655   } else if (dst_enc < 16) {
4656     // use nds as scatch for xmm0 to hold src
4657     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4658     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4659     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4660     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4661   } else {
4662     // worse case scenario, all regs are in the upper bank
4663     subptr(rsp, 64);
4664     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4665     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4666     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4667     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4668     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4669     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4670     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4671     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4672     addptr(rsp, 64);
4673   }
4674 }
4675 
4676 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4677   int dst_enc = dst->encoding();
4678   int nds_enc = nds->encoding();
4679   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4680     Assembler::vpmullw(dst, nds, src, vector_len);
4681   } else if (dst_enc < 16) {
4682     Assembler::vpmullw(dst, dst, src, vector_len);
4683   } else if (nds_enc < 16) {
4684     // implies dst_enc in upper bank with src as scratch
4685     evmovdqul(nds, dst, Assembler::AVX_512bit);
4686     Assembler::vpmullw(nds, nds, src, vector_len);
4687     evmovdqul(dst, nds, Assembler::AVX_512bit);
4688   } else {
4689     // worse case scenario, all regs in upper bank
4690     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4691     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4692     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4693     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4694   }
4695 }
4696 
4697 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4698   int dst_enc = dst->encoding();
4699   int nds_enc = nds->encoding();
4700   int src_enc = src->encoding();
4701   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4702     Assembler::vpsubb(dst, nds, src, vector_len);
4703   } else if ((dst_enc < 16) && (src_enc < 16)) {
4704     Assembler::vpsubb(dst, dst, src, vector_len);
4705   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4706     // use nds as scratch for src
4707     evmovdqul(nds, src, Assembler::AVX_512bit);
4708     Assembler::vpsubb(dst, dst, nds, vector_len);
4709   } else if ((src_enc < 16) && (nds_enc < 16)) {
4710     // use nds as scratch for dst
4711     evmovdqul(nds, dst, Assembler::AVX_512bit);
4712     Assembler::vpsubb(nds, nds, src, vector_len);
4713     evmovdqul(dst, nds, Assembler::AVX_512bit);
4714   } else if (dst_enc < 16) {
4715     // use nds as scatch for xmm0 to hold src
4716     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4717     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4718     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4719     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4720   } else {
4721     // worse case scenario, all regs are in the upper bank
4722     subptr(rsp, 64);
4723     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4724     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4725     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4726     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4727     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4728     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4729     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4730     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4731     addptr(rsp, 64);
4732   }
4733 }
4734 
4735 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4736   int dst_enc = dst->encoding();
4737   int nds_enc = nds->encoding();
4738   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4739     Assembler::vpsubb(dst, nds, src, vector_len);
4740   } else if (dst_enc < 16) {
4741     Assembler::vpsubb(dst, dst, src, vector_len);
4742   } else if (nds_enc < 16) {
4743     // implies dst_enc in upper bank with src as scratch
4744     evmovdqul(nds, dst, Assembler::AVX_512bit);
4745     Assembler::vpsubb(nds, nds, src, vector_len);
4746     evmovdqul(dst, nds, Assembler::AVX_512bit);
4747   } else {
4748     // worse case scenario, all regs in upper bank
4749     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4750     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4751     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4752     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4753   }
4754 }
4755 
4756 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4757   int dst_enc = dst->encoding();
4758   int nds_enc = nds->encoding();
4759   int src_enc = src->encoding();
4760   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4761     Assembler::vpsubw(dst, nds, src, vector_len);
4762   } else if ((dst_enc < 16) && (src_enc < 16)) {
4763     Assembler::vpsubw(dst, dst, src, vector_len);
4764   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4765     // use nds as scratch for src
4766     evmovdqul(nds, src, Assembler::AVX_512bit);
4767     Assembler::vpsubw(dst, dst, nds, vector_len);
4768   } else if ((src_enc < 16) && (nds_enc < 16)) {
4769     // use nds as scratch for dst
4770     evmovdqul(nds, dst, Assembler::AVX_512bit);
4771     Assembler::vpsubw(nds, nds, src, vector_len);
4772     evmovdqul(dst, nds, Assembler::AVX_512bit);
4773   } else if (dst_enc < 16) {
4774     // use nds as scatch for xmm0 to hold src
4775     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4776     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4777     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4778     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4779   } else {
4780     // worse case scenario, all regs are in the upper bank
4781     subptr(rsp, 64);
4782     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4783     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4784     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4785     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4786     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4787     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4788     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4789     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4790     addptr(rsp, 64);
4791   }
4792 }
4793 
4794 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4795   int dst_enc = dst->encoding();
4796   int nds_enc = nds->encoding();
4797   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4798     Assembler::vpsubw(dst, nds, src, vector_len);
4799   } else if (dst_enc < 16) {
4800     Assembler::vpsubw(dst, dst, src, vector_len);
4801   } else if (nds_enc < 16) {
4802     // implies dst_enc in upper bank with src as scratch
4803     evmovdqul(nds, dst, Assembler::AVX_512bit);
4804     Assembler::vpsubw(nds, nds, src, vector_len);
4805     evmovdqul(dst, nds, Assembler::AVX_512bit);
4806   } else {
4807     // worse case scenario, all regs in upper bank
4808     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4809     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4810     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4811     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4812   }
4813 }
4814 
4815 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4816   int dst_enc = dst->encoding();
4817   int nds_enc = nds->encoding();
4818   int shift_enc = shift->encoding();
4819   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4820     Assembler::vpsraw(dst, nds, shift, vector_len);
4821   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4822     Assembler::vpsraw(dst, dst, shift, vector_len);
4823   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4824     // use nds_enc as scratch with shift
4825     evmovdqul(nds, shift, Assembler::AVX_512bit);
4826     Assembler::vpsraw(dst, dst, nds, vector_len);
4827   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4828     // use nds as scratch with dst
4829     evmovdqul(nds, dst, Assembler::AVX_512bit);
4830     Assembler::vpsraw(nds, nds, shift, vector_len);
4831     evmovdqul(dst, nds, Assembler::AVX_512bit);
4832   } else if (dst_enc < 16) {
4833     // use nds to save a copy of xmm0 and hold shift
4834     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4835     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4836     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4837     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4838   } else if (nds_enc < 16) {
4839     // use nds as dest as temps
4840     evmovdqul(nds, dst, Assembler::AVX_512bit);
4841     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4842     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4843     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4844     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4845     evmovdqul(dst, nds, Assembler::AVX_512bit);
4846   } else {
4847     // worse case scenario, all regs are in the upper bank
4848     subptr(rsp, 64);
4849     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4850     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4851     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4852     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4853     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4854     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4855     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4856     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4857     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4858     addptr(rsp, 64);
4859   }
4860 }
4861 
4862 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4863   int dst_enc = dst->encoding();
4864   int nds_enc = nds->encoding();
4865   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4866     Assembler::vpsraw(dst, nds, shift, vector_len);
4867   } else if (dst_enc < 16) {
4868     Assembler::vpsraw(dst, dst, shift, vector_len);
4869   } else if (nds_enc < 16) {
4870     // use nds as scratch
4871     evmovdqul(nds, dst, Assembler::AVX_512bit);
4872     Assembler::vpsraw(nds, nds, shift, vector_len);
4873     evmovdqul(dst, nds, Assembler::AVX_512bit);
4874   } else {
4875     // use nds as scratch for xmm0
4876     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4877     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4878     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4879     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4880   }
4881 }
4882 
4883 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4884   int dst_enc = dst->encoding();
4885   int nds_enc = nds->encoding();
4886   int shift_enc = shift->encoding();
4887   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4888     Assembler::vpsrlw(dst, nds, shift, vector_len);
4889   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4890     Assembler::vpsrlw(dst, dst, shift, vector_len);
4891   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4892     // use nds_enc as scratch with shift
4893     evmovdqul(nds, shift, Assembler::AVX_512bit);
4894     Assembler::vpsrlw(dst, dst, nds, vector_len);
4895   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4896     // use nds as scratch with dst
4897     evmovdqul(nds, dst, Assembler::AVX_512bit);
4898     Assembler::vpsrlw(nds, nds, shift, vector_len);
4899     evmovdqul(dst, nds, Assembler::AVX_512bit);
4900   } else if (dst_enc < 16) {
4901     // use nds to save a copy of xmm0 and hold shift
4902     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4903     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4904     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4905     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4906   } else if (nds_enc < 16) {
4907     // use nds as dest as temps
4908     evmovdqul(nds, dst, Assembler::AVX_512bit);
4909     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4910     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4911     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4912     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4913     evmovdqul(dst, nds, Assembler::AVX_512bit);
4914   } else {
4915     // worse case scenario, all regs are in the upper bank
4916     subptr(rsp, 64);
4917     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4918     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4919     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4920     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4921     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4922     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4923     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4924     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4925     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4926     addptr(rsp, 64);
4927   }
4928 }
4929 
4930 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4931   int dst_enc = dst->encoding();
4932   int nds_enc = nds->encoding();
4933   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4934     Assembler::vpsrlw(dst, nds, shift, vector_len);
4935   } else if (dst_enc < 16) {
4936     Assembler::vpsrlw(dst, dst, shift, vector_len);
4937   } else if (nds_enc < 16) {
4938     // use nds as scratch
4939     evmovdqul(nds, dst, Assembler::AVX_512bit);
4940     Assembler::vpsrlw(nds, nds, shift, vector_len);
4941     evmovdqul(dst, nds, Assembler::AVX_512bit);
4942   } else {
4943     // use nds as scratch for xmm0
4944     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4945     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4946     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4947     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4948   }
4949 }
4950 
4951 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4952   int dst_enc = dst->encoding();
4953   int nds_enc = nds->encoding();
4954   int shift_enc = shift->encoding();
4955   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4956     Assembler::vpsllw(dst, nds, shift, vector_len);
4957   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4958     Assembler::vpsllw(dst, dst, shift, vector_len);
4959   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4960     // use nds_enc as scratch with shift
4961     evmovdqul(nds, shift, Assembler::AVX_512bit);
4962     Assembler::vpsllw(dst, dst, nds, vector_len);
4963   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4964     // use nds as scratch with dst
4965     evmovdqul(nds, dst, Assembler::AVX_512bit);
4966     Assembler::vpsllw(nds, nds, shift, vector_len);
4967     evmovdqul(dst, nds, Assembler::AVX_512bit);
4968   } else if (dst_enc < 16) {
4969     // use nds to save a copy of xmm0 and hold shift
4970     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4971     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4972     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4973     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4974   } else if (nds_enc < 16) {
4975     // use nds as dest as temps
4976     evmovdqul(nds, dst, Assembler::AVX_512bit);
4977     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4978     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4979     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4980     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4981     evmovdqul(dst, nds, Assembler::AVX_512bit);
4982   } else {
4983     // worse case scenario, all regs are in the upper bank
4984     subptr(rsp, 64);
4985     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4986     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4987     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4988     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4989     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4990     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4991     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4992     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4993     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4994     addptr(rsp, 64);
4995   }
4996 }
4997 
4998 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4999   int dst_enc = dst->encoding();
5000   int nds_enc = nds->encoding();
5001   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
5002     Assembler::vpsllw(dst, nds, shift, vector_len);
5003   } else if (dst_enc < 16) {
5004     Assembler::vpsllw(dst, dst, shift, vector_len);
5005   } else if (nds_enc < 16) {
5006     // use nds as scratch
5007     evmovdqul(nds, dst, Assembler::AVX_512bit);
5008     Assembler::vpsllw(nds, nds, shift, vector_len);
5009     evmovdqul(dst, nds, Assembler::AVX_512bit);
5010   } else {
5011     // use nds as scratch for xmm0
5012     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
5013     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5014     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
5015     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5016   }
5017 }
5018 
5019 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
5020   int dst_enc = dst->encoding();
5021   int src_enc = src->encoding();
5022   if ((dst_enc < 16) && (src_enc < 16)) {
5023     Assembler::vptest(dst, src);
5024   } else if (src_enc < 16) {
5025     subptr(rsp, 64);
5026     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5027     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5028     Assembler::vptest(xmm0, src);
5029     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5030     addptr(rsp, 64);
5031   } else if (dst_enc < 16) {
5032     subptr(rsp, 64);
5033     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5034     evmovdqul(xmm0, src, Assembler::AVX_512bit);
5035     Assembler::vptest(dst, xmm0);
5036     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5037     addptr(rsp, 64);
5038   } else {
5039     subptr(rsp, 64);
5040     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5041     subptr(rsp, 64);
5042     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5043     movdqu(xmm0, src);
5044     movdqu(xmm1, dst);
5045     Assembler::vptest(xmm1, xmm0);
5046     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5047     addptr(rsp, 64);
5048     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5049     addptr(rsp, 64);
5050   }
5051 }
5052 
5053 // This instruction exists within macros, ergo we cannot control its input
5054 // when emitted through those patterns.
5055 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
5056   if (VM_Version::supports_avx512nobw()) {
5057     int dst_enc = dst->encoding();
5058     int src_enc = src->encoding();
5059     if (dst_enc == src_enc) {
5060       if (dst_enc < 16) {
5061         Assembler::punpcklbw(dst, src);
5062       } else {
5063         subptr(rsp, 64);
5064         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5066         Assembler::punpcklbw(xmm0, xmm0);
5067         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5068         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5069         addptr(rsp, 64);
5070       }
5071     } else {
5072       if ((src_enc < 16) && (dst_enc < 16)) {
5073         Assembler::punpcklbw(dst, src);
5074       } else if (src_enc < 16) {
5075         subptr(rsp, 64);
5076         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5078         Assembler::punpcklbw(xmm0, src);
5079         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5080         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5081         addptr(rsp, 64);
5082       } else if (dst_enc < 16) {
5083         subptr(rsp, 64);
5084         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5085         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5086         Assembler::punpcklbw(dst, xmm0);
5087         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5088         addptr(rsp, 64);
5089       } else {
5090         subptr(rsp, 64);
5091         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5092         subptr(rsp, 64);
5093         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5094         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5095         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5096         Assembler::punpcklbw(xmm0, xmm1);
5097         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5098         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5099         addptr(rsp, 64);
5100         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5101         addptr(rsp, 64);
5102       }
5103     }
5104   } else {
5105     Assembler::punpcklbw(dst, src);
5106   }
5107 }
5108 
5109 // This instruction exists within macros, ergo we cannot control its input
5110 // when emitted through those patterns.
5111 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5112   if (VM_Version::supports_avx512nobw()) {
5113     int dst_enc = dst->encoding();
5114     int src_enc = src->encoding();
5115     if (dst_enc == src_enc) {
5116       if (dst_enc < 16) {
5117         Assembler::pshuflw(dst, src, mode);
5118       } else {
5119         subptr(rsp, 64);
5120         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5121         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5122         Assembler::pshuflw(xmm0, xmm0, mode);
5123         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5124         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5125         addptr(rsp, 64);
5126       }
5127     } else {
5128       if ((src_enc < 16) && (dst_enc < 16)) {
5129         Assembler::pshuflw(dst, src, mode);
5130       } else if (src_enc < 16) {
5131         subptr(rsp, 64);
5132         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5133         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5134         Assembler::pshuflw(xmm0, src, mode);
5135         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5136         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5137         addptr(rsp, 64);
5138       } else if (dst_enc < 16) {
5139         subptr(rsp, 64);
5140         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5141         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5142         Assembler::pshuflw(dst, xmm0, mode);
5143         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5144         addptr(rsp, 64);
5145       } else {
5146         subptr(rsp, 64);
5147         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5148         subptr(rsp, 64);
5149         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5150         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5151         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5152         Assembler::pshuflw(xmm0, xmm1, mode);
5153         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5154         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5155         addptr(rsp, 64);
5156         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5157         addptr(rsp, 64);
5158       }
5159     }
5160   } else {
5161     Assembler::pshuflw(dst, src, mode);
5162   }
5163 }
5164 
5165 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5166   if (reachable(src)) {
5167     vandpd(dst, nds, as_Address(src), vector_len);
5168   } else {
5169     lea(rscratch1, src);
5170     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5171   }
5172 }
5173 
5174 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5175   if (reachable(src)) {
5176     vandps(dst, nds, as_Address(src), vector_len);
5177   } else {
5178     lea(rscratch1, src);
5179     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5180   }
5181 }
5182 
5183 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5184   if (reachable(src)) {
5185     vdivsd(dst, nds, as_Address(src));
5186   } else {
5187     lea(rscratch1, src);
5188     vdivsd(dst, nds, Address(rscratch1, 0));
5189   }
5190 }
5191 
5192 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5193   if (reachable(src)) {
5194     vdivss(dst, nds, as_Address(src));
5195   } else {
5196     lea(rscratch1, src);
5197     vdivss(dst, nds, Address(rscratch1, 0));
5198   }
5199 }
5200 
5201 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5202   if (reachable(src)) {
5203     vmulsd(dst, nds, as_Address(src));
5204   } else {
5205     lea(rscratch1, src);
5206     vmulsd(dst, nds, Address(rscratch1, 0));
5207   }
5208 }
5209 
5210 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5211   if (reachable(src)) {
5212     vmulss(dst, nds, as_Address(src));
5213   } else {
5214     lea(rscratch1, src);
5215     vmulss(dst, nds, Address(rscratch1, 0));
5216   }
5217 }
5218 
5219 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5220   if (reachable(src)) {
5221     vsubsd(dst, nds, as_Address(src));
5222   } else {
5223     lea(rscratch1, src);
5224     vsubsd(dst, nds, Address(rscratch1, 0));
5225   }
5226 }
5227 
5228 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5229   if (reachable(src)) {
5230     vsubss(dst, nds, as_Address(src));
5231   } else {
5232     lea(rscratch1, src);
5233     vsubss(dst, nds, Address(rscratch1, 0));
5234   }
5235 }
5236 
5237 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5238   int nds_enc = nds->encoding();
5239   int dst_enc = dst->encoding();
5240   bool dst_upper_bank = (dst_enc > 15);
5241   bool nds_upper_bank = (nds_enc > 15);
5242   if (VM_Version::supports_avx512novl() &&
5243       (nds_upper_bank || dst_upper_bank)) {
5244     if (dst_upper_bank) {
5245       subptr(rsp, 64);
5246       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5247       movflt(xmm0, nds);
5248       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5249       movflt(dst, xmm0);
5250       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5251       addptr(rsp, 64);
5252     } else {
5253       movflt(dst, nds);
5254       vxorps(dst, dst, src, Assembler::AVX_128bit);
5255     }
5256   } else {
5257     vxorps(dst, nds, src, Assembler::AVX_128bit);
5258   }
5259 }
5260 
5261 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5262   int nds_enc = nds->encoding();
5263   int dst_enc = dst->encoding();
5264   bool dst_upper_bank = (dst_enc > 15);
5265   bool nds_upper_bank = (nds_enc > 15);
5266   if (VM_Version::supports_avx512novl() &&
5267       (nds_upper_bank || dst_upper_bank)) {
5268     if (dst_upper_bank) {
5269       subptr(rsp, 64);
5270       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5271       movdbl(xmm0, nds);
5272       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5273       movdbl(dst, xmm0);
5274       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5275       addptr(rsp, 64);
5276     } else {
5277       movdbl(dst, nds);
5278       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5279     }
5280   } else {
5281     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5282   }
5283 }
5284 
5285 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5286   if (reachable(src)) {
5287     vxorpd(dst, nds, as_Address(src), vector_len);
5288   } else {
5289     lea(rscratch1, src);
5290     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5291   }
5292 }
5293 
5294 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5295   if (reachable(src)) {
5296     vxorps(dst, nds, as_Address(src), vector_len);
5297   } else {
5298     lea(rscratch1, src);
5299     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5300   }
5301 }
5302 
5303 
5304 //////////////////////////////////////////////////////////////////////////////////
5305 #if INCLUDE_ALL_GCS
5306 
5307 void MacroAssembler::g1_write_barrier_pre(Register obj,
5308                                           Register pre_val,
5309                                           Register thread,
5310                                           Register tmp,
5311                                           bool tosca_live,
5312                                           bool expand_call) {
5313 
5314   // If expand_call is true then we expand the call_VM_leaf macro
5315   // directly to skip generating the check by
5316   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5317 
5318 #ifdef _LP64
5319   assert(thread == r15_thread, "must be");
5320 #endif // _LP64
5321 
5322   Label done;
5323   Label runtime;
5324 
5325   assert(pre_val != noreg, "check this code");
5326 
5327   if (obj != noreg) {
5328     assert_different_registers(obj, pre_val, tmp);
5329     assert(pre_val != rax, "check this code");
5330   }
5331 
5332   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5333                                        SATBMarkQueue::byte_offset_of_active()));
5334   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5335                                        SATBMarkQueue::byte_offset_of_index()));
5336   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5337                                        SATBMarkQueue::byte_offset_of_buf()));
5338 
5339 
5340   // Is marking active?
5341   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5342     cmpl(in_progress, 0);
5343   } else {
5344     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5345     cmpb(in_progress, 0);
5346   }
5347   jcc(Assembler::equal, done);
5348 
5349   // Do we need to load the previous value?
5350   if (obj != noreg) {
5351     load_heap_oop(pre_val, Address(obj, 0));
5352   }
5353 
5354   // Is the previous value null?
5355   cmpptr(pre_val, (int32_t) NULL_WORD);
5356   jcc(Assembler::equal, done);
5357 
5358   // Can we store original value in the thread's buffer?
5359   // Is index == 0?
5360   // (The index field is typed as size_t.)
5361 
5362   movptr(tmp, index);                   // tmp := *index_adr
5363   cmpptr(tmp, 0);                       // tmp == 0?
5364   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5365 
5366   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5367   movptr(index, tmp);                   // *index_adr := tmp
5368   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5369 
5370   // Record the previous value
5371   movptr(Address(tmp, 0), pre_val);
5372   jmp(done);
5373 
5374   bind(runtime);
5375   // save the live input values
5376   if(tosca_live) push(rax);
5377 
5378   if (obj != noreg && obj != rax)
5379     push(obj);
5380 
5381   if (pre_val != rax)
5382     push(pre_val);
5383 
5384   // Calling the runtime using the regular call_VM_leaf mechanism generates
5385   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5386   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5387   //
5388   // If we care generating the pre-barrier without a frame (e.g. in the
5389   // intrinsified Reference.get() routine) then ebp might be pointing to
5390   // the caller frame and so this check will most likely fail at runtime.
5391   //
5392   // Expanding the call directly bypasses the generation of the check.
5393   // So when we do not have have a full interpreter frame on the stack
5394   // expand_call should be passed true.
5395 
5396   NOT_LP64( push(thread); )
5397 
5398   if (expand_call) {
5399     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5400     pass_arg1(this, thread);
5401     pass_arg0(this, pre_val);
5402     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5403   } else {
5404     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5405   }
5406 
5407   NOT_LP64( pop(thread); )
5408 
5409   // save the live input values
5410   if (pre_val != rax)
5411     pop(pre_val);
5412 
5413   if (obj != noreg && obj != rax)
5414     pop(obj);
5415 
5416   if(tosca_live) pop(rax);
5417 
5418   bind(done);
5419 }
5420 
5421 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5422                                            Register new_val,
5423                                            Register thread,
5424                                            Register tmp,
5425                                            Register tmp2) {
5426 #ifdef _LP64
5427   assert(thread == r15_thread, "must be");
5428 #endif // _LP64
5429 
5430   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5431                                        DirtyCardQueue::byte_offset_of_index()));
5432   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5433                                        DirtyCardQueue::byte_offset_of_buf()));
5434 
5435   CardTableModRefBS* ct =
5436     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5437   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5438 
5439   Label done;
5440   Label runtime;
5441 
5442   // Does store cross heap regions?
5443 
5444   movptr(tmp, store_addr);
5445   xorptr(tmp, new_val);
5446   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5447   jcc(Assembler::equal, done);
5448 
5449   // crosses regions, storing NULL?
5450 
5451   cmpptr(new_val, (int32_t) NULL_WORD);
5452   jcc(Assembler::equal, done);
5453 
5454   // storing region crossing non-NULL, is card already dirty?
5455 
5456   const Register card_addr = tmp;
5457   const Register cardtable = tmp2;
5458 
5459   movptr(card_addr, store_addr);
5460   shrptr(card_addr, CardTableModRefBS::card_shift);
5461   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5462   // a valid address and therefore is not properly handled by the relocation code.
5463   movptr(cardtable, (intptr_t)ct->byte_map_base);
5464   addptr(card_addr, cardtable);
5465 
5466   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5467   jcc(Assembler::equal, done);
5468 
5469   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5470   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5471   jcc(Assembler::equal, done);
5472 
5473 
5474   // storing a region crossing, non-NULL oop, card is clean.
5475   // dirty card and log.
5476 
5477   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5478 
5479   cmpl(queue_index, 0);
5480   jcc(Assembler::equal, runtime);
5481   subl(queue_index, wordSize);
5482   movptr(tmp2, buffer);
5483 #ifdef _LP64
5484   movslq(rscratch1, queue_index);
5485   addq(tmp2, rscratch1);
5486   movq(Address(tmp2, 0), card_addr);
5487 #else
5488   addl(tmp2, queue_index);
5489   movl(Address(tmp2, 0), card_addr);
5490 #endif
5491   jmp(done);
5492 
5493   bind(runtime);
5494   // save the live input values
5495   push(store_addr);
5496   push(new_val);
5497 #ifdef _LP64
5498   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5499 #else
5500   push(thread);
5501   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5502   pop(thread);
5503 #endif
5504   pop(new_val);
5505   pop(store_addr);
5506 
5507   bind(done);
5508 }
5509 
5510 #endif // INCLUDE_ALL_GCS
5511 //////////////////////////////////////////////////////////////////////////////////
5512 
5513 
5514 void MacroAssembler::store_check(Register obj, Address dst) {
5515   store_check(obj);
5516 }
5517 
5518 void MacroAssembler::store_check(Register obj) {
5519   // Does a store check for the oop in register obj. The content of
5520   // register obj is destroyed afterwards.
5521   BarrierSet* bs = Universe::heap()->barrier_set();
5522   assert(bs->kind() == BarrierSet::CardTableForRS ||
5523          bs->kind() == BarrierSet::CardTableExtension,
5524          "Wrong barrier set kind");
5525 
5526   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5527   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5528 
5529   shrptr(obj, CardTableModRefBS::card_shift);
5530 
5531   Address card_addr;
5532 
5533   // The calculation for byte_map_base is as follows:
5534   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5535   // So this essentially converts an address to a displacement and it will
5536   // never need to be relocated. On 64bit however the value may be too
5537   // large for a 32bit displacement.
5538   intptr_t disp = (intptr_t) ct->byte_map_base;
5539   if (is_simm32(disp)) {
5540     card_addr = Address(noreg, obj, Address::times_1, disp);
5541   } else {
5542     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5543     // displacement and done in a single instruction given favorable mapping and a
5544     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5545     // entry and that entry is not properly handled by the relocation code.
5546     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5547     Address index(noreg, obj, Address::times_1);
5548     card_addr = as_Address(ArrayAddress(cardtable, index));
5549   }
5550 
5551   int dirty = CardTableModRefBS::dirty_card_val();
5552   if (UseCondCardMark) {
5553     Label L_already_dirty;
5554     if (UseConcMarkSweepGC) {
5555       membar(Assembler::StoreLoad);
5556     }
5557     cmpb(card_addr, dirty);
5558     jcc(Assembler::equal, L_already_dirty);
5559     movb(card_addr, dirty);
5560     bind(L_already_dirty);
5561   } else {
5562     movb(card_addr, dirty);
5563   }
5564 }
5565 
5566 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5567   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5568 }
5569 
5570 // Force generation of a 4 byte immediate value even if it fits into 8bit
5571 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5572   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5573 }
5574 
5575 void MacroAssembler::subptr(Register dst, Register src) {
5576   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5577 }
5578 
5579 // C++ bool manipulation
5580 void MacroAssembler::testbool(Register dst) {
5581   if(sizeof(bool) == 1)
5582     testb(dst, 0xff);
5583   else if(sizeof(bool) == 2) {
5584     // testw implementation needed for two byte bools
5585     ShouldNotReachHere();
5586   } else if(sizeof(bool) == 4)
5587     testl(dst, dst);
5588   else
5589     // unsupported
5590     ShouldNotReachHere();
5591 }
5592 
5593 void MacroAssembler::testptr(Register dst, Register src) {
5594   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5595 }
5596 
5597 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5598 void MacroAssembler::tlab_allocate(Register obj,
5599                                    Register var_size_in_bytes,
5600                                    int con_size_in_bytes,
5601                                    Register t1,
5602                                    Register t2,
5603                                    Label& slow_case) {
5604   assert_different_registers(obj, t1, t2);
5605   assert_different_registers(obj, var_size_in_bytes, t1);
5606   Register end = t2;
5607   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5608 
5609   verify_tlab();
5610 
5611   NOT_LP64(get_thread(thread));
5612 
5613   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5614   if (var_size_in_bytes == noreg) {
5615     lea(end, Address(obj, con_size_in_bytes));
5616   } else {
5617     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5618   }
5619   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5620   jcc(Assembler::above, slow_case);
5621 
5622   // update the tlab top pointer
5623   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5624 
5625   // recover var_size_in_bytes if necessary
5626   if (var_size_in_bytes == end) {
5627     subptr(var_size_in_bytes, obj);
5628   }
5629   verify_tlab();
5630 }
5631 
5632 // Preserves rbx, and rdx.
5633 Register MacroAssembler::tlab_refill(Label& retry,
5634                                      Label& try_eden,
5635                                      Label& slow_case) {
5636   Register top = rax;
5637   Register t1  = rcx;
5638   Register t2  = rsi;
5639   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5640   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5641   Label do_refill, discard_tlab;
5642 
5643   if (!Universe::heap()->supports_inline_contig_alloc()) {
5644     // No allocation in the shared eden.
5645     jmp(slow_case);
5646   }
5647 
5648   NOT_LP64(get_thread(thread_reg));
5649 
5650   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5651   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5652 
5653   // calculate amount of free space
5654   subptr(t1, top);
5655   shrptr(t1, LogHeapWordSize);
5656 
5657   // Retain tlab and allocate object in shared space if
5658   // the amount free in the tlab is too large to discard.
5659   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5660   jcc(Assembler::lessEqual, discard_tlab);
5661 
5662   // Retain
5663   // %%% yuck as movptr...
5664   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5665   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5666   if (TLABStats) {
5667     // increment number of slow_allocations
5668     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5669   }
5670   jmp(try_eden);
5671 
5672   bind(discard_tlab);
5673   if (TLABStats) {
5674     // increment number of refills
5675     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5676     // accumulate wastage -- t1 is amount free in tlab
5677     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5678   }
5679 
5680   // if tlab is currently allocated (top or end != null) then
5681   // fill [top, end + alignment_reserve) with array object
5682   testptr(top, top);
5683   jcc(Assembler::zero, do_refill);
5684 
5685   // set up the mark word
5686   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5687   // set the length to the remaining space
5688   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5689   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5690   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5691   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5692   // set klass to intArrayKlass
5693   // dubious reloc why not an oop reloc?
5694   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5695   // store klass last.  concurrent gcs assumes klass length is valid if
5696   // klass field is not null.
5697   store_klass(top, t1);
5698 
5699   movptr(t1, top);
5700   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5701   incr_allocated_bytes(thread_reg, t1, 0);
5702 
5703   // refill the tlab with an eden allocation
5704   bind(do_refill);
5705   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5706   shlptr(t1, LogHeapWordSize);
5707   // allocate new tlab, address returned in top
5708   eden_allocate(top, t1, 0, t2, slow_case);
5709 
5710   // Check that t1 was preserved in eden_allocate.
5711 #ifdef ASSERT
5712   if (UseTLAB) {
5713     Label ok;
5714     Register tsize = rsi;
5715     assert_different_registers(tsize, thread_reg, t1);
5716     push(tsize);
5717     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5718     shlptr(tsize, LogHeapWordSize);
5719     cmpptr(t1, tsize);
5720     jcc(Assembler::equal, ok);
5721     STOP("assert(t1 != tlab size)");
5722     should_not_reach_here();
5723 
5724     bind(ok);
5725     pop(tsize);
5726   }
5727 #endif
5728   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5729   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5730   addptr(top, t1);
5731   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5732   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5733   verify_tlab();
5734   jmp(retry);
5735 
5736   return thread_reg; // for use by caller
5737 }
5738 
5739 void MacroAssembler::incr_allocated_bytes(Register thread,
5740                                           Register var_size_in_bytes,
5741                                           int con_size_in_bytes,
5742                                           Register t1) {
5743   if (!thread->is_valid()) {
5744 #ifdef _LP64
5745     thread = r15_thread;
5746 #else
5747     assert(t1->is_valid(), "need temp reg");
5748     thread = t1;
5749     get_thread(thread);
5750 #endif
5751   }
5752 
5753 #ifdef _LP64
5754   if (var_size_in_bytes->is_valid()) {
5755     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5756   } else {
5757     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5758   }
5759 #else
5760   if (var_size_in_bytes->is_valid()) {
5761     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5762   } else {
5763     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5764   }
5765   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5766 #endif
5767 }
5768 
5769 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5770   pusha();
5771 
5772   // if we are coming from c1, xmm registers may be live
5773   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5774   if (UseAVX > 2) {
5775     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5776   }
5777 
5778   if (UseSSE == 1)  {
5779     subptr(rsp, sizeof(jdouble)*8);
5780     for (int n = 0; n < 8; n++) {
5781       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5782     }
5783   } else if (UseSSE >= 2)  {
5784     if (UseAVX > 2) {
5785       push(rbx);
5786       movl(rbx, 0xffff);
5787       kmovwl(k1, rbx);
5788       pop(rbx);
5789     }
5790 #ifdef COMPILER2
5791     if (MaxVectorSize > 16) {
5792       if(UseAVX > 2) {
5793         // Save upper half of ZMM registers
5794         subptr(rsp, 32*num_xmm_regs);
5795         for (int n = 0; n < num_xmm_regs; n++) {
5796           vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
5797         }
5798       }
5799       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5800       // Save upper half of YMM registers
5801       subptr(rsp, 16*num_xmm_regs);
5802       for (int n = 0; n < num_xmm_regs; n++) {
5803         vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
5804       }
5805     }
5806 #endif
5807     // Save whole 128bit (16 bytes) XMM registers
5808     subptr(rsp, 16*num_xmm_regs);
5809 #ifdef _LP64
5810     if (VM_Version::supports_evex()) {
5811       for (int n = 0; n < num_xmm_regs; n++) {
5812         vextractf32x4h(Address(rsp, n*16), as_XMMRegister(n), 0);
5813       }
5814     } else {
5815       for (int n = 0; n < num_xmm_regs; n++) {
5816         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5817       }
5818     }
5819 #else
5820     for (int n = 0; n < num_xmm_regs; n++) {
5821       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5822     }
5823 #endif
5824   }
5825 
5826   // Preserve registers across runtime call
5827   int incoming_argument_and_return_value_offset = -1;
5828   if (num_fpu_regs_in_use > 1) {
5829     // Must preserve all other FPU regs (could alternatively convert
5830     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5831     // FPU state, but can not trust C compiler)
5832     NEEDS_CLEANUP;
5833     // NOTE that in this case we also push the incoming argument(s) to
5834     // the stack and restore it later; we also use this stack slot to
5835     // hold the return value from dsin, dcos etc.
5836     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5837       subptr(rsp, sizeof(jdouble));
5838       fstp_d(Address(rsp, 0));
5839     }
5840     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5841     for (int i = nb_args-1; i >= 0; i--) {
5842       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5843     }
5844   }
5845 
5846   subptr(rsp, nb_args*sizeof(jdouble));
5847   for (int i = 0; i < nb_args; i++) {
5848     fstp_d(Address(rsp, i*sizeof(jdouble)));
5849   }
5850 
5851 #ifdef _LP64
5852   if (nb_args > 0) {
5853     movdbl(xmm0, Address(rsp, 0));
5854   }
5855   if (nb_args > 1) {
5856     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5857   }
5858   assert(nb_args <= 2, "unsupported number of args");
5859 #endif // _LP64
5860 
5861   // NOTE: we must not use call_VM_leaf here because that requires a
5862   // complete interpreter frame in debug mode -- same bug as 4387334
5863   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5864   // do proper 64bit abi
5865 
5866   NEEDS_CLEANUP;
5867   // Need to add stack banging before this runtime call if it needs to
5868   // be taken; however, there is no generic stack banging routine at
5869   // the MacroAssembler level
5870 
5871   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5872 
5873 #ifdef _LP64
5874   movsd(Address(rsp, 0), xmm0);
5875   fld_d(Address(rsp, 0));
5876 #endif // _LP64
5877   addptr(rsp, sizeof(jdouble)*nb_args);
5878   if (num_fpu_regs_in_use > 1) {
5879     // Must save return value to stack and then restore entire FPU
5880     // stack except incoming arguments
5881     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5882     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5883       fld_d(Address(rsp, 0));
5884       addptr(rsp, sizeof(jdouble));
5885     }
5886     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5887     addptr(rsp, sizeof(jdouble)*nb_args);
5888   }
5889 
5890   if (UseSSE == 1)  {
5891     for (int n = 0; n < 8; n++) {
5892       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5893     }
5894     addptr(rsp, sizeof(jdouble)*8);
5895   } else if (UseSSE >= 2)  {
5896     // Restore whole 128bit (16 bytes) XMM registers
5897 #ifdef _LP64
5898   if (VM_Version::supports_evex()) {
5899     for (int n = 0; n < num_xmm_regs; n++) {
5900       vinsertf32x4h(as_XMMRegister(n), Address(rsp, n*16), 0);
5901     }
5902   } else {
5903     for (int n = 0; n < num_xmm_regs; n++) {
5904       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5905     }
5906   }
5907 #else
5908   for (int n = 0; n < num_xmm_regs; n++) {
5909     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5910   }
5911 #endif
5912     addptr(rsp, 16*num_xmm_regs);
5913 
5914 #ifdef COMPILER2
5915     if (MaxVectorSize > 16) {
5916       // Restore upper half of YMM registers.
5917       for (int n = 0; n < num_xmm_regs; n++) {
5918         vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
5919       }
5920       addptr(rsp, 16*num_xmm_regs);
5921       if(UseAVX > 2) {
5922         for (int n = 0; n < num_xmm_regs; n++) {
5923           vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
5924         }
5925         addptr(rsp, 32*num_xmm_regs);
5926       }
5927     }
5928 #endif
5929   }
5930   popa();
5931 }
5932 
5933 static const double     pi_4 =  0.7853981633974483;
5934 
5935 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5936   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5937   // was attempted in this code; unfortunately it appears that the
5938   // switch to 80-bit precision and back causes this to be
5939   // unprofitable compared with simply performing a runtime call if
5940   // the argument is out of the (-pi/4, pi/4) range.
5941 
5942   Register tmp = noreg;
5943   if (!VM_Version::supports_cmov()) {
5944     // fcmp needs a temporary so preserve rbx,
5945     tmp = rbx;
5946     push(tmp);
5947   }
5948 
5949   Label slow_case, done;
5950 
5951   ExternalAddress pi4_adr = (address)&pi_4;
5952   if (reachable(pi4_adr)) {
5953     // x ?<= pi/4
5954     fld_d(pi4_adr);
5955     fld_s(1);                // Stack:  X  PI/4  X
5956     fabs();                  // Stack: |X| PI/4  X
5957     fcmp(tmp);
5958     jcc(Assembler::above, slow_case);
5959 
5960     // fastest case: -pi/4 <= x <= pi/4
5961     switch(trig) {
5962     case 's':
5963       fsin();
5964       break;
5965     case 'c':
5966       fcos();
5967       break;
5968     case 't':
5969       ftan();
5970       break;
5971     default:
5972       assert(false, "bad intrinsic");
5973       break;
5974     }
5975     jmp(done);
5976   }
5977 
5978   // slow case: runtime call
5979   bind(slow_case);
5980 
5981   switch(trig) {
5982   case 's':
5983     {
5984       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
5985     }
5986     break;
5987   case 'c':
5988     {
5989       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
5990     }
5991     break;
5992   case 't':
5993     {
5994       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
5995     }
5996     break;
5997   default:
5998     assert(false, "bad intrinsic");
5999     break;
6000   }
6001 
6002   // Come here with result in F-TOS
6003   bind(done);
6004 
6005   if (tmp != noreg) {
6006     pop(tmp);
6007   }
6008 }
6009 
6010 
6011 // Look up the method for a megamorphic invokeinterface call.
6012 // The target method is determined by <intf_klass, itable_index>.
6013 // The receiver klass is in recv_klass.
6014 // On success, the result will be in method_result, and execution falls through.
6015 // On failure, execution transfers to the given label.
6016 void MacroAssembler::lookup_interface_method(Register recv_klass,
6017                                              Register intf_klass,
6018                                              RegisterOrConstant itable_index,
6019                                              Register method_result,
6020                                              Register scan_temp,
6021                                              Label& L_no_such_interface) {
6022   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
6023   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
6024          "caller must use same register for non-constant itable index as for method");
6025 
6026   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
6027   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
6028   int itentry_off = itableMethodEntry::method_offset_in_bytes();
6029   int scan_step   = itableOffsetEntry::size() * wordSize;
6030   int vte_size    = vtableEntry::size() * wordSize;
6031   Address::ScaleFactor times_vte_scale = Address::times_ptr;
6032   assert(vte_size == wordSize, "else adjust times_vte_scale");
6033 
6034   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
6035 
6036   // %%% Could store the aligned, prescaled offset in the klassoop.
6037   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
6038 
6039   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
6040   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
6041   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
6042 
6043   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
6044   //   if (scan->interface() == intf) {
6045   //     result = (klass + scan->offset() + itable_index);
6046   //   }
6047   // }
6048   Label search, found_method;
6049 
6050   for (int peel = 1; peel >= 0; peel--) {
6051     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
6052     cmpptr(intf_klass, method_result);
6053 
6054     if (peel) {
6055       jccb(Assembler::equal, found_method);
6056     } else {
6057       jccb(Assembler::notEqual, search);
6058       // (invert the test to fall through to found_method...)
6059     }
6060 
6061     if (!peel)  break;
6062 
6063     bind(search);
6064 
6065     // Check that the previous entry is non-null.  A null entry means that
6066     // the receiver class doesn't implement the interface, and wasn't the
6067     // same as when the caller was compiled.
6068     testptr(method_result, method_result);
6069     jcc(Assembler::zero, L_no_such_interface);
6070     addptr(scan_temp, scan_step);
6071   }
6072 
6073   bind(found_method);
6074 
6075   // Got a hit.
6076   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
6077   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
6078 }
6079 
6080 
6081 // virtual method calling
6082 void MacroAssembler::lookup_virtual_method(Register recv_klass,
6083                                            RegisterOrConstant vtable_index,
6084                                            Register method_result) {
6085   const int base = InstanceKlass::vtable_start_offset() * wordSize;
6086   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
6087   Address vtable_entry_addr(recv_klass,
6088                             vtable_index, Address::times_ptr,
6089                             base + vtableEntry::method_offset_in_bytes());
6090   movptr(method_result, vtable_entry_addr);
6091 }
6092 
6093 
6094 void MacroAssembler::check_klass_subtype(Register sub_klass,
6095                            Register super_klass,
6096                            Register temp_reg,
6097                            Label& L_success) {
6098   Label L_failure;
6099   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
6100   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
6101   bind(L_failure);
6102 }
6103 
6104 
6105 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
6106                                                    Register super_klass,
6107                                                    Register temp_reg,
6108                                                    Label* L_success,
6109                                                    Label* L_failure,
6110                                                    Label* L_slow_path,
6111                                         RegisterOrConstant super_check_offset) {
6112   assert_different_registers(sub_klass, super_klass, temp_reg);
6113   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
6114   if (super_check_offset.is_register()) {
6115     assert_different_registers(sub_klass, super_klass,
6116                                super_check_offset.as_register());
6117   } else if (must_load_sco) {
6118     assert(temp_reg != noreg, "supply either a temp or a register offset");
6119   }
6120 
6121   Label L_fallthrough;
6122   int label_nulls = 0;
6123   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6124   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6125   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6126   assert(label_nulls <= 1, "at most one NULL in the batch");
6127 
6128   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6129   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6130   Address super_check_offset_addr(super_klass, sco_offset);
6131 
6132   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6133   // range of a jccb.  If this routine grows larger, reconsider at
6134   // least some of these.
6135 #define local_jcc(assembler_cond, label)                                \
6136   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6137   else                             jcc( assembler_cond, label) /*omit semi*/
6138 
6139   // Hacked jmp, which may only be used just before L_fallthrough.
6140 #define final_jmp(label)                                                \
6141   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6142   else                            jmp(label)                /*omit semi*/
6143 
6144   // If the pointers are equal, we are done (e.g., String[] elements).
6145   // This self-check enables sharing of secondary supertype arrays among
6146   // non-primary types such as array-of-interface.  Otherwise, each such
6147   // type would need its own customized SSA.
6148   // We move this check to the front of the fast path because many
6149   // type checks are in fact trivially successful in this manner,
6150   // so we get a nicely predicted branch right at the start of the check.
6151   cmpptr(sub_klass, super_klass);
6152   local_jcc(Assembler::equal, *L_success);
6153 
6154   // Check the supertype display:
6155   if (must_load_sco) {
6156     // Positive movl does right thing on LP64.
6157     movl(temp_reg, super_check_offset_addr);
6158     super_check_offset = RegisterOrConstant(temp_reg);
6159   }
6160   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6161   cmpptr(super_klass, super_check_addr); // load displayed supertype
6162 
6163   // This check has worked decisively for primary supers.
6164   // Secondary supers are sought in the super_cache ('super_cache_addr').
6165   // (Secondary supers are interfaces and very deeply nested subtypes.)
6166   // This works in the same check above because of a tricky aliasing
6167   // between the super_cache and the primary super display elements.
6168   // (The 'super_check_addr' can address either, as the case requires.)
6169   // Note that the cache is updated below if it does not help us find
6170   // what we need immediately.
6171   // So if it was a primary super, we can just fail immediately.
6172   // Otherwise, it's the slow path for us (no success at this point).
6173 
6174   if (super_check_offset.is_register()) {
6175     local_jcc(Assembler::equal, *L_success);
6176     cmpl(super_check_offset.as_register(), sc_offset);
6177     if (L_failure == &L_fallthrough) {
6178       local_jcc(Assembler::equal, *L_slow_path);
6179     } else {
6180       local_jcc(Assembler::notEqual, *L_failure);
6181       final_jmp(*L_slow_path);
6182     }
6183   } else if (super_check_offset.as_constant() == sc_offset) {
6184     // Need a slow path; fast failure is impossible.
6185     if (L_slow_path == &L_fallthrough) {
6186       local_jcc(Assembler::equal, *L_success);
6187     } else {
6188       local_jcc(Assembler::notEqual, *L_slow_path);
6189       final_jmp(*L_success);
6190     }
6191   } else {
6192     // No slow path; it's a fast decision.
6193     if (L_failure == &L_fallthrough) {
6194       local_jcc(Assembler::equal, *L_success);
6195     } else {
6196       local_jcc(Assembler::notEqual, *L_failure);
6197       final_jmp(*L_success);
6198     }
6199   }
6200 
6201   bind(L_fallthrough);
6202 
6203 #undef local_jcc
6204 #undef final_jmp
6205 }
6206 
6207 
6208 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6209                                                    Register super_klass,
6210                                                    Register temp_reg,
6211                                                    Register temp2_reg,
6212                                                    Label* L_success,
6213                                                    Label* L_failure,
6214                                                    bool set_cond_codes) {
6215   assert_different_registers(sub_klass, super_klass, temp_reg);
6216   if (temp2_reg != noreg)
6217     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6218 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6219 
6220   Label L_fallthrough;
6221   int label_nulls = 0;
6222   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6223   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6224   assert(label_nulls <= 1, "at most one NULL in the batch");
6225 
6226   // a couple of useful fields in sub_klass:
6227   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6228   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6229   Address secondary_supers_addr(sub_klass, ss_offset);
6230   Address super_cache_addr(     sub_klass, sc_offset);
6231 
6232   // Do a linear scan of the secondary super-klass chain.
6233   // This code is rarely used, so simplicity is a virtue here.
6234   // The repne_scan instruction uses fixed registers, which we must spill.
6235   // Don't worry too much about pre-existing connections with the input regs.
6236 
6237   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6238   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6239 
6240   // Get super_klass value into rax (even if it was in rdi or rcx).
6241   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6242   if (super_klass != rax || UseCompressedOops) {
6243     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6244     mov(rax, super_klass);
6245   }
6246   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6247   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6248 
6249 #ifndef PRODUCT
6250   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6251   ExternalAddress pst_counter_addr((address) pst_counter);
6252   NOT_LP64(  incrementl(pst_counter_addr) );
6253   LP64_ONLY( lea(rcx, pst_counter_addr) );
6254   LP64_ONLY( incrementl(Address(rcx, 0)) );
6255 #endif //PRODUCT
6256 
6257   // We will consult the secondary-super array.
6258   movptr(rdi, secondary_supers_addr);
6259   // Load the array length.  (Positive movl does right thing on LP64.)
6260   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6261   // Skip to start of data.
6262   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6263 
6264   // Scan RCX words at [RDI] for an occurrence of RAX.
6265   // Set NZ/Z based on last compare.
6266   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6267   // not change flags (only scas instruction which is repeated sets flags).
6268   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6269 
6270     testptr(rax,rax); // Set Z = 0
6271     repne_scan();
6272 
6273   // Unspill the temp. registers:
6274   if (pushed_rdi)  pop(rdi);
6275   if (pushed_rcx)  pop(rcx);
6276   if (pushed_rax)  pop(rax);
6277 
6278   if (set_cond_codes) {
6279     // Special hack for the AD files:  rdi is guaranteed non-zero.
6280     assert(!pushed_rdi, "rdi must be left non-NULL");
6281     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6282   }
6283 
6284   if (L_failure == &L_fallthrough)
6285         jccb(Assembler::notEqual, *L_failure);
6286   else  jcc(Assembler::notEqual, *L_failure);
6287 
6288   // Success.  Cache the super we found and proceed in triumph.
6289   movptr(super_cache_addr, super_klass);
6290 
6291   if (L_success != &L_fallthrough) {
6292     jmp(*L_success);
6293   }
6294 
6295 #undef IS_A_TEMP
6296 
6297   bind(L_fallthrough);
6298 }
6299 
6300 
6301 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6302   if (VM_Version::supports_cmov()) {
6303     cmovl(cc, dst, src);
6304   } else {
6305     Label L;
6306     jccb(negate_condition(cc), L);
6307     movl(dst, src);
6308     bind(L);
6309   }
6310 }
6311 
6312 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6313   if (VM_Version::supports_cmov()) {
6314     cmovl(cc, dst, src);
6315   } else {
6316     Label L;
6317     jccb(negate_condition(cc), L);
6318     movl(dst, src);
6319     bind(L);
6320   }
6321 }
6322 
6323 void MacroAssembler::verify_oop(Register reg, const char* s) {
6324   if (!VerifyOops) return;
6325 
6326   // Pass register number to verify_oop_subroutine
6327   const char* b = NULL;
6328   {
6329     ResourceMark rm;
6330     stringStream ss;
6331     ss.print("verify_oop: %s: %s", reg->name(), s);
6332     b = code_string(ss.as_string());
6333   }
6334   BLOCK_COMMENT("verify_oop {");
6335 #ifdef _LP64
6336   push(rscratch1);                    // save r10, trashed by movptr()
6337 #endif
6338   push(rax);                          // save rax,
6339   push(reg);                          // pass register argument
6340   ExternalAddress buffer((address) b);
6341   // avoid using pushptr, as it modifies scratch registers
6342   // and our contract is not to modify anything
6343   movptr(rax, buffer.addr());
6344   push(rax);
6345   // call indirectly to solve generation ordering problem
6346   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6347   call(rax);
6348   // Caller pops the arguments (oop, message) and restores rax, r10
6349   BLOCK_COMMENT("} verify_oop");
6350 }
6351 
6352 
6353 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6354                                                       Register tmp,
6355                                                       int offset) {
6356   intptr_t value = *delayed_value_addr;
6357   if (value != 0)
6358     return RegisterOrConstant(value + offset);
6359 
6360   // load indirectly to solve generation ordering problem
6361   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6362 
6363 #ifdef ASSERT
6364   { Label L;
6365     testptr(tmp, tmp);
6366     if (WizardMode) {
6367       const char* buf = NULL;
6368       {
6369         ResourceMark rm;
6370         stringStream ss;
6371         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6372         buf = code_string(ss.as_string());
6373       }
6374       jcc(Assembler::notZero, L);
6375       STOP(buf);
6376     } else {
6377       jccb(Assembler::notZero, L);
6378       hlt();
6379     }
6380     bind(L);
6381   }
6382 #endif
6383 
6384   if (offset != 0)
6385     addptr(tmp, offset);
6386 
6387   return RegisterOrConstant(tmp);
6388 }
6389 
6390 
6391 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6392                                          int extra_slot_offset) {
6393   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6394   int stackElementSize = Interpreter::stackElementSize;
6395   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6396 #ifdef ASSERT
6397   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6398   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6399 #endif
6400   Register             scale_reg    = noreg;
6401   Address::ScaleFactor scale_factor = Address::no_scale;
6402   if (arg_slot.is_constant()) {
6403     offset += arg_slot.as_constant() * stackElementSize;
6404   } else {
6405     scale_reg    = arg_slot.as_register();
6406     scale_factor = Address::times(stackElementSize);
6407   }
6408   offset += wordSize;           // return PC is on stack
6409   return Address(rsp, scale_reg, scale_factor, offset);
6410 }
6411 
6412 
6413 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6414   if (!VerifyOops) return;
6415 
6416   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6417   // Pass register number to verify_oop_subroutine
6418   const char* b = NULL;
6419   {
6420     ResourceMark rm;
6421     stringStream ss;
6422     ss.print("verify_oop_addr: %s", s);
6423     b = code_string(ss.as_string());
6424   }
6425 #ifdef _LP64
6426   push(rscratch1);                    // save r10, trashed by movptr()
6427 #endif
6428   push(rax);                          // save rax,
6429   // addr may contain rsp so we will have to adjust it based on the push
6430   // we just did (and on 64 bit we do two pushes)
6431   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6432   // stores rax into addr which is backwards of what was intended.
6433   if (addr.uses(rsp)) {
6434     lea(rax, addr);
6435     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6436   } else {
6437     pushptr(addr);
6438   }
6439 
6440   ExternalAddress buffer((address) b);
6441   // pass msg argument
6442   // avoid using pushptr, as it modifies scratch registers
6443   // and our contract is not to modify anything
6444   movptr(rax, buffer.addr());
6445   push(rax);
6446 
6447   // call indirectly to solve generation ordering problem
6448   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6449   call(rax);
6450   // Caller pops the arguments (addr, message) and restores rax, r10.
6451 }
6452 
6453 void MacroAssembler::verify_tlab() {
6454 #ifdef ASSERT
6455   if (UseTLAB && VerifyOops) {
6456     Label next, ok;
6457     Register t1 = rsi;
6458     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6459 
6460     push(t1);
6461     NOT_LP64(push(thread_reg));
6462     NOT_LP64(get_thread(thread_reg));
6463 
6464     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6465     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6466     jcc(Assembler::aboveEqual, next);
6467     STOP("assert(top >= start)");
6468     should_not_reach_here();
6469 
6470     bind(next);
6471     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6472     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6473     jcc(Assembler::aboveEqual, ok);
6474     STOP("assert(top <= end)");
6475     should_not_reach_here();
6476 
6477     bind(ok);
6478     NOT_LP64(pop(thread_reg));
6479     pop(t1);
6480   }
6481 #endif
6482 }
6483 
6484 class ControlWord {
6485  public:
6486   int32_t _value;
6487 
6488   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6489   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6490   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6491   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6492   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6493   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6494   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6495   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6496 
6497   void print() const {
6498     // rounding control
6499     const char* rc;
6500     switch (rounding_control()) {
6501       case 0: rc = "round near"; break;
6502       case 1: rc = "round down"; break;
6503       case 2: rc = "round up  "; break;
6504       case 3: rc = "chop      "; break;
6505     };
6506     // precision control
6507     const char* pc;
6508     switch (precision_control()) {
6509       case 0: pc = "24 bits "; break;
6510       case 1: pc = "reserved"; break;
6511       case 2: pc = "53 bits "; break;
6512       case 3: pc = "64 bits "; break;
6513     };
6514     // flags
6515     char f[9];
6516     f[0] = ' ';
6517     f[1] = ' ';
6518     f[2] = (precision   ()) ? 'P' : 'p';
6519     f[3] = (underflow   ()) ? 'U' : 'u';
6520     f[4] = (overflow    ()) ? 'O' : 'o';
6521     f[5] = (zero_divide ()) ? 'Z' : 'z';
6522     f[6] = (denormalized()) ? 'D' : 'd';
6523     f[7] = (invalid     ()) ? 'I' : 'i';
6524     f[8] = '\x0';
6525     // output
6526     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6527   }
6528 
6529 };
6530 
6531 class StatusWord {
6532  public:
6533   int32_t _value;
6534 
6535   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6536   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6537   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6538   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6539   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6540   int  top() const                     { return  (_value >> 11) & 7      ; }
6541   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6542   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6543   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6544   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6545   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6546   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6547   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6548   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6549 
6550   void print() const {
6551     // condition codes
6552     char c[5];
6553     c[0] = (C3()) ? '3' : '-';
6554     c[1] = (C2()) ? '2' : '-';
6555     c[2] = (C1()) ? '1' : '-';
6556     c[3] = (C0()) ? '0' : '-';
6557     c[4] = '\x0';
6558     // flags
6559     char f[9];
6560     f[0] = (error_status()) ? 'E' : '-';
6561     f[1] = (stack_fault ()) ? 'S' : '-';
6562     f[2] = (precision   ()) ? 'P' : '-';
6563     f[3] = (underflow   ()) ? 'U' : '-';
6564     f[4] = (overflow    ()) ? 'O' : '-';
6565     f[5] = (zero_divide ()) ? 'Z' : '-';
6566     f[6] = (denormalized()) ? 'D' : '-';
6567     f[7] = (invalid     ()) ? 'I' : '-';
6568     f[8] = '\x0';
6569     // output
6570     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6571   }
6572 
6573 };
6574 
6575 class TagWord {
6576  public:
6577   int32_t _value;
6578 
6579   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6580 
6581   void print() const {
6582     printf("%04x", _value & 0xFFFF);
6583   }
6584 
6585 };
6586 
6587 class FPU_Register {
6588  public:
6589   int32_t _m0;
6590   int32_t _m1;
6591   int16_t _ex;
6592 
6593   bool is_indefinite() const           {
6594     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6595   }
6596 
6597   void print() const {
6598     char  sign = (_ex < 0) ? '-' : '+';
6599     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6600     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6601   };
6602 
6603 };
6604 
6605 class FPU_State {
6606  public:
6607   enum {
6608     register_size       = 10,
6609     number_of_registers =  8,
6610     register_mask       =  7
6611   };
6612 
6613   ControlWord  _control_word;
6614   StatusWord   _status_word;
6615   TagWord      _tag_word;
6616   int32_t      _error_offset;
6617   int32_t      _error_selector;
6618   int32_t      _data_offset;
6619   int32_t      _data_selector;
6620   int8_t       _register[register_size * number_of_registers];
6621 
6622   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6623   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6624 
6625   const char* tag_as_string(int tag) const {
6626     switch (tag) {
6627       case 0: return "valid";
6628       case 1: return "zero";
6629       case 2: return "special";
6630       case 3: return "empty";
6631     }
6632     ShouldNotReachHere();
6633     return NULL;
6634   }
6635 
6636   void print() const {
6637     // print computation registers
6638     { int t = _status_word.top();
6639       for (int i = 0; i < number_of_registers; i++) {
6640         int j = (i - t) & register_mask;
6641         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6642         st(j)->print();
6643         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6644       }
6645     }
6646     printf("\n");
6647     // print control registers
6648     printf("ctrl = "); _control_word.print(); printf("\n");
6649     printf("stat = "); _status_word .print(); printf("\n");
6650     printf("tags = "); _tag_word    .print(); printf("\n");
6651   }
6652 
6653 };
6654 
6655 class Flag_Register {
6656  public:
6657   int32_t _value;
6658 
6659   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6660   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6661   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6662   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6663   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6664   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6665   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6666 
6667   void print() const {
6668     // flags
6669     char f[8];
6670     f[0] = (overflow       ()) ? 'O' : '-';
6671     f[1] = (direction      ()) ? 'D' : '-';
6672     f[2] = (sign           ()) ? 'S' : '-';
6673     f[3] = (zero           ()) ? 'Z' : '-';
6674     f[4] = (auxiliary_carry()) ? 'A' : '-';
6675     f[5] = (parity         ()) ? 'P' : '-';
6676     f[6] = (carry          ()) ? 'C' : '-';
6677     f[7] = '\x0';
6678     // output
6679     printf("%08x  flags = %s", _value, f);
6680   }
6681 
6682 };
6683 
6684 class IU_Register {
6685  public:
6686   int32_t _value;
6687 
6688   void print() const {
6689     printf("%08x  %11d", _value, _value);
6690   }
6691 
6692 };
6693 
6694 class IU_State {
6695  public:
6696   Flag_Register _eflags;
6697   IU_Register   _rdi;
6698   IU_Register   _rsi;
6699   IU_Register   _rbp;
6700   IU_Register   _rsp;
6701   IU_Register   _rbx;
6702   IU_Register   _rdx;
6703   IU_Register   _rcx;
6704   IU_Register   _rax;
6705 
6706   void print() const {
6707     // computation registers
6708     printf("rax,  = "); _rax.print(); printf("\n");
6709     printf("rbx,  = "); _rbx.print(); printf("\n");
6710     printf("rcx  = "); _rcx.print(); printf("\n");
6711     printf("rdx  = "); _rdx.print(); printf("\n");
6712     printf("rdi  = "); _rdi.print(); printf("\n");
6713     printf("rsi  = "); _rsi.print(); printf("\n");
6714     printf("rbp,  = "); _rbp.print(); printf("\n");
6715     printf("rsp  = "); _rsp.print(); printf("\n");
6716     printf("\n");
6717     // control registers
6718     printf("flgs = "); _eflags.print(); printf("\n");
6719   }
6720 };
6721 
6722 
6723 class CPU_State {
6724  public:
6725   FPU_State _fpu_state;
6726   IU_State  _iu_state;
6727 
6728   void print() const {
6729     printf("--------------------------------------------------\n");
6730     _iu_state .print();
6731     printf("\n");
6732     _fpu_state.print();
6733     printf("--------------------------------------------------\n");
6734   }
6735 
6736 };
6737 
6738 
6739 static void _print_CPU_state(CPU_State* state) {
6740   state->print();
6741 };
6742 
6743 
6744 void MacroAssembler::print_CPU_state() {
6745   push_CPU_state();
6746   push(rsp);                // pass CPU state
6747   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6748   addptr(rsp, wordSize);       // discard argument
6749   pop_CPU_state();
6750 }
6751 
6752 
6753 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6754   static int counter = 0;
6755   FPU_State* fs = &state->_fpu_state;
6756   counter++;
6757   // For leaf calls, only verify that the top few elements remain empty.
6758   // We only need 1 empty at the top for C2 code.
6759   if( stack_depth < 0 ) {
6760     if( fs->tag_for_st(7) != 3 ) {
6761       printf("FPR7 not empty\n");
6762       state->print();
6763       assert(false, "error");
6764       return false;
6765     }
6766     return true;                // All other stack states do not matter
6767   }
6768 
6769   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6770          "bad FPU control word");
6771 
6772   // compute stack depth
6773   int i = 0;
6774   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6775   int d = i;
6776   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6777   // verify findings
6778   if (i != FPU_State::number_of_registers) {
6779     // stack not contiguous
6780     printf("%s: stack not contiguous at ST%d\n", s, i);
6781     state->print();
6782     assert(false, "error");
6783     return false;
6784   }
6785   // check if computed stack depth corresponds to expected stack depth
6786   if (stack_depth < 0) {
6787     // expected stack depth is -stack_depth or less
6788     if (d > -stack_depth) {
6789       // too many elements on the stack
6790       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6791       state->print();
6792       assert(false, "error");
6793       return false;
6794     }
6795   } else {
6796     // expected stack depth is stack_depth
6797     if (d != stack_depth) {
6798       // wrong stack depth
6799       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6800       state->print();
6801       assert(false, "error");
6802       return false;
6803     }
6804   }
6805   // everything is cool
6806   return true;
6807 }
6808 
6809 
6810 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6811   if (!VerifyFPU) return;
6812   push_CPU_state();
6813   push(rsp);                // pass CPU state
6814   ExternalAddress msg((address) s);
6815   // pass message string s
6816   pushptr(msg.addr());
6817   push(stack_depth);        // pass stack depth
6818   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6819   addptr(rsp, 3 * wordSize);   // discard arguments
6820   // check for error
6821   { Label L;
6822     testl(rax, rax);
6823     jcc(Assembler::notZero, L);
6824     int3();                  // break if error condition
6825     bind(L);
6826   }
6827   pop_CPU_state();
6828 }
6829 
6830 void MacroAssembler::restore_cpu_control_state_after_jni() {
6831   // Either restore the MXCSR register after returning from the JNI Call
6832   // or verify that it wasn't changed (with -Xcheck:jni flag).
6833   if (VM_Version::supports_sse()) {
6834     if (RestoreMXCSROnJNICalls) {
6835       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6836     } else if (CheckJNICalls) {
6837       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6838     }
6839   }
6840   if (VM_Version::supports_avx()) {
6841     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6842     vzeroupper();
6843   }
6844 
6845 #ifndef _LP64
6846   // Either restore the x87 floating pointer control word after returning
6847   // from the JNI call or verify that it wasn't changed.
6848   if (CheckJNICalls) {
6849     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6850   }
6851 #endif // _LP64
6852 }
6853 
6854 
6855 void MacroAssembler::load_klass(Register dst, Register src) {
6856 #ifdef _LP64
6857   if (UseCompressedClassPointers) {
6858     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6859     decode_klass_not_null(dst);
6860   } else
6861 #endif
6862     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6863 }
6864 
6865 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6866   load_klass(dst, src);
6867   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6868 }
6869 
6870 void MacroAssembler::store_klass(Register dst, Register src) {
6871 #ifdef _LP64
6872   if (UseCompressedClassPointers) {
6873     encode_klass_not_null(src);
6874     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6875   } else
6876 #endif
6877     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6878 }
6879 
6880 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6881 #ifdef _LP64
6882   // FIXME: Must change all places where we try to load the klass.
6883   if (UseCompressedOops) {
6884     movl(dst, src);
6885     decode_heap_oop(dst);
6886   } else
6887 #endif
6888     movptr(dst, src);
6889 }
6890 
6891 // Doesn't do verfication, generates fixed size code
6892 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6893 #ifdef _LP64
6894   if (UseCompressedOops) {
6895     movl(dst, src);
6896     decode_heap_oop_not_null(dst);
6897   } else
6898 #endif
6899     movptr(dst, src);
6900 }
6901 
6902 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6903 #ifdef _LP64
6904   if (UseCompressedOops) {
6905     assert(!dst.uses(src), "not enough registers");
6906     encode_heap_oop(src);
6907     movl(dst, src);
6908   } else
6909 #endif
6910     movptr(dst, src);
6911 }
6912 
6913 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6914   assert_different_registers(src1, tmp);
6915 #ifdef _LP64
6916   if (UseCompressedOops) {
6917     bool did_push = false;
6918     if (tmp == noreg) {
6919       tmp = rax;
6920       push(tmp);
6921       did_push = true;
6922       assert(!src2.uses(rsp), "can't push");
6923     }
6924     load_heap_oop(tmp, src2);
6925     cmpptr(src1, tmp);
6926     if (did_push)  pop(tmp);
6927   } else
6928 #endif
6929     cmpptr(src1, src2);
6930 }
6931 
6932 // Used for storing NULLs.
6933 void MacroAssembler::store_heap_oop_null(Address dst) {
6934 #ifdef _LP64
6935   if (UseCompressedOops) {
6936     movl(dst, (int32_t)NULL_WORD);
6937   } else {
6938     movslq(dst, (int32_t)NULL_WORD);
6939   }
6940 #else
6941   movl(dst, (int32_t)NULL_WORD);
6942 #endif
6943 }
6944 
6945 #ifdef _LP64
6946 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6947   if (UseCompressedClassPointers) {
6948     // Store to klass gap in destination
6949     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6950   }
6951 }
6952 
6953 #ifdef ASSERT
6954 void MacroAssembler::verify_heapbase(const char* msg) {
6955   assert (UseCompressedOops, "should be compressed");
6956   assert (Universe::heap() != NULL, "java heap should be initialized");
6957   if (CheckCompressedOops) {
6958     Label ok;
6959     push(rscratch1); // cmpptr trashes rscratch1
6960     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6961     jcc(Assembler::equal, ok);
6962     STOP(msg);
6963     bind(ok);
6964     pop(rscratch1);
6965   }
6966 }
6967 #endif
6968 
6969 // Algorithm must match oop.inline.hpp encode_heap_oop.
6970 void MacroAssembler::encode_heap_oop(Register r) {
6971 #ifdef ASSERT
6972   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6973 #endif
6974   verify_oop(r, "broken oop in encode_heap_oop");
6975   if (Universe::narrow_oop_base() == NULL) {
6976     if (Universe::narrow_oop_shift() != 0) {
6977       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6978       shrq(r, LogMinObjAlignmentInBytes);
6979     }
6980     return;
6981   }
6982   testq(r, r);
6983   cmovq(Assembler::equal, r, r12_heapbase);
6984   subq(r, r12_heapbase);
6985   shrq(r, LogMinObjAlignmentInBytes);
6986 }
6987 
6988 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6989 #ifdef ASSERT
6990   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6991   if (CheckCompressedOops) {
6992     Label ok;
6993     testq(r, r);
6994     jcc(Assembler::notEqual, ok);
6995     STOP("null oop passed to encode_heap_oop_not_null");
6996     bind(ok);
6997   }
6998 #endif
6999   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7000   if (Universe::narrow_oop_base() != NULL) {
7001     subq(r, r12_heapbase);
7002   }
7003   if (Universe::narrow_oop_shift() != 0) {
7004     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7005     shrq(r, LogMinObjAlignmentInBytes);
7006   }
7007 }
7008 
7009 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7010 #ifdef ASSERT
7011   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7012   if (CheckCompressedOops) {
7013     Label ok;
7014     testq(src, src);
7015     jcc(Assembler::notEqual, ok);
7016     STOP("null oop passed to encode_heap_oop_not_null2");
7017     bind(ok);
7018   }
7019 #endif
7020   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7021   if (dst != src) {
7022     movq(dst, src);
7023   }
7024   if (Universe::narrow_oop_base() != NULL) {
7025     subq(dst, r12_heapbase);
7026   }
7027   if (Universe::narrow_oop_shift() != 0) {
7028     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7029     shrq(dst, LogMinObjAlignmentInBytes);
7030   }
7031 }
7032 
7033 void  MacroAssembler::decode_heap_oop(Register r) {
7034 #ifdef ASSERT
7035   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7036 #endif
7037   if (Universe::narrow_oop_base() == NULL) {
7038     if (Universe::narrow_oop_shift() != 0) {
7039       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7040       shlq(r, LogMinObjAlignmentInBytes);
7041     }
7042   } else {
7043     Label done;
7044     shlq(r, LogMinObjAlignmentInBytes);
7045     jccb(Assembler::equal, done);
7046     addq(r, r12_heapbase);
7047     bind(done);
7048   }
7049   verify_oop(r, "broken oop in decode_heap_oop");
7050 }
7051 
7052 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7053   // Note: it will change flags
7054   assert (UseCompressedOops, "should only be used for compressed headers");
7055   assert (Universe::heap() != NULL, "java heap should be initialized");
7056   // Cannot assert, unverified entry point counts instructions (see .ad file)
7057   // vtableStubs also counts instructions in pd_code_size_limit.
7058   // Also do not verify_oop as this is called by verify_oop.
7059   if (Universe::narrow_oop_shift() != 0) {
7060     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7061     shlq(r, LogMinObjAlignmentInBytes);
7062     if (Universe::narrow_oop_base() != NULL) {
7063       addq(r, r12_heapbase);
7064     }
7065   } else {
7066     assert (Universe::narrow_oop_base() == NULL, "sanity");
7067   }
7068 }
7069 
7070 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7071   // Note: it will change flags
7072   assert (UseCompressedOops, "should only be used for compressed headers");
7073   assert (Universe::heap() != NULL, "java heap should be initialized");
7074   // Cannot assert, unverified entry point counts instructions (see .ad file)
7075   // vtableStubs also counts instructions in pd_code_size_limit.
7076   // Also do not verify_oop as this is called by verify_oop.
7077   if (Universe::narrow_oop_shift() != 0) {
7078     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7079     if (LogMinObjAlignmentInBytes == Address::times_8) {
7080       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7081     } else {
7082       if (dst != src) {
7083         movq(dst, src);
7084       }
7085       shlq(dst, LogMinObjAlignmentInBytes);
7086       if (Universe::narrow_oop_base() != NULL) {
7087         addq(dst, r12_heapbase);
7088       }
7089     }
7090   } else {
7091     assert (Universe::narrow_oop_base() == NULL, "sanity");
7092     if (dst != src) {
7093       movq(dst, src);
7094     }
7095   }
7096 }
7097 
7098 void MacroAssembler::encode_klass_not_null(Register r) {
7099   if (Universe::narrow_klass_base() != NULL) {
7100     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7101     assert(r != r12_heapbase, "Encoding a klass in r12");
7102     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7103     subq(r, r12_heapbase);
7104   }
7105   if (Universe::narrow_klass_shift() != 0) {
7106     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7107     shrq(r, LogKlassAlignmentInBytes);
7108   }
7109   if (Universe::narrow_klass_base() != NULL) {
7110     reinit_heapbase();
7111   }
7112 }
7113 
7114 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7115   if (dst == src) {
7116     encode_klass_not_null(src);
7117   } else {
7118     if (Universe::narrow_klass_base() != NULL) {
7119       mov64(dst, (int64_t)Universe::narrow_klass_base());
7120       negq(dst);
7121       addq(dst, src);
7122     } else {
7123       movptr(dst, src);
7124     }
7125     if (Universe::narrow_klass_shift() != 0) {
7126       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7127       shrq(dst, LogKlassAlignmentInBytes);
7128     }
7129   }
7130 }
7131 
7132 // Function instr_size_for_decode_klass_not_null() counts the instructions
7133 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7134 // when (Universe::heap() != NULL).  Hence, if the instructions they
7135 // generate change, then this method needs to be updated.
7136 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7137   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7138   if (Universe::narrow_klass_base() != NULL) {
7139     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7140     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7141   } else {
7142     // longest load decode klass function, mov64, leaq
7143     return 16;
7144   }
7145 }
7146 
7147 // !!! If the instructions that get generated here change then function
7148 // instr_size_for_decode_klass_not_null() needs to get updated.
7149 void  MacroAssembler::decode_klass_not_null(Register r) {
7150   // Note: it will change flags
7151   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7152   assert(r != r12_heapbase, "Decoding a klass in r12");
7153   // Cannot assert, unverified entry point counts instructions (see .ad file)
7154   // vtableStubs also counts instructions in pd_code_size_limit.
7155   // Also do not verify_oop as this is called by verify_oop.
7156   if (Universe::narrow_klass_shift() != 0) {
7157     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7158     shlq(r, LogKlassAlignmentInBytes);
7159   }
7160   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7161   if (Universe::narrow_klass_base() != NULL) {
7162     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7163     addq(r, r12_heapbase);
7164     reinit_heapbase();
7165   }
7166 }
7167 
7168 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7169   // Note: it will change flags
7170   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7171   if (dst == src) {
7172     decode_klass_not_null(dst);
7173   } else {
7174     // Cannot assert, unverified entry point counts instructions (see .ad file)
7175     // vtableStubs also counts instructions in pd_code_size_limit.
7176     // Also do not verify_oop as this is called by verify_oop.
7177     mov64(dst, (int64_t)Universe::narrow_klass_base());
7178     if (Universe::narrow_klass_shift() != 0) {
7179       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7180       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7181       leaq(dst, Address(dst, src, Address::times_8, 0));
7182     } else {
7183       addq(dst, src);
7184     }
7185   }
7186 }
7187 
7188 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7189   assert (UseCompressedOops, "should only be used for compressed headers");
7190   assert (Universe::heap() != NULL, "java heap should be initialized");
7191   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7192   int oop_index = oop_recorder()->find_index(obj);
7193   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7194   mov_narrow_oop(dst, oop_index, rspec);
7195 }
7196 
7197 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7198   assert (UseCompressedOops, "should only be used for compressed headers");
7199   assert (Universe::heap() != NULL, "java heap should be initialized");
7200   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7201   int oop_index = oop_recorder()->find_index(obj);
7202   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7203   mov_narrow_oop(dst, oop_index, rspec);
7204 }
7205 
7206 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7207   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7208   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7209   int klass_index = oop_recorder()->find_index(k);
7210   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7211   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7212 }
7213 
7214 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7215   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7216   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7217   int klass_index = oop_recorder()->find_index(k);
7218   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7219   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7220 }
7221 
7222 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7223   assert (UseCompressedOops, "should only be used for compressed headers");
7224   assert (Universe::heap() != NULL, "java heap should be initialized");
7225   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7226   int oop_index = oop_recorder()->find_index(obj);
7227   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7228   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7229 }
7230 
7231 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7232   assert (UseCompressedOops, "should only be used for compressed headers");
7233   assert (Universe::heap() != NULL, "java heap should be initialized");
7234   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7235   int oop_index = oop_recorder()->find_index(obj);
7236   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7237   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7238 }
7239 
7240 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7241   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7242   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7243   int klass_index = oop_recorder()->find_index(k);
7244   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7245   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7246 }
7247 
7248 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7249   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7250   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7251   int klass_index = oop_recorder()->find_index(k);
7252   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7253   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7254 }
7255 
7256 void MacroAssembler::reinit_heapbase() {
7257   if (UseCompressedOops || UseCompressedClassPointers) {
7258     if (Universe::heap() != NULL) {
7259       if (Universe::narrow_oop_base() == NULL) {
7260         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7261       } else {
7262         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7263       }
7264     } else {
7265       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7266     }
7267   }
7268 }
7269 
7270 #endif // _LP64
7271 
7272 
7273 // C2 compiled method's prolog code.
7274 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7275 
7276   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7277   // NativeJump::patch_verified_entry will be able to patch out the entry
7278   // code safely. The push to verify stack depth is ok at 5 bytes,
7279   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7280   // stack bang then we must use the 6 byte frame allocation even if
7281   // we have no frame. :-(
7282   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7283 
7284   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7285   // Remove word for return addr
7286   framesize -= wordSize;
7287   stack_bang_size -= wordSize;
7288 
7289   // Calls to C2R adapters often do not accept exceptional returns.
7290   // We require that their callers must bang for them.  But be careful, because
7291   // some VM calls (such as call site linkage) can use several kilobytes of
7292   // stack.  But the stack safety zone should account for that.
7293   // See bugs 4446381, 4468289, 4497237.
7294   if (stack_bang_size > 0) {
7295     generate_stack_overflow_check(stack_bang_size);
7296 
7297     // We always push rbp, so that on return to interpreter rbp, will be
7298     // restored correctly and we can correct the stack.
7299     push(rbp);
7300     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7301     if (PreserveFramePointer) {
7302       mov(rbp, rsp);
7303     }
7304     // Remove word for ebp
7305     framesize -= wordSize;
7306 
7307     // Create frame
7308     if (framesize) {
7309       subptr(rsp, framesize);
7310     }
7311   } else {
7312     // Create frame (force generation of a 4 byte immediate value)
7313     subptr_imm32(rsp, framesize);
7314 
7315     // Save RBP register now.
7316     framesize -= wordSize;
7317     movptr(Address(rsp, framesize), rbp);
7318     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7319     if (PreserveFramePointer) {
7320       movptr(rbp, rsp);
7321       if (framesize > 0) {
7322         addptr(rbp, framesize);
7323       }
7324     }
7325   }
7326 
7327   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7328     framesize -= wordSize;
7329     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7330   }
7331 
7332 #ifndef _LP64
7333   // If method sets FPU control word do it now
7334   if (fp_mode_24b) {
7335     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7336   }
7337   if (UseSSE >= 2 && VerifyFPU) {
7338     verify_FPU(0, "FPU stack must be clean on entry");
7339   }
7340 #endif
7341 
7342 #ifdef ASSERT
7343   if (VerifyStackAtCalls) {
7344     Label L;
7345     push(rax);
7346     mov(rax, rsp);
7347     andptr(rax, StackAlignmentInBytes-1);
7348     cmpptr(rax, StackAlignmentInBytes-wordSize);
7349     pop(rax);
7350     jcc(Assembler::equal, L);
7351     STOP("Stack is not properly aligned!");
7352     bind(L);
7353   }
7354 #endif
7355 
7356 }
7357 
7358 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
7359   // cnt - number of qwords (8-byte words).
7360   // base - start address, qword aligned.
7361   assert(base==rdi, "base register must be edi for rep stos");
7362   assert(tmp==rax,   "tmp register must be eax for rep stos");
7363   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7364 
7365   xorptr(tmp, tmp);
7366   if (UseFastStosb) {
7367     shlptr(cnt,3); // convert to number of bytes
7368     rep_stosb();
7369   } else {
7370     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
7371     rep_stos();
7372   }
7373 }
7374 
7375 #ifdef COMPILER2
7376 
7377 // IndexOf for constant substrings with size >= 8 chars
7378 // which don't need to be loaded through stack.
7379 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7380                                       Register cnt1, Register cnt2,
7381                                       int int_cnt2,  Register result,
7382                                       XMMRegister vec, Register tmp,
7383                                       int ae) {
7384   ShortBranchVerifier sbv(this);
7385   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7386   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7387   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7388 
7389   // This method uses the pcmpestri instruction with bound registers
7390   //   inputs:
7391   //     xmm - substring
7392   //     rax - substring length (elements count)
7393   //     mem - scanned string
7394   //     rdx - string length (elements count)
7395   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7396   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7397   //   outputs:
7398   //     rcx - matched index in string
7399   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7400   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7401   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7402   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7403   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7404 
7405   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7406         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7407         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7408 
7409   // Note, inline_string_indexOf() generates checks:
7410   // if (substr.count > string.count) return -1;
7411   // if (substr.count == 0) return 0;
7412   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7413 
7414   // Load substring.
7415   if (ae == StrIntrinsicNode::UL) {
7416     pmovzxbw(vec, Address(str2, 0));
7417   } else {
7418     movdqu(vec, Address(str2, 0));
7419   }
7420   movl(cnt2, int_cnt2);
7421   movptr(result, str1); // string addr
7422 
7423   if (int_cnt2 > stride) {
7424     jmpb(SCAN_TO_SUBSTR);
7425 
7426     // Reload substr for rescan, this code
7427     // is executed only for large substrings (> 8 chars)
7428     bind(RELOAD_SUBSTR);
7429     if (ae == StrIntrinsicNode::UL) {
7430       pmovzxbw(vec, Address(str2, 0));
7431     } else {
7432       movdqu(vec, Address(str2, 0));
7433     }
7434     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7435 
7436     bind(RELOAD_STR);
7437     // We came here after the beginning of the substring was
7438     // matched but the rest of it was not so we need to search
7439     // again. Start from the next element after the previous match.
7440 
7441     // cnt2 is number of substring reminding elements and
7442     // cnt1 is number of string reminding elements when cmp failed.
7443     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7444     subl(cnt1, cnt2);
7445     addl(cnt1, int_cnt2);
7446     movl(cnt2, int_cnt2); // Now restore cnt2
7447 
7448     decrementl(cnt1);     // Shift to next element
7449     cmpl(cnt1, cnt2);
7450     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7451 
7452     addptr(result, (1<<scale1));
7453 
7454   } // (int_cnt2 > 8)
7455 
7456   // Scan string for start of substr in 16-byte vectors
7457   bind(SCAN_TO_SUBSTR);
7458   pcmpestri(vec, Address(result, 0), mode);
7459   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7460   subl(cnt1, stride);
7461   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7462   cmpl(cnt1, cnt2);
7463   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7464   addptr(result, 16);
7465   jmpb(SCAN_TO_SUBSTR);
7466 
7467   // Found a potential substr
7468   bind(FOUND_CANDIDATE);
7469   // Matched whole vector if first element matched (tmp(rcx) == 0).
7470   if (int_cnt2 == stride) {
7471     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7472   } else { // int_cnt2 > 8
7473     jccb(Assembler::overflow, FOUND_SUBSTR);
7474   }
7475   // After pcmpestri tmp(rcx) contains matched element index
7476   // Compute start addr of substr
7477   lea(result, Address(result, tmp, scale1));
7478 
7479   // Make sure string is still long enough
7480   subl(cnt1, tmp);
7481   cmpl(cnt1, cnt2);
7482   if (int_cnt2 == stride) {
7483     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7484   } else { // int_cnt2 > 8
7485     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7486   }
7487   // Left less then substring.
7488 
7489   bind(RET_NOT_FOUND);
7490   movl(result, -1);
7491   jmpb(EXIT);
7492 
7493   if (int_cnt2 > stride) {
7494     // This code is optimized for the case when whole substring
7495     // is matched if its head is matched.
7496     bind(MATCH_SUBSTR_HEAD);
7497     pcmpestri(vec, Address(result, 0), mode);
7498     // Reload only string if does not match
7499     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7500 
7501     Label CONT_SCAN_SUBSTR;
7502     // Compare the rest of substring (> 8 chars).
7503     bind(FOUND_SUBSTR);
7504     // First 8 chars are already matched.
7505     negptr(cnt2);
7506     addptr(cnt2, stride);
7507 
7508     bind(SCAN_SUBSTR);
7509     subl(cnt1, stride);
7510     cmpl(cnt2, -stride); // Do not read beyond substring
7511     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7512     // Back-up strings to avoid reading beyond substring:
7513     // cnt1 = cnt1 - cnt2 + 8
7514     addl(cnt1, cnt2); // cnt2 is negative
7515     addl(cnt1, stride);
7516     movl(cnt2, stride); negptr(cnt2);
7517     bind(CONT_SCAN_SUBSTR);
7518     if (int_cnt2 < (int)G) {
7519       int tail_off1 = int_cnt2<<scale1;
7520       int tail_off2 = int_cnt2<<scale2;
7521       if (ae == StrIntrinsicNode::UL) {
7522         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7523       } else {
7524         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7525       }
7526       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7527     } else {
7528       // calculate index in register to avoid integer overflow (int_cnt2*2)
7529       movl(tmp, int_cnt2);
7530       addptr(tmp, cnt2);
7531       if (ae == StrIntrinsicNode::UL) {
7532         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7533       } else {
7534         movdqu(vec, Address(str2, tmp, scale2, 0));
7535       }
7536       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7537     }
7538     // Need to reload strings pointers if not matched whole vector
7539     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7540     addptr(cnt2, stride);
7541     jcc(Assembler::negative, SCAN_SUBSTR);
7542     // Fall through if found full substring
7543 
7544   } // (int_cnt2 > 8)
7545 
7546   bind(RET_FOUND);
7547   // Found result if we matched full small substring.
7548   // Compute substr offset
7549   subptr(result, str1);
7550   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7551     shrl(result, 1); // index
7552   }
7553   bind(EXIT);
7554 
7555 } // string_indexofC8
7556 
7557 // Small strings are loaded through stack if they cross page boundary.
7558 void MacroAssembler::string_indexof(Register str1, Register str2,
7559                                     Register cnt1, Register cnt2,
7560                                     int int_cnt2,  Register result,
7561                                     XMMRegister vec, Register tmp,
7562                                     int ae) {
7563   ShortBranchVerifier sbv(this);
7564   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7565   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7566   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7567 
7568   //
7569   // int_cnt2 is length of small (< 8 chars) constant substring
7570   // or (-1) for non constant substring in which case its length
7571   // is in cnt2 register.
7572   //
7573   // Note, inline_string_indexOf() generates checks:
7574   // if (substr.count > string.count) return -1;
7575   // if (substr.count == 0) return 0;
7576   //
7577   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7578   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7579   // This method uses the pcmpestri instruction with bound registers
7580   //   inputs:
7581   //     xmm - substring
7582   //     rax - substring length (elements count)
7583   //     mem - scanned string
7584   //     rdx - string length (elements count)
7585   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7586   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7587   //   outputs:
7588   //     rcx - matched index in string
7589   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7590   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7591   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7592   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7593 
7594   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7595         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7596         FOUND_CANDIDATE;
7597 
7598   { //========================================================
7599     // We don't know where these strings are located
7600     // and we can't read beyond them. Load them through stack.
7601     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7602 
7603     movptr(tmp, rsp); // save old SP
7604 
7605     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7606       if (int_cnt2 == (1>>scale2)) { // One byte
7607         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7608         load_unsigned_byte(result, Address(str2, 0));
7609         movdl(vec, result); // move 32 bits
7610       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7611         // Not enough header space in 32-bit VM: 12+3 = 15.
7612         movl(result, Address(str2, -1));
7613         shrl(result, 8);
7614         movdl(vec, result); // move 32 bits
7615       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7616         load_unsigned_short(result, Address(str2, 0));
7617         movdl(vec, result); // move 32 bits
7618       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7619         movdl(vec, Address(str2, 0)); // move 32 bits
7620       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7621         movq(vec, Address(str2, 0));  // move 64 bits
7622       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7623         // Array header size is 12 bytes in 32-bit VM
7624         // + 6 bytes for 3 chars == 18 bytes,
7625         // enough space to load vec and shift.
7626         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7627         if (ae == StrIntrinsicNode::UL) {
7628           int tail_off = int_cnt2-8;
7629           pmovzxbw(vec, Address(str2, tail_off));
7630           psrldq(vec, -2*tail_off);
7631         }
7632         else {
7633           int tail_off = int_cnt2*(1<<scale2);
7634           movdqu(vec, Address(str2, tail_off-16));
7635           psrldq(vec, 16-tail_off);
7636         }
7637       }
7638     } else { // not constant substring
7639       cmpl(cnt2, stride);
7640       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7641 
7642       // We can read beyond string if srt+16 does not cross page boundary
7643       // since heaps are aligned and mapped by pages.
7644       assert(os::vm_page_size() < (int)G, "default page should be small");
7645       movl(result, str2); // We need only low 32 bits
7646       andl(result, (os::vm_page_size()-1));
7647       cmpl(result, (os::vm_page_size()-16));
7648       jccb(Assembler::belowEqual, CHECK_STR);
7649 
7650       // Move small strings to stack to allow load 16 bytes into vec.
7651       subptr(rsp, 16);
7652       int stk_offset = wordSize-(1<<scale2);
7653       push(cnt2);
7654 
7655       bind(COPY_SUBSTR);
7656       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7657         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7658         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7659       } else if (ae == StrIntrinsicNode::UU) {
7660         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7661         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7662       }
7663       decrement(cnt2);
7664       jccb(Assembler::notZero, COPY_SUBSTR);
7665 
7666       pop(cnt2);
7667       movptr(str2, rsp);  // New substring address
7668     } // non constant
7669 
7670     bind(CHECK_STR);
7671     cmpl(cnt1, stride);
7672     jccb(Assembler::aboveEqual, BIG_STRINGS);
7673 
7674     // Check cross page boundary.
7675     movl(result, str1); // We need only low 32 bits
7676     andl(result, (os::vm_page_size()-1));
7677     cmpl(result, (os::vm_page_size()-16));
7678     jccb(Assembler::belowEqual, BIG_STRINGS);
7679 
7680     subptr(rsp, 16);
7681     int stk_offset = -(1<<scale1);
7682     if (int_cnt2 < 0) { // not constant
7683       push(cnt2);
7684       stk_offset += wordSize;
7685     }
7686     movl(cnt2, cnt1);
7687 
7688     bind(COPY_STR);
7689     if (ae == StrIntrinsicNode::LL) {
7690       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7691       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7692     } else {
7693       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7694       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7695     }
7696     decrement(cnt2);
7697     jccb(Assembler::notZero, COPY_STR);
7698 
7699     if (int_cnt2 < 0) { // not constant
7700       pop(cnt2);
7701     }
7702     movptr(str1, rsp);  // New string address
7703 
7704     bind(BIG_STRINGS);
7705     // Load substring.
7706     if (int_cnt2 < 0) { // -1
7707       if (ae == StrIntrinsicNode::UL) {
7708         pmovzxbw(vec, Address(str2, 0));
7709       } else {
7710         movdqu(vec, Address(str2, 0));
7711       }
7712       push(cnt2);       // substr count
7713       push(str2);       // substr addr
7714       push(str1);       // string addr
7715     } else {
7716       // Small (< 8 chars) constant substrings are loaded already.
7717       movl(cnt2, int_cnt2);
7718     }
7719     push(tmp);  // original SP
7720 
7721   } // Finished loading
7722 
7723   //========================================================
7724   // Start search
7725   //
7726 
7727   movptr(result, str1); // string addr
7728 
7729   if (int_cnt2  < 0) {  // Only for non constant substring
7730     jmpb(SCAN_TO_SUBSTR);
7731 
7732     // SP saved at sp+0
7733     // String saved at sp+1*wordSize
7734     // Substr saved at sp+2*wordSize
7735     // Substr count saved at sp+3*wordSize
7736 
7737     // Reload substr for rescan, this code
7738     // is executed only for large substrings (> 8 chars)
7739     bind(RELOAD_SUBSTR);
7740     movptr(str2, Address(rsp, 2*wordSize));
7741     movl(cnt2, Address(rsp, 3*wordSize));
7742     if (ae == StrIntrinsicNode::UL) {
7743       pmovzxbw(vec, Address(str2, 0));
7744     } else {
7745       movdqu(vec, Address(str2, 0));
7746     }
7747     // We came here after the beginning of the substring was
7748     // matched but the rest of it was not so we need to search
7749     // again. Start from the next element after the previous match.
7750     subptr(str1, result); // Restore counter
7751     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7752       shrl(str1, 1);
7753     }
7754     addl(cnt1, str1);
7755     decrementl(cnt1);   // Shift to next element
7756     cmpl(cnt1, cnt2);
7757     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7758 
7759     addptr(result, (1<<scale1));
7760   } // non constant
7761 
7762   // Scan string for start of substr in 16-byte vectors
7763   bind(SCAN_TO_SUBSTR);
7764   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7765   pcmpestri(vec, Address(result, 0), mode);
7766   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7767   subl(cnt1, stride);
7768   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7769   cmpl(cnt1, cnt2);
7770   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7771   addptr(result, 16);
7772 
7773   bind(ADJUST_STR);
7774   cmpl(cnt1, stride); // Do not read beyond string
7775   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7776   // Back-up string to avoid reading beyond string.
7777   lea(result, Address(result, cnt1, scale1, -16));
7778   movl(cnt1, stride);
7779   jmpb(SCAN_TO_SUBSTR);
7780 
7781   // Found a potential substr
7782   bind(FOUND_CANDIDATE);
7783   // After pcmpestri tmp(rcx) contains matched element index
7784 
7785   // Make sure string is still long enough
7786   subl(cnt1, tmp);
7787   cmpl(cnt1, cnt2);
7788   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7789   // Left less then substring.
7790 
7791   bind(RET_NOT_FOUND);
7792   movl(result, -1);
7793   jmpb(CLEANUP);
7794 
7795   bind(FOUND_SUBSTR);
7796   // Compute start addr of substr
7797   lea(result, Address(result, tmp, scale1));
7798   if (int_cnt2 > 0) { // Constant substring
7799     // Repeat search for small substring (< 8 chars)
7800     // from new point without reloading substring.
7801     // Have to check that we don't read beyond string.
7802     cmpl(tmp, stride-int_cnt2);
7803     jccb(Assembler::greater, ADJUST_STR);
7804     // Fall through if matched whole substring.
7805   } else { // non constant
7806     assert(int_cnt2 == -1, "should be != 0");
7807 
7808     addl(tmp, cnt2);
7809     // Found result if we matched whole substring.
7810     cmpl(tmp, stride);
7811     jccb(Assembler::lessEqual, RET_FOUND);
7812 
7813     // Repeat search for small substring (<= 8 chars)
7814     // from new point 'str1' without reloading substring.
7815     cmpl(cnt2, stride);
7816     // Have to check that we don't read beyond string.
7817     jccb(Assembler::lessEqual, ADJUST_STR);
7818 
7819     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7820     // Compare the rest of substring (> 8 chars).
7821     movptr(str1, result);
7822 
7823     cmpl(tmp, cnt2);
7824     // First 8 chars are already matched.
7825     jccb(Assembler::equal, CHECK_NEXT);
7826 
7827     bind(SCAN_SUBSTR);
7828     pcmpestri(vec, Address(str1, 0), mode);
7829     // Need to reload strings pointers if not matched whole vector
7830     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7831 
7832     bind(CHECK_NEXT);
7833     subl(cnt2, stride);
7834     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7835     addptr(str1, 16);
7836     if (ae == StrIntrinsicNode::UL) {
7837       addptr(str2, 8);
7838     } else {
7839       addptr(str2, 16);
7840     }
7841     subl(cnt1, stride);
7842     cmpl(cnt2, stride); // Do not read beyond substring
7843     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7844     // Back-up strings to avoid reading beyond substring.
7845 
7846     if (ae == StrIntrinsicNode::UL) {
7847       lea(str2, Address(str2, cnt2, scale2, -8));
7848       lea(str1, Address(str1, cnt2, scale1, -16));
7849     } else {
7850       lea(str2, Address(str2, cnt2, scale2, -16));
7851       lea(str1, Address(str1, cnt2, scale1, -16));
7852     }
7853     subl(cnt1, cnt2);
7854     movl(cnt2, stride);
7855     addl(cnt1, stride);
7856     bind(CONT_SCAN_SUBSTR);
7857     if (ae == StrIntrinsicNode::UL) {
7858       pmovzxbw(vec, Address(str2, 0));
7859     } else {
7860       movdqu(vec, Address(str2, 0));
7861     }
7862     jmpb(SCAN_SUBSTR);
7863 
7864     bind(RET_FOUND_LONG);
7865     movptr(str1, Address(rsp, wordSize));
7866   } // non constant
7867 
7868   bind(RET_FOUND);
7869   // Compute substr offset
7870   subptr(result, str1);
7871   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7872     shrl(result, 1); // index
7873   }
7874   bind(CLEANUP);
7875   pop(rsp); // restore SP
7876 
7877 } // string_indexof
7878 
7879 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7880                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7881   ShortBranchVerifier sbv(this);
7882   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7883   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7884 
7885   int stride = 8;
7886 
7887   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7888         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7889         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7890         FOUND_SEQ_CHAR, DONE_LABEL;
7891 
7892   movptr(result, str1);
7893   if (UseAVX >= 2) {
7894     cmpl(cnt1, stride);
7895     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7896     cmpl(cnt1, 2*stride);
7897     jccb(Assembler::less, SCAN_TO_8_CHAR_INIT);
7898     movdl(vec1, ch);
7899     vpbroadcastw(vec1, vec1);
7900     vpxor(vec2, vec2);
7901     movl(tmp, cnt1);
7902     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7903     andl(cnt1,0x0000000F);  //tail count (in chars)
7904 
7905     bind(SCAN_TO_16_CHAR_LOOP);
7906     vmovdqu(vec3, Address(result, 0));
7907     vpcmpeqw(vec3, vec3, vec1, 1);
7908     vptest(vec2, vec3);
7909     jcc(Assembler::carryClear, FOUND_CHAR);
7910     addptr(result, 32);
7911     subl(tmp, 2*stride);
7912     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7913     jmp(SCAN_TO_8_CHAR);
7914     bind(SCAN_TO_8_CHAR_INIT);
7915     movdl(vec1, ch);
7916     pshuflw(vec1, vec1, 0x00);
7917     pshufd(vec1, vec1, 0);
7918     pxor(vec2, vec2);
7919   }
7920   bind(SCAN_TO_8_CHAR);
7921   cmpl(cnt1, stride);
7922   if (UseAVX >= 2) {
7923     jccb(Assembler::less, SCAN_TO_CHAR);
7924   } else {
7925     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7926     movdl(vec1, ch);
7927     pshuflw(vec1, vec1, 0x00);
7928     pshufd(vec1, vec1, 0);
7929     pxor(vec2, vec2);
7930   }
7931   movl(tmp, cnt1);
7932   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7933   andl(cnt1,0x00000007);  //tail count (in chars)
7934 
7935   bind(SCAN_TO_8_CHAR_LOOP);
7936   movdqu(vec3, Address(result, 0));
7937   pcmpeqw(vec3, vec1);
7938   ptest(vec2, vec3);
7939   jcc(Assembler::carryClear, FOUND_CHAR);
7940   addptr(result, 16);
7941   subl(tmp, stride);
7942   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7943   bind(SCAN_TO_CHAR);
7944   testl(cnt1, cnt1);
7945   jcc(Assembler::zero, RET_NOT_FOUND);
7946   bind(SCAN_TO_CHAR_LOOP);
7947   load_unsigned_short(tmp, Address(result, 0));
7948   cmpl(ch, tmp);
7949   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7950   addptr(result, 2);
7951   subl(cnt1, 1);
7952   jccb(Assembler::zero, RET_NOT_FOUND);
7953   jmp(SCAN_TO_CHAR_LOOP);
7954 
7955   bind(RET_NOT_FOUND);
7956   movl(result, -1);
7957   jmpb(DONE_LABEL);
7958 
7959   bind(FOUND_CHAR);
7960   if (UseAVX >= 2) {
7961     vpmovmskb(tmp, vec3);
7962   } else {
7963     pmovmskb(tmp, vec3);
7964   }
7965   bsfl(ch, tmp);
7966   addl(result, ch);
7967 
7968   bind(FOUND_SEQ_CHAR);
7969   subptr(result, str1);
7970   shrl(result, 1);
7971 
7972   bind(DONE_LABEL);
7973 } // string_indexof_char
7974 
7975 // helper function for string_compare
7976 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7977                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7978                                         Address::ScaleFactor scale2, Register index, int ae) {
7979   if (ae == StrIntrinsicNode::LL) {
7980     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7981     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7982   } else if (ae == StrIntrinsicNode::UU) {
7983     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7984     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7985   } else {
7986     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7987     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7988   }
7989 }
7990 
7991 // Compare strings, used for char[] and byte[].
7992 void MacroAssembler::string_compare(Register str1, Register str2,
7993                                     Register cnt1, Register cnt2, Register result,
7994                                     XMMRegister vec1, int ae) {
7995   ShortBranchVerifier sbv(this);
7996   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7997   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7998   Address::ScaleFactor scale, scale1, scale2;
7999 
8000   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8001     shrl(cnt2, 1);
8002   }
8003   // Compute the minimum of the string lengths and the
8004   // difference of the string lengths (stack).
8005   // Do the conditional move stuff
8006   movl(result, cnt1);
8007   subl(cnt1, cnt2);
8008   push(cnt1);
8009   cmov32(Assembler::lessEqual, cnt2, result);
8010 
8011   // Is the minimum length zero?
8012   testl(cnt2, cnt2);
8013   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8014   if (ae == StrIntrinsicNode::LL) {
8015     // Load first bytes
8016     load_unsigned_byte(result, Address(str1, 0));
8017     load_unsigned_byte(cnt1, Address(str2, 0));
8018   } else if (ae == StrIntrinsicNode::UU) {
8019     // Load first characters
8020     load_unsigned_short(result, Address(str1, 0));
8021     load_unsigned_short(cnt1, Address(str2, 0));
8022   } else {
8023     load_unsigned_byte(result, Address(str1, 0));
8024     load_unsigned_short(cnt1, Address(str2, 0));
8025   }
8026   subl(result, cnt1);
8027   jcc(Assembler::notZero,  POP_LABEL);
8028 
8029   if (ae == StrIntrinsicNode::UU) {
8030     // Divide length by 2 to get number of chars
8031     shrl(cnt2, 1);
8032   }
8033   cmpl(cnt2, 1);
8034   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8035 
8036   // Check if the strings start at the same location and setup scale and stride
8037   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8038     cmpptr(str1, str2);
8039     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8040     if (ae == StrIntrinsicNode::LL) {
8041       scale = Address::times_1;
8042       stride = 16;
8043     } else {
8044       scale = Address::times_2;
8045       stride = 8;
8046     }
8047   } else {
8048     scale = Address::no_scale;  // not used
8049     scale1 = Address::times_1;
8050     scale2 = Address::times_2;
8051     stride = 8;
8052   }
8053 
8054   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8055     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8056     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8057     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8058     Label COMPARE_TAIL_LONG;
8059     int pcmpmask = 0x19;
8060     if (ae == StrIntrinsicNode::LL) {
8061       pcmpmask &= ~0x01;
8062     }
8063 
8064     // Setup to compare 16-chars (32-bytes) vectors,
8065     // start from first character again because it has aligned address.
8066     if (ae == StrIntrinsicNode::LL) {
8067       stride2 = 32;
8068     } else {
8069       stride2 = 16;
8070     }
8071     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8072       adr_stride = stride << scale;
8073     } else {
8074       adr_stride1 = 8;  //stride << scale1;
8075       adr_stride2 = 16; //stride << scale2;
8076     }
8077 
8078     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8079     // rax and rdx are used by pcmpestri as elements counters
8080     movl(result, cnt2);
8081     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8082     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8083 
8084     // fast path : compare first 2 8-char vectors.
8085     bind(COMPARE_16_CHARS);
8086     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8087       movdqu(vec1, Address(str1, 0));
8088     } else {
8089       pmovzxbw(vec1, Address(str1, 0));
8090     }
8091     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8092     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8093 
8094     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8095       movdqu(vec1, Address(str1, adr_stride));
8096       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8097     } else {
8098       pmovzxbw(vec1, Address(str1, adr_stride1));
8099       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8100     }
8101     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8102     addl(cnt1, stride);
8103 
8104     // Compare the characters at index in cnt1
8105     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8106     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8107     subl(result, cnt2);
8108     jmp(POP_LABEL);
8109 
8110     // Setup the registers to start vector comparison loop
8111     bind(COMPARE_WIDE_VECTORS);
8112     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8113       lea(str1, Address(str1, result, scale));
8114       lea(str2, Address(str2, result, scale));
8115     } else {
8116       lea(str1, Address(str1, result, scale1));
8117       lea(str2, Address(str2, result, scale2));
8118     }
8119     subl(result, stride2);
8120     subl(cnt2, stride2);
8121     jccb(Assembler::zero, COMPARE_WIDE_TAIL);
8122     negptr(result);
8123 
8124     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8125     bind(COMPARE_WIDE_VECTORS_LOOP);
8126     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8127       vmovdqu(vec1, Address(str1, result, scale));
8128       vpxor(vec1, Address(str2, result, scale));
8129     } else {
8130       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8131       vpxor(vec1, Address(str2, result, scale2));
8132     }
8133     vptest(vec1, vec1);
8134     jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
8135     addptr(result, stride2);
8136     subl(cnt2, stride2);
8137     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8138     // clean upper bits of YMM registers
8139     vpxor(vec1, vec1);
8140 
8141     // compare wide vectors tail
8142     bind(COMPARE_WIDE_TAIL);
8143     testptr(result, result);
8144     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8145 
8146     movl(result, stride2);
8147     movl(cnt2, result);
8148     negptr(result);
8149     jmpb(COMPARE_WIDE_VECTORS_LOOP);
8150 
8151     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8152     bind(VECTOR_NOT_EQUAL);
8153     // clean upper bits of YMM registers
8154     vpxor(vec1, vec1);
8155     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8156       lea(str1, Address(str1, result, scale));
8157       lea(str2, Address(str2, result, scale));
8158     } else {
8159       lea(str1, Address(str1, result, scale1));
8160       lea(str2, Address(str2, result, scale2));
8161     }
8162     jmp(COMPARE_16_CHARS);
8163 
8164     // Compare tail chars, length between 1 to 15 chars
8165     bind(COMPARE_TAIL_LONG);
8166     movl(cnt2, result);
8167     cmpl(cnt2, stride);
8168     jccb(Assembler::less, COMPARE_SMALL_STR);
8169 
8170     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8171       movdqu(vec1, Address(str1, 0));
8172     } else {
8173       pmovzxbw(vec1, Address(str1, 0));
8174     }
8175     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8176     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8177     subptr(cnt2, stride);
8178     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8179     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8180       lea(str1, Address(str1, result, scale));
8181       lea(str2, Address(str2, result, scale));
8182     } else {
8183       lea(str1, Address(str1, result, scale1));
8184       lea(str2, Address(str2, result, scale2));
8185     }
8186     negptr(cnt2);
8187     jmpb(WHILE_HEAD_LABEL);
8188 
8189     bind(COMPARE_SMALL_STR);
8190   } else if (UseSSE42Intrinsics) {
8191     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8192     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8193     int pcmpmask = 0x19;
8194     // Setup to compare 8-char (16-byte) vectors,
8195     // start from first character again because it has aligned address.
8196     movl(result, cnt2);
8197     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8198     if (ae == StrIntrinsicNode::LL) {
8199       pcmpmask &= ~0x01;
8200     }
8201     jccb(Assembler::zero, COMPARE_TAIL);
8202     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8203       lea(str1, Address(str1, result, scale));
8204       lea(str2, Address(str2, result, scale));
8205     } else {
8206       lea(str1, Address(str1, result, scale1));
8207       lea(str2, Address(str2, result, scale2));
8208     }
8209     negptr(result);
8210 
8211     // pcmpestri
8212     //   inputs:
8213     //     vec1- substring
8214     //     rax - negative string length (elements count)
8215     //     mem - scanned string
8216     //     rdx - string length (elements count)
8217     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8218     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8219     //   outputs:
8220     //     rcx - first mismatched element index
8221     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8222 
8223     bind(COMPARE_WIDE_VECTORS);
8224     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8225       movdqu(vec1, Address(str1, result, scale));
8226       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8227     } else {
8228       pmovzxbw(vec1, Address(str1, result, scale1));
8229       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8230     }
8231     // After pcmpestri cnt1(rcx) contains mismatched element index
8232 
8233     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8234     addptr(result, stride);
8235     subptr(cnt2, stride);
8236     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8237 
8238     // compare wide vectors tail
8239     testptr(result, result);
8240     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8241 
8242     movl(cnt2, stride);
8243     movl(result, stride);
8244     negptr(result);
8245     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8246       movdqu(vec1, Address(str1, result, scale));
8247       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8248     } else {
8249       pmovzxbw(vec1, Address(str1, result, scale1));
8250       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8251     }
8252     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8253 
8254     // Mismatched characters in the vectors
8255     bind(VECTOR_NOT_EQUAL);
8256     addptr(cnt1, result);
8257     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8258     subl(result, cnt2);
8259     jmpb(POP_LABEL);
8260 
8261     bind(COMPARE_TAIL); // limit is zero
8262     movl(cnt2, result);
8263     // Fallthru to tail compare
8264   }
8265   // Shift str2 and str1 to the end of the arrays, negate min
8266   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8267     lea(str1, Address(str1, cnt2, scale));
8268     lea(str2, Address(str2, cnt2, scale));
8269   } else {
8270     lea(str1, Address(str1, cnt2, scale1));
8271     lea(str2, Address(str2, cnt2, scale2));
8272   }
8273   decrementl(cnt2);  // first character was compared already
8274   negptr(cnt2);
8275 
8276   // Compare the rest of the elements
8277   bind(WHILE_HEAD_LABEL);
8278   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8279   subl(result, cnt1);
8280   jccb(Assembler::notZero, POP_LABEL);
8281   increment(cnt2);
8282   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8283 
8284   // Strings are equal up to min length.  Return the length difference.
8285   bind(LENGTH_DIFF_LABEL);
8286   pop(result);
8287   if (ae == StrIntrinsicNode::UU) {
8288     // Divide diff by 2 to get number of chars
8289     sarl(result, 1);
8290   }
8291   jmpb(DONE_LABEL);
8292 
8293   // Discard the stored length difference
8294   bind(POP_LABEL);
8295   pop(cnt1);
8296 
8297   // That's it
8298   bind(DONE_LABEL);
8299   if(ae == StrIntrinsicNode::UL) {
8300     negl(result);
8301   }
8302 }
8303 
8304 // Search for Non-ASCII character (Negative byte value) in a byte array,
8305 // return true if it has any and false otherwise.
8306 void MacroAssembler::has_negatives(Register ary1, Register len,
8307                                    Register result, Register tmp1,
8308                                    XMMRegister vec1, XMMRegister vec2) {
8309 
8310   // rsi: byte array
8311   // rcx: len
8312   // rax: result
8313   ShortBranchVerifier sbv(this);
8314   assert_different_registers(ary1, len, result, tmp1);
8315   assert_different_registers(vec1, vec2);
8316   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8317 
8318   // len == 0
8319   testl(len, len);
8320   jcc(Assembler::zero, FALSE_LABEL);
8321 
8322   movl(result, len); // copy
8323 
8324   if (UseAVX >= 2 && UseSSE >= 2) {
8325     // With AVX2, use 32-byte vector compare
8326     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8327 
8328     // Compare 32-byte vectors
8329     andl(result, 0x0000001f);  //   tail count (in bytes)
8330     andl(len, 0xffffffe0);   // vector count (in bytes)
8331     jccb(Assembler::zero, COMPARE_TAIL);
8332 
8333     lea(ary1, Address(ary1, len, Address::times_1));
8334     negptr(len);
8335 
8336     movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8337     movdl(vec2, tmp1);
8338     vpbroadcastd(vec2, vec2);
8339 
8340     bind(COMPARE_WIDE_VECTORS);
8341     vmovdqu(vec1, Address(ary1, len, Address::times_1));
8342     vptest(vec1, vec2);
8343     jccb(Assembler::notZero, TRUE_LABEL);
8344     addptr(len, 32);
8345     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8346 
8347     testl(result, result);
8348     jccb(Assembler::zero, FALSE_LABEL);
8349 
8350     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8351     vptest(vec1, vec2);
8352     jccb(Assembler::notZero, TRUE_LABEL);
8353     jmpb(FALSE_LABEL);
8354 
8355     bind(COMPARE_TAIL); // len is zero
8356     movl(len, result);
8357     // Fallthru to tail compare
8358   } else if (UseSSE42Intrinsics) {
8359     assert(UseSSE >= 4, "SSE4 must be  for SSE4.2 intrinsics to be available");
8360     // With SSE4.2, use double quad vector compare
8361     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8362 
8363     // Compare 16-byte vectors
8364     andl(result, 0x0000000f);  //   tail count (in bytes)
8365     andl(len, 0xfffffff0);   // vector count (in bytes)
8366     jccb(Assembler::zero, COMPARE_TAIL);
8367 
8368     lea(ary1, Address(ary1, len, Address::times_1));
8369     negptr(len);
8370 
8371     movl(tmp1, 0x80808080);
8372     movdl(vec2, tmp1);
8373     pshufd(vec2, vec2, 0);
8374 
8375     bind(COMPARE_WIDE_VECTORS);
8376     movdqu(vec1, Address(ary1, len, Address::times_1));
8377     ptest(vec1, vec2);
8378     jccb(Assembler::notZero, TRUE_LABEL);
8379     addptr(len, 16);
8380     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8381 
8382     testl(result, result);
8383     jccb(Assembler::zero, FALSE_LABEL);
8384 
8385     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8386     ptest(vec1, vec2);
8387     jccb(Assembler::notZero, TRUE_LABEL);
8388     jmpb(FALSE_LABEL);
8389 
8390     bind(COMPARE_TAIL); // len is zero
8391     movl(len, result);
8392     // Fallthru to tail compare
8393   }
8394 
8395   // Compare 4-byte vectors
8396   andl(len, 0xfffffffc); // vector count (in bytes)
8397   jccb(Assembler::zero, COMPARE_CHAR);
8398 
8399   lea(ary1, Address(ary1, len, Address::times_1));
8400   negptr(len);
8401 
8402   bind(COMPARE_VECTORS);
8403   movl(tmp1, Address(ary1, len, Address::times_1));
8404   andl(tmp1, 0x80808080);
8405   jccb(Assembler::notZero, TRUE_LABEL);
8406   addptr(len, 4);
8407   jcc(Assembler::notZero, COMPARE_VECTORS);
8408 
8409   // Compare trailing char (final 2 bytes), if any
8410   bind(COMPARE_CHAR);
8411   testl(result, 0x2);   // tail  char
8412   jccb(Assembler::zero, COMPARE_BYTE);
8413   load_unsigned_short(tmp1, Address(ary1, 0));
8414   andl(tmp1, 0x00008080);
8415   jccb(Assembler::notZero, TRUE_LABEL);
8416   subptr(result, 2);
8417   lea(ary1, Address(ary1, 2));
8418 
8419   bind(COMPARE_BYTE);
8420   testl(result, 0x1);   // tail  byte
8421   jccb(Assembler::zero, FALSE_LABEL);
8422   load_unsigned_byte(tmp1, Address(ary1, 0));
8423   andl(tmp1, 0x00000080);
8424   jccb(Assembler::notEqual, TRUE_LABEL);
8425   jmpb(FALSE_LABEL);
8426 
8427   bind(TRUE_LABEL);
8428   movl(result, 1);   // return true
8429   jmpb(DONE);
8430 
8431   bind(FALSE_LABEL);
8432   xorl(result, result); // return false
8433 
8434   // That's it
8435   bind(DONE);
8436   if (UseAVX >= 2 && UseSSE >= 2) {
8437     // clean upper bits of YMM registers
8438     vpxor(vec1, vec1);
8439     vpxor(vec2, vec2);
8440   }
8441 }
8442 
8443 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8444 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8445                                    Register limit, Register result, Register chr,
8446                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8447   ShortBranchVerifier sbv(this);
8448   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8449 
8450   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8451   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8452 
8453   if (is_array_equ) {
8454     // Check the input args
8455     cmpptr(ary1, ary2);
8456     jcc(Assembler::equal, TRUE_LABEL);
8457 
8458     // Need additional checks for arrays_equals.
8459     testptr(ary1, ary1);
8460     jcc(Assembler::zero, FALSE_LABEL);
8461     testptr(ary2, ary2);
8462     jcc(Assembler::zero, FALSE_LABEL);
8463 
8464     // Check the lengths
8465     movl(limit, Address(ary1, length_offset));
8466     cmpl(limit, Address(ary2, length_offset));
8467     jcc(Assembler::notEqual, FALSE_LABEL);
8468   }
8469 
8470   // count == 0
8471   testl(limit, limit);
8472   jcc(Assembler::zero, TRUE_LABEL);
8473 
8474   if (is_array_equ) {
8475     // Load array address
8476     lea(ary1, Address(ary1, base_offset));
8477     lea(ary2, Address(ary2, base_offset));
8478   }
8479 
8480   if (is_array_equ && is_char) {
8481     // arrays_equals when used for char[].
8482     shll(limit, 1);      // byte count != 0
8483   }
8484   movl(result, limit); // copy
8485 
8486   if (UseAVX >= 2) {
8487     // With AVX2, use 32-byte vector compare
8488     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8489 
8490     // Compare 32-byte vectors
8491     andl(result, 0x0000001f);  //   tail count (in bytes)
8492     andl(limit, 0xffffffe0);   // vector count (in bytes)
8493     jccb(Assembler::zero, COMPARE_TAIL);
8494 
8495     lea(ary1, Address(ary1, limit, Address::times_1));
8496     lea(ary2, Address(ary2, limit, Address::times_1));
8497     negptr(limit);
8498 
8499     bind(COMPARE_WIDE_VECTORS);
8500     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8501     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8502     vpxor(vec1, vec2);
8503 
8504     vptest(vec1, vec1);
8505     jccb(Assembler::notZero, FALSE_LABEL);
8506     addptr(limit, 32);
8507     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8508 
8509     testl(result, result);
8510     jccb(Assembler::zero, TRUE_LABEL);
8511 
8512     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8513     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8514     vpxor(vec1, vec2);
8515 
8516     vptest(vec1, vec1);
8517     jccb(Assembler::notZero, FALSE_LABEL);
8518     jmpb(TRUE_LABEL);
8519 
8520     bind(COMPARE_TAIL); // limit is zero
8521     movl(limit, result);
8522     // Fallthru to tail compare
8523   } else if (UseSSE42Intrinsics) {
8524     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8525     // With SSE4.2, use double quad vector compare
8526     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8527 
8528     // Compare 16-byte vectors
8529     andl(result, 0x0000000f);  //   tail count (in bytes)
8530     andl(limit, 0xfffffff0);   // vector count (in bytes)
8531     jccb(Assembler::zero, COMPARE_TAIL);
8532 
8533     lea(ary1, Address(ary1, limit, Address::times_1));
8534     lea(ary2, Address(ary2, limit, Address::times_1));
8535     negptr(limit);
8536 
8537     bind(COMPARE_WIDE_VECTORS);
8538     movdqu(vec1, Address(ary1, limit, Address::times_1));
8539     movdqu(vec2, Address(ary2, limit, Address::times_1));
8540     pxor(vec1, vec2);
8541 
8542     ptest(vec1, vec1);
8543     jccb(Assembler::notZero, FALSE_LABEL);
8544     addptr(limit, 16);
8545     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8546 
8547     testl(result, result);
8548     jccb(Assembler::zero, TRUE_LABEL);
8549 
8550     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8551     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8552     pxor(vec1, vec2);
8553 
8554     ptest(vec1, vec1);
8555     jccb(Assembler::notZero, FALSE_LABEL);
8556     jmpb(TRUE_LABEL);
8557 
8558     bind(COMPARE_TAIL); // limit is zero
8559     movl(limit, result);
8560     // Fallthru to tail compare
8561   }
8562 
8563   // Compare 4-byte vectors
8564   andl(limit, 0xfffffffc); // vector count (in bytes)
8565   jccb(Assembler::zero, COMPARE_CHAR);
8566 
8567   lea(ary1, Address(ary1, limit, Address::times_1));
8568   lea(ary2, Address(ary2, limit, Address::times_1));
8569   negptr(limit);
8570 
8571   bind(COMPARE_VECTORS);
8572   movl(chr, Address(ary1, limit, Address::times_1));
8573   cmpl(chr, Address(ary2, limit, Address::times_1));
8574   jccb(Assembler::notEqual, FALSE_LABEL);
8575   addptr(limit, 4);
8576   jcc(Assembler::notZero, COMPARE_VECTORS);
8577 
8578   // Compare trailing char (final 2 bytes), if any
8579   bind(COMPARE_CHAR);
8580   testl(result, 0x2);   // tail  char
8581   jccb(Assembler::zero, COMPARE_BYTE);
8582   load_unsigned_short(chr, Address(ary1, 0));
8583   load_unsigned_short(limit, Address(ary2, 0));
8584   cmpl(chr, limit);
8585   jccb(Assembler::notEqual, FALSE_LABEL);
8586 
8587   if (is_array_equ && is_char) {
8588     bind(COMPARE_BYTE);
8589   } else {
8590     lea(ary1, Address(ary1, 2));
8591     lea(ary2, Address(ary2, 2));
8592 
8593     bind(COMPARE_BYTE);
8594     testl(result, 0x1);   // tail  byte
8595     jccb(Assembler::zero, TRUE_LABEL);
8596     load_unsigned_byte(chr, Address(ary1, 0));
8597     load_unsigned_byte(limit, Address(ary2, 0));
8598     cmpl(chr, limit);
8599     jccb(Assembler::notEqual, FALSE_LABEL);
8600   }
8601   bind(TRUE_LABEL);
8602   movl(result, 1);   // return true
8603   jmpb(DONE);
8604 
8605   bind(FALSE_LABEL);
8606   xorl(result, result); // return false
8607 
8608   // That's it
8609   bind(DONE);
8610   if (UseAVX >= 2) {
8611     // clean upper bits of YMM registers
8612     vpxor(vec1, vec1);
8613     vpxor(vec2, vec2);
8614   }
8615 }
8616 
8617 #endif
8618 
8619 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8620                                    Register to, Register value, Register count,
8621                                    Register rtmp, XMMRegister xtmp) {
8622   ShortBranchVerifier sbv(this);
8623   assert_different_registers(to, value, count, rtmp);
8624   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8625   Label L_fill_2_bytes, L_fill_4_bytes;
8626 
8627   int shift = -1;
8628   switch (t) {
8629     case T_BYTE:
8630       shift = 2;
8631       break;
8632     case T_SHORT:
8633       shift = 1;
8634       break;
8635     case T_INT:
8636       shift = 0;
8637       break;
8638     default: ShouldNotReachHere();
8639   }
8640 
8641   if (t == T_BYTE) {
8642     andl(value, 0xff);
8643     movl(rtmp, value);
8644     shll(rtmp, 8);
8645     orl(value, rtmp);
8646   }
8647   if (t == T_SHORT) {
8648     andl(value, 0xffff);
8649   }
8650   if (t == T_BYTE || t == T_SHORT) {
8651     movl(rtmp, value);
8652     shll(rtmp, 16);
8653     orl(value, rtmp);
8654   }
8655 
8656   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8657   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8658   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8659     // align source address at 4 bytes address boundary
8660     if (t == T_BYTE) {
8661       // One byte misalignment happens only for byte arrays
8662       testptr(to, 1);
8663       jccb(Assembler::zero, L_skip_align1);
8664       movb(Address(to, 0), value);
8665       increment(to);
8666       decrement(count);
8667       BIND(L_skip_align1);
8668     }
8669     // Two bytes misalignment happens only for byte and short (char) arrays
8670     testptr(to, 2);
8671     jccb(Assembler::zero, L_skip_align2);
8672     movw(Address(to, 0), value);
8673     addptr(to, 2);
8674     subl(count, 1<<(shift-1));
8675     BIND(L_skip_align2);
8676   }
8677   if (UseSSE < 2) {
8678     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8679     // Fill 32-byte chunks
8680     subl(count, 8 << shift);
8681     jcc(Assembler::less, L_check_fill_8_bytes);
8682     align(16);
8683 
8684     BIND(L_fill_32_bytes_loop);
8685 
8686     for (int i = 0; i < 32; i += 4) {
8687       movl(Address(to, i), value);
8688     }
8689 
8690     addptr(to, 32);
8691     subl(count, 8 << shift);
8692     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8693     BIND(L_check_fill_8_bytes);
8694     addl(count, 8 << shift);
8695     jccb(Assembler::zero, L_exit);
8696     jmpb(L_fill_8_bytes);
8697 
8698     //
8699     // length is too short, just fill qwords
8700     //
8701     BIND(L_fill_8_bytes_loop);
8702     movl(Address(to, 0), value);
8703     movl(Address(to, 4), value);
8704     addptr(to, 8);
8705     BIND(L_fill_8_bytes);
8706     subl(count, 1 << (shift + 1));
8707     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8708     // fall through to fill 4 bytes
8709   } else {
8710     Label L_fill_32_bytes;
8711     if (!UseUnalignedLoadStores) {
8712       // align to 8 bytes, we know we are 4 byte aligned to start
8713       testptr(to, 4);
8714       jccb(Assembler::zero, L_fill_32_bytes);
8715       movl(Address(to, 0), value);
8716       addptr(to, 4);
8717       subl(count, 1<<shift);
8718     }
8719     BIND(L_fill_32_bytes);
8720     {
8721       assert( UseSSE >= 2, "supported cpu only" );
8722       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8723       if (UseAVX > 2) {
8724         movl(rtmp, 0xffff);
8725         kmovwl(k1, rtmp);
8726       }
8727       movdl(xtmp, value);
8728       if (UseAVX > 2 && UseUnalignedLoadStores) {
8729         // Fill 64-byte chunks
8730         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8731         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8732 
8733         subl(count, 16 << shift);
8734         jcc(Assembler::less, L_check_fill_32_bytes);
8735         align(16);
8736 
8737         BIND(L_fill_64_bytes_loop);
8738         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8739         addptr(to, 64);
8740         subl(count, 16 << shift);
8741         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8742 
8743         BIND(L_check_fill_32_bytes);
8744         addl(count, 8 << shift);
8745         jccb(Assembler::less, L_check_fill_8_bytes);
8746         vmovdqu(Address(to, 0), xtmp);
8747         addptr(to, 32);
8748         subl(count, 8 << shift);
8749 
8750         BIND(L_check_fill_8_bytes);
8751       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8752         // Fill 64-byte chunks
8753         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8754         vpbroadcastd(xtmp, xtmp);
8755 
8756         subl(count, 16 << shift);
8757         jcc(Assembler::less, L_check_fill_32_bytes);
8758         align(16);
8759 
8760         BIND(L_fill_64_bytes_loop);
8761         vmovdqu(Address(to, 0), xtmp);
8762         vmovdqu(Address(to, 32), xtmp);
8763         addptr(to, 64);
8764         subl(count, 16 << shift);
8765         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8766 
8767         BIND(L_check_fill_32_bytes);
8768         addl(count, 8 << shift);
8769         jccb(Assembler::less, L_check_fill_8_bytes);
8770         vmovdqu(Address(to, 0), xtmp);
8771         addptr(to, 32);
8772         subl(count, 8 << shift);
8773 
8774         BIND(L_check_fill_8_bytes);
8775         // clean upper bits of YMM registers
8776         movdl(xtmp, value);
8777         pshufd(xtmp, xtmp, 0);
8778       } else {
8779         // Fill 32-byte chunks
8780         pshufd(xtmp, xtmp, 0);
8781 
8782         subl(count, 8 << shift);
8783         jcc(Assembler::less, L_check_fill_8_bytes);
8784         align(16);
8785 
8786         BIND(L_fill_32_bytes_loop);
8787 
8788         if (UseUnalignedLoadStores) {
8789           movdqu(Address(to, 0), xtmp);
8790           movdqu(Address(to, 16), xtmp);
8791         } else {
8792           movq(Address(to, 0), xtmp);
8793           movq(Address(to, 8), xtmp);
8794           movq(Address(to, 16), xtmp);
8795           movq(Address(to, 24), xtmp);
8796         }
8797 
8798         addptr(to, 32);
8799         subl(count, 8 << shift);
8800         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8801 
8802         BIND(L_check_fill_8_bytes);
8803       }
8804       addl(count, 8 << shift);
8805       jccb(Assembler::zero, L_exit);
8806       jmpb(L_fill_8_bytes);
8807 
8808       //
8809       // length is too short, just fill qwords
8810       //
8811       BIND(L_fill_8_bytes_loop);
8812       movq(Address(to, 0), xtmp);
8813       addptr(to, 8);
8814       BIND(L_fill_8_bytes);
8815       subl(count, 1 << (shift + 1));
8816       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8817     }
8818   }
8819   // fill trailing 4 bytes
8820   BIND(L_fill_4_bytes);
8821   testl(count, 1<<shift);
8822   jccb(Assembler::zero, L_fill_2_bytes);
8823   movl(Address(to, 0), value);
8824   if (t == T_BYTE || t == T_SHORT) {
8825     addptr(to, 4);
8826     BIND(L_fill_2_bytes);
8827     // fill trailing 2 bytes
8828     testl(count, 1<<(shift-1));
8829     jccb(Assembler::zero, L_fill_byte);
8830     movw(Address(to, 0), value);
8831     if (t == T_BYTE) {
8832       addptr(to, 2);
8833       BIND(L_fill_byte);
8834       // fill trailing byte
8835       testl(count, 1);
8836       jccb(Assembler::zero, L_exit);
8837       movb(Address(to, 0), value);
8838     } else {
8839       BIND(L_fill_byte);
8840     }
8841   } else {
8842     BIND(L_fill_2_bytes);
8843   }
8844   BIND(L_exit);
8845 }
8846 
8847 // encode char[] to byte[] in ISO_8859_1
8848 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8849                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8850                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8851                                       Register tmp5, Register result) {
8852   // rsi: src
8853   // rdi: dst
8854   // rdx: len
8855   // rcx: tmp5
8856   // rax: result
8857   ShortBranchVerifier sbv(this);
8858   assert_different_registers(src, dst, len, tmp5, result);
8859   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8860 
8861   // set result
8862   xorl(result, result);
8863   // check for zero length
8864   testl(len, len);
8865   jcc(Assembler::zero, L_done);
8866   movl(result, len);
8867 
8868   // Setup pointers
8869   lea(src, Address(src, len, Address::times_2)); // char[]
8870   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8871   negptr(len);
8872 
8873   if (UseSSE42Intrinsics || UseAVX >= 2) {
8874     assert(UseSSE42Intrinsics ? UseSSE >= 4 : true, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8875     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8876     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8877 
8878     if (UseAVX >= 2) {
8879       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8880       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8881       movdl(tmp1Reg, tmp5);
8882       vpbroadcastd(tmp1Reg, tmp1Reg);
8883       jmpb(L_chars_32_check);
8884 
8885       bind(L_copy_32_chars);
8886       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8887       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8888       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8889       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8890       jccb(Assembler::notZero, L_copy_32_chars_exit);
8891       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8892       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8893       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8894 
8895       bind(L_chars_32_check);
8896       addptr(len, 32);
8897       jccb(Assembler::lessEqual, L_copy_32_chars);
8898 
8899       bind(L_copy_32_chars_exit);
8900       subptr(len, 16);
8901       jccb(Assembler::greater, L_copy_16_chars_exit);
8902 
8903     } else if (UseSSE42Intrinsics) {
8904       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8905       movdl(tmp1Reg, tmp5);
8906       pshufd(tmp1Reg, tmp1Reg, 0);
8907       jmpb(L_chars_16_check);
8908     }
8909 
8910     bind(L_copy_16_chars);
8911     if (UseAVX >= 2) {
8912       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8913       vptest(tmp2Reg, tmp1Reg);
8914       jccb(Assembler::notZero, L_copy_16_chars_exit);
8915       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8916       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8917     } else {
8918       if (UseAVX > 0) {
8919         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8920         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8921         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8922       } else {
8923         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8924         por(tmp2Reg, tmp3Reg);
8925         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8926         por(tmp2Reg, tmp4Reg);
8927       }
8928       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8929       jccb(Assembler::notZero, L_copy_16_chars_exit);
8930       packuswb(tmp3Reg, tmp4Reg);
8931     }
8932     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8933 
8934     bind(L_chars_16_check);
8935     addptr(len, 16);
8936     jccb(Assembler::lessEqual, L_copy_16_chars);
8937 
8938     bind(L_copy_16_chars_exit);
8939     if (UseAVX >= 2) {
8940       // clean upper bits of YMM registers
8941       vpxor(tmp2Reg, tmp2Reg);
8942       vpxor(tmp3Reg, tmp3Reg);
8943       vpxor(tmp4Reg, tmp4Reg);
8944       movdl(tmp1Reg, tmp5);
8945       pshufd(tmp1Reg, tmp1Reg, 0);
8946     }
8947     subptr(len, 8);
8948     jccb(Assembler::greater, L_copy_8_chars_exit);
8949 
8950     bind(L_copy_8_chars);
8951     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8952     ptest(tmp3Reg, tmp1Reg);
8953     jccb(Assembler::notZero, L_copy_8_chars_exit);
8954     packuswb(tmp3Reg, tmp1Reg);
8955     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8956     addptr(len, 8);
8957     jccb(Assembler::lessEqual, L_copy_8_chars);
8958 
8959     bind(L_copy_8_chars_exit);
8960     subptr(len, 8);
8961     jccb(Assembler::zero, L_done);
8962   }
8963 
8964   bind(L_copy_1_char);
8965   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8966   testl(tmp5, 0xff00);      // check if Unicode char
8967   jccb(Assembler::notZero, L_copy_1_char_exit);
8968   movb(Address(dst, len, Address::times_1, 0), tmp5);
8969   addptr(len, 1);
8970   jccb(Assembler::less, L_copy_1_char);
8971 
8972   bind(L_copy_1_char_exit);
8973   addptr(result, len); // len is negative count of not processed elements
8974   bind(L_done);
8975 }
8976 
8977 #ifdef _LP64
8978 /**
8979  * Helper for multiply_to_len().
8980  */
8981 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8982   addq(dest_lo, src1);
8983   adcq(dest_hi, 0);
8984   addq(dest_lo, src2);
8985   adcq(dest_hi, 0);
8986 }
8987 
8988 /**
8989  * Multiply 64 bit by 64 bit first loop.
8990  */
8991 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8992                                            Register y, Register y_idx, Register z,
8993                                            Register carry, Register product,
8994                                            Register idx, Register kdx) {
8995   //
8996   //  jlong carry, x[], y[], z[];
8997   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8998   //    huge_128 product = y[idx] * x[xstart] + carry;
8999   //    z[kdx] = (jlong)product;
9000   //    carry  = (jlong)(product >>> 64);
9001   //  }
9002   //  z[xstart] = carry;
9003   //
9004 
9005   Label L_first_loop, L_first_loop_exit;
9006   Label L_one_x, L_one_y, L_multiply;
9007 
9008   decrementl(xstart);
9009   jcc(Assembler::negative, L_one_x);
9010 
9011   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9012   rorq(x_xstart, 32); // convert big-endian to little-endian
9013 
9014   bind(L_first_loop);
9015   decrementl(idx);
9016   jcc(Assembler::negative, L_first_loop_exit);
9017   decrementl(idx);
9018   jcc(Assembler::negative, L_one_y);
9019   movq(y_idx, Address(y, idx, Address::times_4,  0));
9020   rorq(y_idx, 32); // convert big-endian to little-endian
9021   bind(L_multiply);
9022   movq(product, x_xstart);
9023   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9024   addq(product, carry);
9025   adcq(rdx, 0);
9026   subl(kdx, 2);
9027   movl(Address(z, kdx, Address::times_4,  4), product);
9028   shrq(product, 32);
9029   movl(Address(z, kdx, Address::times_4,  0), product);
9030   movq(carry, rdx);
9031   jmp(L_first_loop);
9032 
9033   bind(L_one_y);
9034   movl(y_idx, Address(y,  0));
9035   jmp(L_multiply);
9036 
9037   bind(L_one_x);
9038   movl(x_xstart, Address(x,  0));
9039   jmp(L_first_loop);
9040 
9041   bind(L_first_loop_exit);
9042 }
9043 
9044 /**
9045  * Multiply 64 bit by 64 bit and add 128 bit.
9046  */
9047 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9048                                             Register yz_idx, Register idx,
9049                                             Register carry, Register product, int offset) {
9050   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9051   //     z[kdx] = (jlong)product;
9052 
9053   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9054   rorq(yz_idx, 32); // convert big-endian to little-endian
9055   movq(product, x_xstart);
9056   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9057   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9058   rorq(yz_idx, 32); // convert big-endian to little-endian
9059 
9060   add2_with_carry(rdx, product, carry, yz_idx);
9061 
9062   movl(Address(z, idx, Address::times_4,  offset+4), product);
9063   shrq(product, 32);
9064   movl(Address(z, idx, Address::times_4,  offset), product);
9065 
9066 }
9067 
9068 /**
9069  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9070  */
9071 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9072                                              Register yz_idx, Register idx, Register jdx,
9073                                              Register carry, Register product,
9074                                              Register carry2) {
9075   //   jlong carry, x[], y[], z[];
9076   //   int kdx = ystart+1;
9077   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9078   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9079   //     z[kdx+idx+1] = (jlong)product;
9080   //     jlong carry2  = (jlong)(product >>> 64);
9081   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9082   //     z[kdx+idx] = (jlong)product;
9083   //     carry  = (jlong)(product >>> 64);
9084   //   }
9085   //   idx += 2;
9086   //   if (idx > 0) {
9087   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9088   //     z[kdx+idx] = (jlong)product;
9089   //     carry  = (jlong)(product >>> 64);
9090   //   }
9091   //
9092 
9093   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9094 
9095   movl(jdx, idx);
9096   andl(jdx, 0xFFFFFFFC);
9097   shrl(jdx, 2);
9098 
9099   bind(L_third_loop);
9100   subl(jdx, 1);
9101   jcc(Assembler::negative, L_third_loop_exit);
9102   subl(idx, 4);
9103 
9104   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9105   movq(carry2, rdx);
9106 
9107   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9108   movq(carry, rdx);
9109   jmp(L_third_loop);
9110 
9111   bind (L_third_loop_exit);
9112 
9113   andl (idx, 0x3);
9114   jcc(Assembler::zero, L_post_third_loop_done);
9115 
9116   Label L_check_1;
9117   subl(idx, 2);
9118   jcc(Assembler::negative, L_check_1);
9119 
9120   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9121   movq(carry, rdx);
9122 
9123   bind (L_check_1);
9124   addl (idx, 0x2);
9125   andl (idx, 0x1);
9126   subl(idx, 1);
9127   jcc(Assembler::negative, L_post_third_loop_done);
9128 
9129   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9130   movq(product, x_xstart);
9131   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9132   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9133 
9134   add2_with_carry(rdx, product, yz_idx, carry);
9135 
9136   movl(Address(z, idx, Address::times_4,  0), product);
9137   shrq(product, 32);
9138 
9139   shlq(rdx, 32);
9140   orq(product, rdx);
9141   movq(carry, product);
9142 
9143   bind(L_post_third_loop_done);
9144 }
9145 
9146 /**
9147  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9148  *
9149  */
9150 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9151                                                   Register carry, Register carry2,
9152                                                   Register idx, Register jdx,
9153                                                   Register yz_idx1, Register yz_idx2,
9154                                                   Register tmp, Register tmp3, Register tmp4) {
9155   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9156 
9157   //   jlong carry, x[], y[], z[];
9158   //   int kdx = ystart+1;
9159   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9160   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9161   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9162   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9163   //     carry  = (jlong)(tmp4 >>> 64);
9164   //     z[kdx+idx+1] = (jlong)tmp3;
9165   //     z[kdx+idx] = (jlong)tmp4;
9166   //   }
9167   //   idx += 2;
9168   //   if (idx > 0) {
9169   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9170   //     z[kdx+idx] = (jlong)yz_idx1;
9171   //     carry  = (jlong)(yz_idx1 >>> 64);
9172   //   }
9173   //
9174 
9175   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9176 
9177   movl(jdx, idx);
9178   andl(jdx, 0xFFFFFFFC);
9179   shrl(jdx, 2);
9180 
9181   bind(L_third_loop);
9182   subl(jdx, 1);
9183   jcc(Assembler::negative, L_third_loop_exit);
9184   subl(idx, 4);
9185 
9186   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9187   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9188   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9189   rorxq(yz_idx2, yz_idx2, 32);
9190 
9191   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9192   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9193 
9194   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9195   rorxq(yz_idx1, yz_idx1, 32);
9196   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9197   rorxq(yz_idx2, yz_idx2, 32);
9198 
9199   if (VM_Version::supports_adx()) {
9200     adcxq(tmp3, carry);
9201     adoxq(tmp3, yz_idx1);
9202 
9203     adcxq(tmp4, tmp);
9204     adoxq(tmp4, yz_idx2);
9205 
9206     movl(carry, 0); // does not affect flags
9207     adcxq(carry2, carry);
9208     adoxq(carry2, carry);
9209   } else {
9210     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9211     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9212   }
9213   movq(carry, carry2);
9214 
9215   movl(Address(z, idx, Address::times_4, 12), tmp3);
9216   shrq(tmp3, 32);
9217   movl(Address(z, idx, Address::times_4,  8), tmp3);
9218 
9219   movl(Address(z, idx, Address::times_4,  4), tmp4);
9220   shrq(tmp4, 32);
9221   movl(Address(z, idx, Address::times_4,  0), tmp4);
9222 
9223   jmp(L_third_loop);
9224 
9225   bind (L_third_loop_exit);
9226 
9227   andl (idx, 0x3);
9228   jcc(Assembler::zero, L_post_third_loop_done);
9229 
9230   Label L_check_1;
9231   subl(idx, 2);
9232   jcc(Assembler::negative, L_check_1);
9233 
9234   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9235   rorxq(yz_idx1, yz_idx1, 32);
9236   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9237   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9238   rorxq(yz_idx2, yz_idx2, 32);
9239 
9240   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9241 
9242   movl(Address(z, idx, Address::times_4,  4), tmp3);
9243   shrq(tmp3, 32);
9244   movl(Address(z, idx, Address::times_4,  0), tmp3);
9245   movq(carry, tmp4);
9246 
9247   bind (L_check_1);
9248   addl (idx, 0x2);
9249   andl (idx, 0x1);
9250   subl(idx, 1);
9251   jcc(Assembler::negative, L_post_third_loop_done);
9252   movl(tmp4, Address(y, idx, Address::times_4,  0));
9253   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9254   movl(tmp4, Address(z, idx, Address::times_4,  0));
9255 
9256   add2_with_carry(carry2, tmp3, tmp4, carry);
9257 
9258   movl(Address(z, idx, Address::times_4,  0), tmp3);
9259   shrq(tmp3, 32);
9260 
9261   shlq(carry2, 32);
9262   orq(tmp3, carry2);
9263   movq(carry, tmp3);
9264 
9265   bind(L_post_third_loop_done);
9266 }
9267 
9268 /**
9269  * Code for BigInteger::multiplyToLen() instrinsic.
9270  *
9271  * rdi: x
9272  * rax: xlen
9273  * rsi: y
9274  * rcx: ylen
9275  * r8:  z
9276  * r11: zlen
9277  * r12: tmp1
9278  * r13: tmp2
9279  * r14: tmp3
9280  * r15: tmp4
9281  * rbx: tmp5
9282  *
9283  */
9284 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9285                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9286   ShortBranchVerifier sbv(this);
9287   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9288 
9289   push(tmp1);
9290   push(tmp2);
9291   push(tmp3);
9292   push(tmp4);
9293   push(tmp5);
9294 
9295   push(xlen);
9296   push(zlen);
9297 
9298   const Register idx = tmp1;
9299   const Register kdx = tmp2;
9300   const Register xstart = tmp3;
9301 
9302   const Register y_idx = tmp4;
9303   const Register carry = tmp5;
9304   const Register product  = xlen;
9305   const Register x_xstart = zlen;  // reuse register
9306 
9307   // First Loop.
9308   //
9309   //  final static long LONG_MASK = 0xffffffffL;
9310   //  int xstart = xlen - 1;
9311   //  int ystart = ylen - 1;
9312   //  long carry = 0;
9313   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9314   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9315   //    z[kdx] = (int)product;
9316   //    carry = product >>> 32;
9317   //  }
9318   //  z[xstart] = (int)carry;
9319   //
9320 
9321   movl(idx, ylen);      // idx = ylen;
9322   movl(kdx, zlen);      // kdx = xlen+ylen;
9323   xorq(carry, carry);   // carry = 0;
9324 
9325   Label L_done;
9326 
9327   movl(xstart, xlen);
9328   decrementl(xstart);
9329   jcc(Assembler::negative, L_done);
9330 
9331   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9332 
9333   Label L_second_loop;
9334   testl(kdx, kdx);
9335   jcc(Assembler::zero, L_second_loop);
9336 
9337   Label L_carry;
9338   subl(kdx, 1);
9339   jcc(Assembler::zero, L_carry);
9340 
9341   movl(Address(z, kdx, Address::times_4,  0), carry);
9342   shrq(carry, 32);
9343   subl(kdx, 1);
9344 
9345   bind(L_carry);
9346   movl(Address(z, kdx, Address::times_4,  0), carry);
9347 
9348   // Second and third (nested) loops.
9349   //
9350   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9351   //   carry = 0;
9352   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9353   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9354   //                    (z[k] & LONG_MASK) + carry;
9355   //     z[k] = (int)product;
9356   //     carry = product >>> 32;
9357   //   }
9358   //   z[i] = (int)carry;
9359   // }
9360   //
9361   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9362 
9363   const Register jdx = tmp1;
9364 
9365   bind(L_second_loop);
9366   xorl(carry, carry);    // carry = 0;
9367   movl(jdx, ylen);       // j = ystart+1
9368 
9369   subl(xstart, 1);       // i = xstart-1;
9370   jcc(Assembler::negative, L_done);
9371 
9372   push (z);
9373 
9374   Label L_last_x;
9375   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9376   subl(xstart, 1);       // i = xstart-1;
9377   jcc(Assembler::negative, L_last_x);
9378 
9379   if (UseBMI2Instructions) {
9380     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9381     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9382   } else {
9383     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9384     rorq(x_xstart, 32);  // convert big-endian to little-endian
9385   }
9386 
9387   Label L_third_loop_prologue;
9388   bind(L_third_loop_prologue);
9389 
9390   push (x);
9391   push (xstart);
9392   push (ylen);
9393 
9394 
9395   if (UseBMI2Instructions) {
9396     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9397   } else { // !UseBMI2Instructions
9398     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9399   }
9400 
9401   pop(ylen);
9402   pop(xlen);
9403   pop(x);
9404   pop(z);
9405 
9406   movl(tmp3, xlen);
9407   addl(tmp3, 1);
9408   movl(Address(z, tmp3, Address::times_4,  0), carry);
9409   subl(tmp3, 1);
9410   jccb(Assembler::negative, L_done);
9411 
9412   shrq(carry, 32);
9413   movl(Address(z, tmp3, Address::times_4,  0), carry);
9414   jmp(L_second_loop);
9415 
9416   // Next infrequent code is moved outside loops.
9417   bind(L_last_x);
9418   if (UseBMI2Instructions) {
9419     movl(rdx, Address(x,  0));
9420   } else {
9421     movl(x_xstart, Address(x,  0));
9422   }
9423   jmp(L_third_loop_prologue);
9424 
9425   bind(L_done);
9426 
9427   pop(zlen);
9428   pop(xlen);
9429 
9430   pop(tmp5);
9431   pop(tmp4);
9432   pop(tmp3);
9433   pop(tmp2);
9434   pop(tmp1);
9435 }
9436 
9437 //Helper functions for square_to_len()
9438 
9439 /**
9440  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9441  * Preserves x and z and modifies rest of the registers.
9442  */
9443 
9444 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9445   // Perform square and right shift by 1
9446   // Handle odd xlen case first, then for even xlen do the following
9447   // jlong carry = 0;
9448   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9449   //     huge_128 product = x[j:j+1] * x[j:j+1];
9450   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9451   //     z[i+2:i+3] = (jlong)(product >>> 1);
9452   //     carry = (jlong)product;
9453   // }
9454 
9455   xorq(tmp5, tmp5);     // carry
9456   xorq(rdxReg, rdxReg);
9457   xorl(tmp1, tmp1);     // index for x
9458   xorl(tmp4, tmp4);     // index for z
9459 
9460   Label L_first_loop, L_first_loop_exit;
9461 
9462   testl(xlen, 1);
9463   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9464 
9465   // Square and right shift by 1 the odd element using 32 bit multiply
9466   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9467   imulq(raxReg, raxReg);
9468   shrq(raxReg, 1);
9469   adcq(tmp5, 0);
9470   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9471   incrementl(tmp1);
9472   addl(tmp4, 2);
9473 
9474   // Square and  right shift by 1 the rest using 64 bit multiply
9475   bind(L_first_loop);
9476   cmpptr(tmp1, xlen);
9477   jccb(Assembler::equal, L_first_loop_exit);
9478 
9479   // Square
9480   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9481   rorq(raxReg, 32);    // convert big-endian to little-endian
9482   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9483 
9484   // Right shift by 1 and save carry
9485   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9486   rcrq(rdxReg, 1);
9487   rcrq(raxReg, 1);
9488   adcq(tmp5, 0);
9489 
9490   // Store result in z
9491   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9492   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9493 
9494   // Update indices for x and z
9495   addl(tmp1, 2);
9496   addl(tmp4, 4);
9497   jmp(L_first_loop);
9498 
9499   bind(L_first_loop_exit);
9500 }
9501 
9502 
9503 /**
9504  * Perform the following multiply add operation using BMI2 instructions
9505  * carry:sum = sum + op1*op2 + carry
9506  * op2 should be in rdx
9507  * op2 is preserved, all other registers are modified
9508  */
9509 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9510   // assert op2 is rdx
9511   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9512   addq(sum, carry);
9513   adcq(tmp2, 0);
9514   addq(sum, op1);
9515   adcq(tmp2, 0);
9516   movq(carry, tmp2);
9517 }
9518 
9519 /**
9520  * Perform the following multiply add operation:
9521  * carry:sum = sum + op1*op2 + carry
9522  * Preserves op1, op2 and modifies rest of registers
9523  */
9524 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9525   // rdx:rax = op1 * op2
9526   movq(raxReg, op2);
9527   mulq(op1);
9528 
9529   //  rdx:rax = sum + carry + rdx:rax
9530   addq(sum, carry);
9531   adcq(rdxReg, 0);
9532   addq(sum, raxReg);
9533   adcq(rdxReg, 0);
9534 
9535   // carry:sum = rdx:sum
9536   movq(carry, rdxReg);
9537 }
9538 
9539 /**
9540  * Add 64 bit long carry into z[] with carry propogation.
9541  * Preserves z and carry register values and modifies rest of registers.
9542  *
9543  */
9544 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9545   Label L_fourth_loop, L_fourth_loop_exit;
9546 
9547   movl(tmp1, 1);
9548   subl(zlen, 2);
9549   addq(Address(z, zlen, Address::times_4, 0), carry);
9550 
9551   bind(L_fourth_loop);
9552   jccb(Assembler::carryClear, L_fourth_loop_exit);
9553   subl(zlen, 2);
9554   jccb(Assembler::negative, L_fourth_loop_exit);
9555   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9556   jmp(L_fourth_loop);
9557   bind(L_fourth_loop_exit);
9558 }
9559 
9560 /**
9561  * Shift z[] left by 1 bit.
9562  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9563  *
9564  */
9565 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9566 
9567   Label L_fifth_loop, L_fifth_loop_exit;
9568 
9569   // Fifth loop
9570   // Perform primitiveLeftShift(z, zlen, 1)
9571 
9572   const Register prev_carry = tmp1;
9573   const Register new_carry = tmp4;
9574   const Register value = tmp2;
9575   const Register zidx = tmp3;
9576 
9577   // int zidx, carry;
9578   // long value;
9579   // carry = 0;
9580   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9581   //    (carry:value)  = (z[i] << 1) | carry ;
9582   //    z[i] = value;
9583   // }
9584 
9585   movl(zidx, zlen);
9586   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9587 
9588   bind(L_fifth_loop);
9589   decl(zidx);  // Use decl to preserve carry flag
9590   decl(zidx);
9591   jccb(Assembler::negative, L_fifth_loop_exit);
9592 
9593   if (UseBMI2Instructions) {
9594      movq(value, Address(z, zidx, Address::times_4, 0));
9595      rclq(value, 1);
9596      rorxq(value, value, 32);
9597      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9598   }
9599   else {
9600     // clear new_carry
9601     xorl(new_carry, new_carry);
9602 
9603     // Shift z[i] by 1, or in previous carry and save new carry
9604     movq(value, Address(z, zidx, Address::times_4, 0));
9605     shlq(value, 1);
9606     adcl(new_carry, 0);
9607 
9608     orq(value, prev_carry);
9609     rorq(value, 0x20);
9610     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9611 
9612     // Set previous carry = new carry
9613     movl(prev_carry, new_carry);
9614   }
9615   jmp(L_fifth_loop);
9616 
9617   bind(L_fifth_loop_exit);
9618 }
9619 
9620 
9621 /**
9622  * Code for BigInteger::squareToLen() intrinsic
9623  *
9624  * rdi: x
9625  * rsi: len
9626  * r8:  z
9627  * rcx: zlen
9628  * r12: tmp1
9629  * r13: tmp2
9630  * r14: tmp3
9631  * r15: tmp4
9632  * rbx: tmp5
9633  *
9634  */
9635 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) {
9636 
9637   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;
9638   push(tmp1);
9639   push(tmp2);
9640   push(tmp3);
9641   push(tmp4);
9642   push(tmp5);
9643 
9644   // First loop
9645   // Store the squares, right shifted one bit (i.e., divided by 2).
9646   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9647 
9648   // Add in off-diagonal sums.
9649   //
9650   // Second, third (nested) and fourth loops.
9651   // zlen +=2;
9652   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9653   //    carry = 0;
9654   //    long op2 = x[xidx:xidx+1];
9655   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9656   //       k -= 2;
9657   //       long op1 = x[j:j+1];
9658   //       long sum = z[k:k+1];
9659   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9660   //       z[k:k+1] = sum;
9661   //    }
9662   //    add_one_64(z, k, carry, tmp_regs);
9663   // }
9664 
9665   const Register carry = tmp5;
9666   const Register sum = tmp3;
9667   const Register op1 = tmp4;
9668   Register op2 = tmp2;
9669 
9670   push(zlen);
9671   push(len);
9672   addl(zlen,2);
9673   bind(L_second_loop);
9674   xorq(carry, carry);
9675   subl(zlen, 4);
9676   subl(len, 2);
9677   push(zlen);
9678   push(len);
9679   cmpl(len, 0);
9680   jccb(Assembler::lessEqual, L_second_loop_exit);
9681 
9682   // Multiply an array by one 64 bit long.
9683   if (UseBMI2Instructions) {
9684     op2 = rdxReg;
9685     movq(op2, Address(x, len, Address::times_4,  0));
9686     rorxq(op2, op2, 32);
9687   }
9688   else {
9689     movq(op2, Address(x, len, Address::times_4,  0));
9690     rorq(op2, 32);
9691   }
9692 
9693   bind(L_third_loop);
9694   decrementl(len);
9695   jccb(Assembler::negative, L_third_loop_exit);
9696   decrementl(len);
9697   jccb(Assembler::negative, L_last_x);
9698 
9699   movq(op1, Address(x, len, Address::times_4,  0));
9700   rorq(op1, 32);
9701 
9702   bind(L_multiply);
9703   subl(zlen, 2);
9704   movq(sum, Address(z, zlen, Address::times_4,  0));
9705 
9706   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9707   if (UseBMI2Instructions) {
9708     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9709   }
9710   else {
9711     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9712   }
9713 
9714   movq(Address(z, zlen, Address::times_4, 0), sum);
9715 
9716   jmp(L_third_loop);
9717   bind(L_third_loop_exit);
9718 
9719   // Fourth loop
9720   // Add 64 bit long carry into z with carry propogation.
9721   // Uses offsetted zlen.
9722   add_one_64(z, zlen, carry, tmp1);
9723 
9724   pop(len);
9725   pop(zlen);
9726   jmp(L_second_loop);
9727 
9728   // Next infrequent code is moved outside loops.
9729   bind(L_last_x);
9730   movl(op1, Address(x, 0));
9731   jmp(L_multiply);
9732 
9733   bind(L_second_loop_exit);
9734   pop(len);
9735   pop(zlen);
9736   pop(len);
9737   pop(zlen);
9738 
9739   // Fifth loop
9740   // Shift z left 1 bit.
9741   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9742 
9743   // z[zlen-1] |= x[len-1] & 1;
9744   movl(tmp3, Address(x, len, Address::times_4, -4));
9745   andl(tmp3, 1);
9746   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9747 
9748   pop(tmp5);
9749   pop(tmp4);
9750   pop(tmp3);
9751   pop(tmp2);
9752   pop(tmp1);
9753 }
9754 
9755 /**
9756  * Helper function for mul_add()
9757  * Multiply the in[] by int k and add to out[] starting at offset offs using
9758  * 128 bit by 32 bit multiply and return the carry in tmp5.
9759  * Only quad int aligned length of in[] is operated on in this function.
9760  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9761  * This function preserves out, in and k registers.
9762  * len and offset point to the appropriate index in "in" & "out" correspondingly
9763  * tmp5 has the carry.
9764  * other registers are temporary and are modified.
9765  *
9766  */
9767 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9768   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9769   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9770 
9771   Label L_first_loop, L_first_loop_exit;
9772 
9773   movl(tmp1, len);
9774   shrl(tmp1, 2);
9775 
9776   bind(L_first_loop);
9777   subl(tmp1, 1);
9778   jccb(Assembler::negative, L_first_loop_exit);
9779 
9780   subl(len, 4);
9781   subl(offset, 4);
9782 
9783   Register op2 = tmp2;
9784   const Register sum = tmp3;
9785   const Register op1 = tmp4;
9786   const Register carry = tmp5;
9787 
9788   if (UseBMI2Instructions) {
9789     op2 = rdxReg;
9790   }
9791 
9792   movq(op1, Address(in, len, Address::times_4,  8));
9793   rorq(op1, 32);
9794   movq(sum, Address(out, offset, Address::times_4,  8));
9795   rorq(sum, 32);
9796   if (UseBMI2Instructions) {
9797     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9798   }
9799   else {
9800     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9801   }
9802   // Store back in big endian from little endian
9803   rorq(sum, 0x20);
9804   movq(Address(out, offset, Address::times_4,  8), sum);
9805 
9806   movq(op1, Address(in, len, Address::times_4,  0));
9807   rorq(op1, 32);
9808   movq(sum, Address(out, offset, Address::times_4,  0));
9809   rorq(sum, 32);
9810   if (UseBMI2Instructions) {
9811     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9812   }
9813   else {
9814     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9815   }
9816   // Store back in big endian from little endian
9817   rorq(sum, 0x20);
9818   movq(Address(out, offset, Address::times_4,  0), sum);
9819 
9820   jmp(L_first_loop);
9821   bind(L_first_loop_exit);
9822 }
9823 
9824 /**
9825  * Code for BigInteger::mulAdd() intrinsic
9826  *
9827  * rdi: out
9828  * rsi: in
9829  * r11: offs (out.length - offset)
9830  * rcx: len
9831  * r8:  k
9832  * r12: tmp1
9833  * r13: tmp2
9834  * r14: tmp3
9835  * r15: tmp4
9836  * rbx: tmp5
9837  * Multiply the in[] by word k and add to out[], return the carry in rax
9838  */
9839 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9840    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9841    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9842 
9843   Label L_carry, L_last_in, L_done;
9844 
9845 // carry = 0;
9846 // for (int j=len-1; j >= 0; j--) {
9847 //    long product = (in[j] & LONG_MASK) * kLong +
9848 //                   (out[offs] & LONG_MASK) + carry;
9849 //    out[offs--] = (int)product;
9850 //    carry = product >>> 32;
9851 // }
9852 //
9853   push(tmp1);
9854   push(tmp2);
9855   push(tmp3);
9856   push(tmp4);
9857   push(tmp5);
9858 
9859   Register op2 = tmp2;
9860   const Register sum = tmp3;
9861   const Register op1 = tmp4;
9862   const Register carry =  tmp5;
9863 
9864   if (UseBMI2Instructions) {
9865     op2 = rdxReg;
9866     movl(op2, k);
9867   }
9868   else {
9869     movl(op2, k);
9870   }
9871 
9872   xorq(carry, carry);
9873 
9874   //First loop
9875 
9876   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9877   //The carry is in tmp5
9878   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9879 
9880   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9881   decrementl(len);
9882   jccb(Assembler::negative, L_carry);
9883   decrementl(len);
9884   jccb(Assembler::negative, L_last_in);
9885 
9886   movq(op1, Address(in, len, Address::times_4,  0));
9887   rorq(op1, 32);
9888 
9889   subl(offs, 2);
9890   movq(sum, Address(out, offs, Address::times_4,  0));
9891   rorq(sum, 32);
9892 
9893   if (UseBMI2Instructions) {
9894     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9895   }
9896   else {
9897     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9898   }
9899 
9900   // Store back in big endian from little endian
9901   rorq(sum, 0x20);
9902   movq(Address(out, offs, Address::times_4,  0), sum);
9903 
9904   testl(len, len);
9905   jccb(Assembler::zero, L_carry);
9906 
9907   //Multiply the last in[] entry, if any
9908   bind(L_last_in);
9909   movl(op1, Address(in, 0));
9910   movl(sum, Address(out, offs, Address::times_4,  -4));
9911 
9912   movl(raxReg, k);
9913   mull(op1); //tmp4 * eax -> edx:eax
9914   addl(sum, carry);
9915   adcl(rdxReg, 0);
9916   addl(sum, raxReg);
9917   adcl(rdxReg, 0);
9918   movl(carry, rdxReg);
9919 
9920   movl(Address(out, offs, Address::times_4,  -4), sum);
9921 
9922   bind(L_carry);
9923   //return tmp5/carry as carry in rax
9924   movl(rax, carry);
9925 
9926   bind(L_done);
9927   pop(tmp5);
9928   pop(tmp4);
9929   pop(tmp3);
9930   pop(tmp2);
9931   pop(tmp1);
9932 }
9933 #endif
9934 
9935 /**
9936  * Emits code to update CRC-32 with a byte value according to constants in table
9937  *
9938  * @param [in,out]crc   Register containing the crc.
9939  * @param [in]val       Register containing the byte to fold into the CRC.
9940  * @param [in]table     Register containing the table of crc constants.
9941  *
9942  * uint32_t crc;
9943  * val = crc_table[(val ^ crc) & 0xFF];
9944  * crc = val ^ (crc >> 8);
9945  *
9946  */
9947 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9948   xorl(val, crc);
9949   andl(val, 0xFF);
9950   shrl(crc, 8); // unsigned shift
9951   xorl(crc, Address(table, val, Address::times_4, 0));
9952 }
9953 
9954 /**
9955  * Fold 128-bit data chunk
9956  */
9957 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9958   if (UseAVX > 0) {
9959     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9960     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9961     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9962     pxor(xcrc, xtmp);
9963   } else {
9964     movdqa(xtmp, xcrc);
9965     pclmulhdq(xtmp, xK);   // [123:64]
9966     pclmulldq(xcrc, xK);   // [63:0]
9967     pxor(xcrc, xtmp);
9968     movdqu(xtmp, Address(buf, offset));
9969     pxor(xcrc, xtmp);
9970   }
9971 }
9972 
9973 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9974   if (UseAVX > 0) {
9975     vpclmulhdq(xtmp, xK, xcrc);
9976     vpclmulldq(xcrc, xK, xcrc);
9977     pxor(xcrc, xbuf);
9978     pxor(xcrc, xtmp);
9979   } else {
9980     movdqa(xtmp, xcrc);
9981     pclmulhdq(xtmp, xK);
9982     pclmulldq(xcrc, xK);
9983     pxor(xcrc, xbuf);
9984     pxor(xcrc, xtmp);
9985   }
9986 }
9987 
9988 /**
9989  * 8-bit folds to compute 32-bit CRC
9990  *
9991  * uint64_t xcrc;
9992  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9993  */
9994 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9995   movdl(tmp, xcrc);
9996   andl(tmp, 0xFF);
9997   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9998   psrldq(xcrc, 1); // unsigned shift one byte
9999   pxor(xcrc, xtmp);
10000 }
10001 
10002 /**
10003  * uint32_t crc;
10004  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10005  */
10006 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10007   movl(tmp, crc);
10008   andl(tmp, 0xFF);
10009   shrl(crc, 8);
10010   xorl(crc, Address(table, tmp, Address::times_4, 0));
10011 }
10012 
10013 /**
10014  * @param crc   register containing existing CRC (32-bit)
10015  * @param buf   register pointing to input byte buffer (byte*)
10016  * @param len   register containing number of bytes
10017  * @param table register that will contain address of CRC table
10018  * @param tmp   scratch register
10019  */
10020 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10021   assert_different_registers(crc, buf, len, table, tmp, rax);
10022 
10023   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10024   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10025 
10026   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10027   // context for the registers used, where all instructions below are using 128-bit mode
10028   // On EVEX without VL and BW, these instructions will all be AVX.
10029   if (VM_Version::supports_avx512vlbw()) {
10030     movl(tmp, 0xffff);
10031     kmovwl(k1, tmp);
10032   }
10033 
10034   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10035   notl(crc); // ~crc
10036   cmpl(len, 16);
10037   jcc(Assembler::less, L_tail);
10038 
10039   // Align buffer to 16 bytes
10040   movl(tmp, buf);
10041   andl(tmp, 0xF);
10042   jccb(Assembler::zero, L_aligned);
10043   subl(tmp,  16);
10044   addl(len, tmp);
10045 
10046   align(4);
10047   BIND(L_align_loop);
10048   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10049   update_byte_crc32(crc, rax, table);
10050   increment(buf);
10051   incrementl(tmp);
10052   jccb(Assembler::less, L_align_loop);
10053 
10054   BIND(L_aligned);
10055   movl(tmp, len); // save
10056   shrl(len, 4);
10057   jcc(Assembler::zero, L_tail_restore);
10058 
10059   // Fold crc into first bytes of vector
10060   movdqa(xmm1, Address(buf, 0));
10061   movdl(rax, xmm1);
10062   xorl(crc, rax);
10063   pinsrd(xmm1, crc, 0);
10064   addptr(buf, 16);
10065   subl(len, 4); // len > 0
10066   jcc(Assembler::less, L_fold_tail);
10067 
10068   movdqa(xmm2, Address(buf,  0));
10069   movdqa(xmm3, Address(buf, 16));
10070   movdqa(xmm4, Address(buf, 32));
10071   addptr(buf, 48);
10072   subl(len, 3);
10073   jcc(Assembler::lessEqual, L_fold_512b);
10074 
10075   // Fold total 512 bits of polynomial on each iteration,
10076   // 128 bits per each of 4 parallel streams.
10077   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10078 
10079   align(32);
10080   BIND(L_fold_512b_loop);
10081   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10082   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10083   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10084   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10085   addptr(buf, 64);
10086   subl(len, 4);
10087   jcc(Assembler::greater, L_fold_512b_loop);
10088 
10089   // Fold 512 bits to 128 bits.
10090   BIND(L_fold_512b);
10091   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10092   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10093   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10094   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10095 
10096   // Fold the rest of 128 bits data chunks
10097   BIND(L_fold_tail);
10098   addl(len, 3);
10099   jccb(Assembler::lessEqual, L_fold_128b);
10100   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10101 
10102   BIND(L_fold_tail_loop);
10103   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10104   addptr(buf, 16);
10105   decrementl(len);
10106   jccb(Assembler::greater, L_fold_tail_loop);
10107 
10108   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10109   BIND(L_fold_128b);
10110   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10111   if (UseAVX > 0) {
10112     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10113     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10114     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10115   } else {
10116     movdqa(xmm2, xmm0);
10117     pclmulqdq(xmm2, xmm1, 0x1);
10118     movdqa(xmm3, xmm0);
10119     pand(xmm3, xmm2);
10120     pclmulqdq(xmm0, xmm3, 0x1);
10121   }
10122   psrldq(xmm1, 8);
10123   psrldq(xmm2, 4);
10124   pxor(xmm0, xmm1);
10125   pxor(xmm0, xmm2);
10126 
10127   // 8 8-bit folds to compute 32-bit CRC.
10128   for (int j = 0; j < 4; j++) {
10129     fold_8bit_crc32(xmm0, table, xmm1, rax);
10130   }
10131   movdl(crc, xmm0); // mov 32 bits to general register
10132   for (int j = 0; j < 4; j++) {
10133     fold_8bit_crc32(crc, table, rax);
10134   }
10135 
10136   BIND(L_tail_restore);
10137   movl(len, tmp); // restore
10138   BIND(L_tail);
10139   andl(len, 0xf);
10140   jccb(Assembler::zero, L_exit);
10141 
10142   // Fold the rest of bytes
10143   align(4);
10144   BIND(L_tail_loop);
10145   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10146   update_byte_crc32(crc, rax, table);
10147   increment(buf);
10148   decrementl(len);
10149   jccb(Assembler::greater, L_tail_loop);
10150 
10151   BIND(L_exit);
10152   notl(crc); // ~c
10153 }
10154 
10155 #ifdef _LP64
10156 // S. Gueron / Information Processing Letters 112 (2012) 184
10157 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10158 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10159 // Output: the 64-bit carry-less product of B * CONST
10160 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10161                                      Register tmp1, Register tmp2, Register tmp3) {
10162   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10163   if (n > 0) {
10164     addq(tmp3, n * 256 * 8);
10165   }
10166   //    Q1 = TABLEExt[n][B & 0xFF];
10167   movl(tmp1, in);
10168   andl(tmp1, 0x000000FF);
10169   shll(tmp1, 3);
10170   addq(tmp1, tmp3);
10171   movq(tmp1, Address(tmp1, 0));
10172 
10173   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10174   movl(tmp2, in);
10175   shrl(tmp2, 8);
10176   andl(tmp2, 0x000000FF);
10177   shll(tmp2, 3);
10178   addq(tmp2, tmp3);
10179   movq(tmp2, Address(tmp2, 0));
10180 
10181   shlq(tmp2, 8);
10182   xorq(tmp1, tmp2);
10183 
10184   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10185   movl(tmp2, in);
10186   shrl(tmp2, 16);
10187   andl(tmp2, 0x000000FF);
10188   shll(tmp2, 3);
10189   addq(tmp2, tmp3);
10190   movq(tmp2, Address(tmp2, 0));
10191 
10192   shlq(tmp2, 16);
10193   xorq(tmp1, tmp2);
10194 
10195   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10196   shrl(in, 24);
10197   andl(in, 0x000000FF);
10198   shll(in, 3);
10199   addq(in, tmp3);
10200   movq(in, Address(in, 0));
10201 
10202   shlq(in, 24);
10203   xorq(in, tmp1);
10204   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10205 }
10206 
10207 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10208                                       Register in_out,
10209                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10210                                       XMMRegister w_xtmp2,
10211                                       Register tmp1,
10212                                       Register n_tmp2, Register n_tmp3) {
10213   if (is_pclmulqdq_supported) {
10214     movdl(w_xtmp1, in_out); // modified blindly
10215 
10216     movl(tmp1, const_or_pre_comp_const_index);
10217     movdl(w_xtmp2, tmp1);
10218     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10219 
10220     movdq(in_out, w_xtmp1);
10221   } else {
10222     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10223   }
10224 }
10225 
10226 // Recombination Alternative 2: No bit-reflections
10227 // T1 = (CRC_A * U1) << 1
10228 // T2 = (CRC_B * U2) << 1
10229 // C1 = T1 >> 32
10230 // C2 = T2 >> 32
10231 // T1 = T1 & 0xFFFFFFFF
10232 // T2 = T2 & 0xFFFFFFFF
10233 // T1 = CRC32(0, T1)
10234 // T2 = CRC32(0, T2)
10235 // C1 = C1 ^ T1
10236 // C2 = C2 ^ T2
10237 // CRC = C1 ^ C2 ^ CRC_C
10238 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,
10239                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10240                                      Register tmp1, Register tmp2,
10241                                      Register n_tmp3) {
10242   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10243   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10244   shlq(in_out, 1);
10245   movl(tmp1, in_out);
10246   shrq(in_out, 32);
10247   xorl(tmp2, tmp2);
10248   crc32(tmp2, tmp1, 4);
10249   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10250   shlq(in1, 1);
10251   movl(tmp1, in1);
10252   shrq(in1, 32);
10253   xorl(tmp2, tmp2);
10254   crc32(tmp2, tmp1, 4);
10255   xorl(in1, tmp2);
10256   xorl(in_out, in1);
10257   xorl(in_out, in2);
10258 }
10259 
10260 // Set N to predefined value
10261 // Subtract from a lenght of a buffer
10262 // execute in a loop:
10263 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10264 // for i = 1 to N do
10265 //  CRC_A = CRC32(CRC_A, A[i])
10266 //  CRC_B = CRC32(CRC_B, B[i])
10267 //  CRC_C = CRC32(CRC_C, C[i])
10268 // end for
10269 // Recombine
10270 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,
10271                                        Register in_out1, Register in_out2, Register in_out3,
10272                                        Register tmp1, Register tmp2, Register tmp3,
10273                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10274                                        Register tmp4, Register tmp5,
10275                                        Register n_tmp6) {
10276   Label L_processPartitions;
10277   Label L_processPartition;
10278   Label L_exit;
10279 
10280   bind(L_processPartitions);
10281   cmpl(in_out1, 3 * size);
10282   jcc(Assembler::less, L_exit);
10283     xorl(tmp1, tmp1);
10284     xorl(tmp2, tmp2);
10285     movq(tmp3, in_out2);
10286     addq(tmp3, size);
10287 
10288     bind(L_processPartition);
10289       crc32(in_out3, Address(in_out2, 0), 8);
10290       crc32(tmp1, Address(in_out2, size), 8);
10291       crc32(tmp2, Address(in_out2, size * 2), 8);
10292       addq(in_out2, 8);
10293       cmpq(in_out2, tmp3);
10294       jcc(Assembler::less, L_processPartition);
10295     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10296             w_xtmp1, w_xtmp2, w_xtmp3,
10297             tmp4, tmp5,
10298             n_tmp6);
10299     addq(in_out2, 2 * size);
10300     subl(in_out1, 3 * size);
10301     jmp(L_processPartitions);
10302 
10303   bind(L_exit);
10304 }
10305 #else
10306 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10307                                      Register tmp1, Register tmp2, Register tmp3,
10308                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10309   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10310   if (n > 0) {
10311     addl(tmp3, n * 256 * 8);
10312   }
10313   //    Q1 = TABLEExt[n][B & 0xFF];
10314   movl(tmp1, in_out);
10315   andl(tmp1, 0x000000FF);
10316   shll(tmp1, 3);
10317   addl(tmp1, tmp3);
10318   movq(xtmp1, Address(tmp1, 0));
10319 
10320   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10321   movl(tmp2, in_out);
10322   shrl(tmp2, 8);
10323   andl(tmp2, 0x000000FF);
10324   shll(tmp2, 3);
10325   addl(tmp2, tmp3);
10326   movq(xtmp2, Address(tmp2, 0));
10327 
10328   psllq(xtmp2, 8);
10329   pxor(xtmp1, xtmp2);
10330 
10331   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10332   movl(tmp2, in_out);
10333   shrl(tmp2, 16);
10334   andl(tmp2, 0x000000FF);
10335   shll(tmp2, 3);
10336   addl(tmp2, tmp3);
10337   movq(xtmp2, Address(tmp2, 0));
10338 
10339   psllq(xtmp2, 16);
10340   pxor(xtmp1, xtmp2);
10341 
10342   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10343   shrl(in_out, 24);
10344   andl(in_out, 0x000000FF);
10345   shll(in_out, 3);
10346   addl(in_out, tmp3);
10347   movq(xtmp2, Address(in_out, 0));
10348 
10349   psllq(xtmp2, 24);
10350   pxor(xtmp1, xtmp2); // Result in CXMM
10351   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10352 }
10353 
10354 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10355                                       Register in_out,
10356                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10357                                       XMMRegister w_xtmp2,
10358                                       Register tmp1,
10359                                       Register n_tmp2, Register n_tmp3) {
10360   if (is_pclmulqdq_supported) {
10361     movdl(w_xtmp1, in_out);
10362 
10363     movl(tmp1, const_or_pre_comp_const_index);
10364     movdl(w_xtmp2, tmp1);
10365     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10366     // Keep result in XMM since GPR is 32 bit in length
10367   } else {
10368     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10369   }
10370 }
10371 
10372 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,
10373                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10374                                      Register tmp1, Register tmp2,
10375                                      Register n_tmp3) {
10376   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10377   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10378 
10379   psllq(w_xtmp1, 1);
10380   movdl(tmp1, w_xtmp1);
10381   psrlq(w_xtmp1, 32);
10382   movdl(in_out, w_xtmp1);
10383 
10384   xorl(tmp2, tmp2);
10385   crc32(tmp2, tmp1, 4);
10386   xorl(in_out, tmp2);
10387 
10388   psllq(w_xtmp2, 1);
10389   movdl(tmp1, w_xtmp2);
10390   psrlq(w_xtmp2, 32);
10391   movdl(in1, w_xtmp2);
10392 
10393   xorl(tmp2, tmp2);
10394   crc32(tmp2, tmp1, 4);
10395   xorl(in1, tmp2);
10396   xorl(in_out, in1);
10397   xorl(in_out, in2);
10398 }
10399 
10400 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,
10401                                        Register in_out1, Register in_out2, Register in_out3,
10402                                        Register tmp1, Register tmp2, Register tmp3,
10403                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10404                                        Register tmp4, Register tmp5,
10405                                        Register n_tmp6) {
10406   Label L_processPartitions;
10407   Label L_processPartition;
10408   Label L_exit;
10409 
10410   bind(L_processPartitions);
10411   cmpl(in_out1, 3 * size);
10412   jcc(Assembler::less, L_exit);
10413     xorl(tmp1, tmp1);
10414     xorl(tmp2, tmp2);
10415     movl(tmp3, in_out2);
10416     addl(tmp3, size);
10417 
10418     bind(L_processPartition);
10419       crc32(in_out3, Address(in_out2, 0), 4);
10420       crc32(tmp1, Address(in_out2, size), 4);
10421       crc32(tmp2, Address(in_out2, size*2), 4);
10422       crc32(in_out3, Address(in_out2, 0+4), 4);
10423       crc32(tmp1, Address(in_out2, size+4), 4);
10424       crc32(tmp2, Address(in_out2, size*2+4), 4);
10425       addl(in_out2, 8);
10426       cmpl(in_out2, tmp3);
10427       jcc(Assembler::less, L_processPartition);
10428 
10429         push(tmp3);
10430         push(in_out1);
10431         push(in_out2);
10432         tmp4 = tmp3;
10433         tmp5 = in_out1;
10434         n_tmp6 = in_out2;
10435 
10436       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10437             w_xtmp1, w_xtmp2, w_xtmp3,
10438             tmp4, tmp5,
10439             n_tmp6);
10440 
10441         pop(in_out2);
10442         pop(in_out1);
10443         pop(tmp3);
10444 
10445     addl(in_out2, 2 * size);
10446     subl(in_out1, 3 * size);
10447     jmp(L_processPartitions);
10448 
10449   bind(L_exit);
10450 }
10451 #endif //LP64
10452 
10453 #ifdef _LP64
10454 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10455 // Input: A buffer I of L bytes.
10456 // Output: the CRC32C value of the buffer.
10457 // Notations:
10458 // Write L = 24N + r, with N = floor (L/24).
10459 // r = L mod 24 (0 <= r < 24).
10460 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10461 // N quadwords, and R consists of r bytes.
10462 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10463 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10464 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10465 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10466 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10467                                           Register tmp1, Register tmp2, Register tmp3,
10468                                           Register tmp4, Register tmp5, Register tmp6,
10469                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10470                                           bool is_pclmulqdq_supported) {
10471   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10472   Label L_wordByWord;
10473   Label L_byteByByteProlog;
10474   Label L_byteByByte;
10475   Label L_exit;
10476 
10477   if (is_pclmulqdq_supported ) {
10478     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10479     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10480 
10481     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10482     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10483 
10484     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10485     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10486     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10487   } else {
10488     const_or_pre_comp_const_index[0] = 1;
10489     const_or_pre_comp_const_index[1] = 0;
10490 
10491     const_or_pre_comp_const_index[2] = 3;
10492     const_or_pre_comp_const_index[3] = 2;
10493 
10494     const_or_pre_comp_const_index[4] = 5;
10495     const_or_pre_comp_const_index[5] = 4;
10496    }
10497   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10498                     in2, in1, in_out,
10499                     tmp1, tmp2, tmp3,
10500                     w_xtmp1, w_xtmp2, w_xtmp3,
10501                     tmp4, tmp5,
10502                     tmp6);
10503   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10504                     in2, in1, in_out,
10505                     tmp1, tmp2, tmp3,
10506                     w_xtmp1, w_xtmp2, w_xtmp3,
10507                     tmp4, tmp5,
10508                     tmp6);
10509   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10510                     in2, in1, in_out,
10511                     tmp1, tmp2, tmp3,
10512                     w_xtmp1, w_xtmp2, w_xtmp3,
10513                     tmp4, tmp5,
10514                     tmp6);
10515   movl(tmp1, in2);
10516   andl(tmp1, 0x00000007);
10517   negl(tmp1);
10518   addl(tmp1, in2);
10519   addq(tmp1, in1);
10520 
10521   BIND(L_wordByWord);
10522   cmpq(in1, tmp1);
10523   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10524     crc32(in_out, Address(in1, 0), 4);
10525     addq(in1, 4);
10526     jmp(L_wordByWord);
10527 
10528   BIND(L_byteByByteProlog);
10529   andl(in2, 0x00000007);
10530   movl(tmp2, 1);
10531 
10532   BIND(L_byteByByte);
10533   cmpl(tmp2, in2);
10534   jccb(Assembler::greater, L_exit);
10535     crc32(in_out, Address(in1, 0), 1);
10536     incq(in1);
10537     incl(tmp2);
10538     jmp(L_byteByByte);
10539 
10540   BIND(L_exit);
10541 }
10542 #else
10543 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10544                                           Register tmp1, Register  tmp2, Register tmp3,
10545                                           Register tmp4, Register  tmp5, Register tmp6,
10546                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10547                                           bool is_pclmulqdq_supported) {
10548   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10549   Label L_wordByWord;
10550   Label L_byteByByteProlog;
10551   Label L_byteByByte;
10552   Label L_exit;
10553 
10554   if (is_pclmulqdq_supported) {
10555     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10556     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10557 
10558     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10559     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10560 
10561     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10562     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10563   } else {
10564     const_or_pre_comp_const_index[0] = 1;
10565     const_or_pre_comp_const_index[1] = 0;
10566 
10567     const_or_pre_comp_const_index[2] = 3;
10568     const_or_pre_comp_const_index[3] = 2;
10569 
10570     const_or_pre_comp_const_index[4] = 5;
10571     const_or_pre_comp_const_index[5] = 4;
10572   }
10573   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10574                     in2, in1, in_out,
10575                     tmp1, tmp2, tmp3,
10576                     w_xtmp1, w_xtmp2, w_xtmp3,
10577                     tmp4, tmp5,
10578                     tmp6);
10579   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10580                     in2, in1, in_out,
10581                     tmp1, tmp2, tmp3,
10582                     w_xtmp1, w_xtmp2, w_xtmp3,
10583                     tmp4, tmp5,
10584                     tmp6);
10585   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10586                     in2, in1, in_out,
10587                     tmp1, tmp2, tmp3,
10588                     w_xtmp1, w_xtmp2, w_xtmp3,
10589                     tmp4, tmp5,
10590                     tmp6);
10591   movl(tmp1, in2);
10592   andl(tmp1, 0x00000007);
10593   negl(tmp1);
10594   addl(tmp1, in2);
10595   addl(tmp1, in1);
10596 
10597   BIND(L_wordByWord);
10598   cmpl(in1, tmp1);
10599   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10600     crc32(in_out, Address(in1,0), 4);
10601     addl(in1, 4);
10602     jmp(L_wordByWord);
10603 
10604   BIND(L_byteByByteProlog);
10605   andl(in2, 0x00000007);
10606   movl(tmp2, 1);
10607 
10608   BIND(L_byteByByte);
10609   cmpl(tmp2, in2);
10610   jccb(Assembler::greater, L_exit);
10611     movb(tmp1, Address(in1, 0));
10612     crc32(in_out, tmp1, 1);
10613     incl(in1);
10614     incl(tmp2);
10615     jmp(L_byteByByte);
10616 
10617   BIND(L_exit);
10618 }
10619 #endif // LP64
10620 #undef BIND
10621 #undef BLOCK_COMMENT
10622 
10623 
10624 // Compress char[] array to byte[].
10625 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10626                                          XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10627                                          XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10628                                          Register tmp5, Register result) {
10629   Label copy_chars_loop, return_length, return_zero, done;
10630 
10631   // rsi: src
10632   // rdi: dst
10633   // rdx: len
10634   // rcx: tmp5
10635   // rax: result
10636 
10637   // rsi holds start addr of source char[] to be compressed
10638   // rdi holds start addr of destination byte[]
10639   // rdx holds length
10640 
10641   assert(len != result, "");
10642 
10643   // save length for return
10644   push(len);
10645 
10646   if (UseSSE42Intrinsics) {
10647     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10648     Label copy_32_loop, copy_16, copy_tail;
10649 
10650     movl(result, len);
10651     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10652 
10653     // vectored compression
10654     andl(len, 0xfffffff0);    // vector count (in chars)
10655     andl(result, 0x0000000f);    // tail count (in chars)
10656     testl(len, len);
10657     jccb(Assembler::zero, copy_16);
10658 
10659     // compress 16 chars per iter
10660     movdl(tmp1Reg, tmp5);
10661     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10662     pxor(tmp4Reg, tmp4Reg);
10663 
10664     lea(src, Address(src, len, Address::times_2));
10665     lea(dst, Address(dst, len, Address::times_1));
10666     negptr(len);
10667 
10668     bind(copy_32_loop);
10669     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10670     por(tmp4Reg, tmp2Reg);
10671     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10672     por(tmp4Reg, tmp3Reg);
10673     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10674     jcc(Assembler::notZero, return_zero);
10675     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10676     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10677     addptr(len, 16);
10678     jcc(Assembler::notZero, copy_32_loop);
10679 
10680     // compress next vector of 8 chars (if any)
10681     bind(copy_16);
10682     movl(len, result);
10683     andl(len, 0xfffffff8);    // vector count (in chars)
10684     andl(result, 0x00000007);    // tail count (in chars)
10685     testl(len, len);
10686     jccb(Assembler::zero, copy_tail);
10687 
10688     movdl(tmp1Reg, tmp5);
10689     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10690     pxor(tmp3Reg, tmp3Reg);
10691 
10692     movdqu(tmp2Reg, Address(src, 0));
10693     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10694     jccb(Assembler::notZero, return_zero);
10695     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10696     movq(Address(dst, 0), tmp2Reg);
10697     addptr(src, 16);
10698     addptr(dst, 8);
10699 
10700     bind(copy_tail);
10701     movl(len, result);
10702   }
10703   // compress 1 char per iter
10704   testl(len, len);
10705   jccb(Assembler::zero, return_length);
10706   lea(src, Address(src, len, Address::times_2));
10707   lea(dst, Address(dst, len, Address::times_1));
10708   negptr(len);
10709 
10710   bind(copy_chars_loop);
10711   load_unsigned_short(result, Address(src, len, Address::times_2));
10712   testl(result, 0xff00);      // check if Unicode char
10713   jccb(Assembler::notZero, return_zero);
10714   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10715   increment(len);
10716   jcc(Assembler::notZero, copy_chars_loop);
10717 
10718   // if compression succeeded, return length
10719   bind(return_length);
10720   pop(result);
10721   jmpb(done);
10722 
10723   // if compression failed, return 0
10724   bind(return_zero);
10725   xorl(result, result);
10726   addptr(rsp, wordSize);
10727 
10728   bind(done);
10729 }
10730 
10731 // Inflate byte[] array to char[].
10732 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10733                                         XMMRegister tmp1, Register tmp2) {
10734   Label copy_chars_loop, done;
10735 
10736   // rsi: src
10737   // rdi: dst
10738   // rdx: len
10739   // rcx: tmp2
10740 
10741   // rsi holds start addr of source byte[] to be inflated
10742   // rdi holds start addr of destination char[]
10743   // rdx holds length
10744   assert_different_registers(src, dst, len, tmp2);
10745 
10746   if (UseSSE42Intrinsics) {
10747     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10748     Label copy_8_loop, copy_bytes, copy_tail;
10749 
10750     movl(tmp2, len);
10751     andl(tmp2, 0x00000007);   // tail count (in chars)
10752     andl(len, 0xfffffff8);    // vector count (in chars)
10753     jccb(Assembler::zero, copy_tail);
10754 
10755     // vectored inflation
10756     lea(src, Address(src, len, Address::times_1));
10757     lea(dst, Address(dst, len, Address::times_2));
10758     negptr(len);
10759 
10760     // inflate 8 chars per iter
10761     bind(copy_8_loop);
10762     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10763     movdqu(Address(dst, len, Address::times_2), tmp1);
10764     addptr(len, 8);
10765     jcc(Assembler::notZero, copy_8_loop);
10766 
10767     bind(copy_tail);
10768     movl(len, tmp2);
10769 
10770     cmpl(len, 4);
10771     jccb(Assembler::less, copy_bytes);
10772 
10773     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10774     pmovzxbw(tmp1, tmp1);
10775     movq(Address(dst, 0), tmp1);
10776     subptr(len, 4);
10777     addptr(src, 4);
10778     addptr(dst, 8);
10779 
10780     bind(copy_bytes);
10781   }
10782   testl(len, len);
10783   jccb(Assembler::zero, done);
10784   lea(src, Address(src, len, Address::times_1));
10785   lea(dst, Address(dst, len, Address::times_2));
10786   negptr(len);
10787 
10788   // inflate 1 char per iter
10789   bind(copy_chars_loop);
10790   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10791   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10792   increment(len);
10793   jcc(Assembler::notZero, copy_chars_loop);
10794 
10795   bind(done);
10796 }
10797 
10798 
10799 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10800   switch (cond) {
10801     // Note some conditions are synonyms for others
10802     case Assembler::zero:         return Assembler::notZero;
10803     case Assembler::notZero:      return Assembler::zero;
10804     case Assembler::less:         return Assembler::greaterEqual;
10805     case Assembler::lessEqual:    return Assembler::greater;
10806     case Assembler::greater:      return Assembler::lessEqual;
10807     case Assembler::greaterEqual: return Assembler::less;
10808     case Assembler::below:        return Assembler::aboveEqual;
10809     case Assembler::belowEqual:   return Assembler::above;
10810     case Assembler::above:        return Assembler::belowEqual;
10811     case Assembler::aboveEqual:   return Assembler::below;
10812     case Assembler::overflow:     return Assembler::noOverflow;
10813     case Assembler::noOverflow:   return Assembler::overflow;
10814     case Assembler::negative:     return Assembler::positive;
10815     case Assembler::positive:     return Assembler::negative;
10816     case Assembler::parity:       return Assembler::noParity;
10817     case Assembler::noParity:     return Assembler::parity;
10818   }
10819   ShouldNotReachHere(); return Assembler::overflow;
10820 }
10821 
10822 SkipIfEqual::SkipIfEqual(
10823     MacroAssembler* masm, const bool* flag_addr, bool value) {
10824   _masm = masm;
10825   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10826   _masm->jcc(Assembler::equal, _label);
10827 }
10828 
10829 SkipIfEqual::~SkipIfEqual() {
10830   _masm->bind(_label);
10831 }