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