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::addpd(XMMRegister dst, AddressLiteral src) {
 975   if (reachable(src)) {
 976     Assembler::addpd(dst, as_Address(src));
 977   } else {
 978     lea(rscratch1, src);
 979     Assembler::addpd(dst, Address(rscratch1, 0));
 980   }
 981 }
 982 
 983 void MacroAssembler::align(int modulus) {
 984   align(modulus, offset());
 985 }
 986 
 987 void MacroAssembler::align(int modulus, int target) {
 988   if (target % modulus != 0) {
 989     nop(modulus - (target % modulus));
 990   }
 991 }
 992 
 993 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 994   // Used in sign-masking with aligned address.
 995   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 996   if (reachable(src)) {
 997     Assembler::andpd(dst, as_Address(src));
 998   } else {
 999     lea(rscratch1, src);
1000     Assembler::andpd(dst, Address(rscratch1, 0));
1001   }
1002 }
1003 
1004 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1005   // Used in sign-masking with aligned address.
1006   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1007   if (reachable(src)) {
1008     Assembler::andps(dst, as_Address(src));
1009   } else {
1010     lea(rscratch1, src);
1011     Assembler::andps(dst, Address(rscratch1, 0));
1012   }
1013 }
1014 
1015 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1016   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1017 }
1018 
1019 void MacroAssembler::atomic_incl(Address counter_addr) {
1020   if (os::is_MP())
1021     lock();
1022   incrementl(counter_addr);
1023 }
1024 
1025 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1026   if (reachable(counter_addr)) {
1027     atomic_incl(as_Address(counter_addr));
1028   } else {
1029     lea(scr, counter_addr);
1030     atomic_incl(Address(scr, 0));
1031   }
1032 }
1033 
1034 #ifdef _LP64
1035 void MacroAssembler::atomic_incq(Address counter_addr) {
1036   if (os::is_MP())
1037     lock();
1038   incrementq(counter_addr);
1039 }
1040 
1041 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1042   if (reachable(counter_addr)) {
1043     atomic_incq(as_Address(counter_addr));
1044   } else {
1045     lea(scr, counter_addr);
1046     atomic_incq(Address(scr, 0));
1047   }
1048 }
1049 #endif
1050 
1051 // Writes to stack successive pages until offset reached to check for
1052 // stack overflow + shadow pages.  This clobbers tmp.
1053 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1054   movptr(tmp, rsp);
1055   // Bang stack for total size given plus shadow page size.
1056   // Bang one page at a time because large size can bang beyond yellow and
1057   // red zones.
1058   Label loop;
1059   bind(loop);
1060   movl(Address(tmp, (-os::vm_page_size())), size );
1061   subptr(tmp, os::vm_page_size());
1062   subl(size, os::vm_page_size());
1063   jcc(Assembler::greater, loop);
1064 
1065   // Bang down shadow pages too.
1066   // At this point, (tmp-0) is the last address touched, so don't
1067   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1068   // was post-decremented.)  Skip this address by starting at i=1, and
1069   // touch a few more pages below.  N.B.  It is important to touch all
1070   // the way down to and including i=StackShadowPages.
1071   for (int i = 1; i < StackShadowPages; i++) {
1072     // this could be any sized move but this is can be a debugging crumb
1073     // so the bigger the better.
1074     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1075   }
1076 }
1077 
1078 int MacroAssembler::biased_locking_enter(Register lock_reg,
1079                                          Register obj_reg,
1080                                          Register swap_reg,
1081                                          Register tmp_reg,
1082                                          bool swap_reg_contains_mark,
1083                                          Label& done,
1084                                          Label* slow_case,
1085                                          BiasedLockingCounters* counters) {
1086   assert(UseBiasedLocking, "why call this otherwise?");
1087   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1088   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1089   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1090   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1091   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1092   Address saved_mark_addr(lock_reg, 0);
1093 
1094   if (PrintBiasedLockingStatistics && counters == NULL) {
1095     counters = BiasedLocking::counters();
1096   }
1097   // Biased locking
1098   // See whether the lock is currently biased toward our thread and
1099   // whether the epoch is still valid
1100   // Note that the runtime guarantees sufficient alignment of JavaThread
1101   // pointers to allow age to be placed into low bits
1102   // First check to see whether biasing is even enabled for this object
1103   Label cas_label;
1104   int null_check_offset = -1;
1105   if (!swap_reg_contains_mark) {
1106     null_check_offset = offset();
1107     movptr(swap_reg, mark_addr);
1108   }
1109   movptr(tmp_reg, swap_reg);
1110   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1111   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1112   jcc(Assembler::notEqual, cas_label);
1113   // The bias pattern is present in the object's header. Need to check
1114   // whether the bias owner and the epoch are both still current.
1115 #ifndef _LP64
1116   // Note that because there is no current thread register on x86_32 we
1117   // need to store off the mark word we read out of the object to
1118   // avoid reloading it and needing to recheck invariants below. This
1119   // store is unfortunate but it makes the overall code shorter and
1120   // simpler.
1121   movptr(saved_mark_addr, swap_reg);
1122 #endif
1123   if (swap_reg_contains_mark) {
1124     null_check_offset = offset();
1125   }
1126   load_prototype_header(tmp_reg, obj_reg);
1127 #ifdef _LP64
1128   orptr(tmp_reg, r15_thread);
1129   xorptr(tmp_reg, swap_reg);
1130   Register header_reg = tmp_reg;
1131 #else
1132   xorptr(tmp_reg, swap_reg);
1133   get_thread(swap_reg);
1134   xorptr(swap_reg, tmp_reg);
1135   Register header_reg = swap_reg;
1136 #endif
1137   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1138   if (counters != NULL) {
1139     cond_inc32(Assembler::zero,
1140                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1141   }
1142   jcc(Assembler::equal, done);
1143 
1144   Label try_revoke_bias;
1145   Label try_rebias;
1146 
1147   // At this point we know that the header has the bias pattern and
1148   // that we are not the bias owner in the current epoch. We need to
1149   // figure out more details about the state of the header in order to
1150   // know what operations can be legally performed on the object's
1151   // header.
1152 
1153   // If the low three bits in the xor result aren't clear, that means
1154   // the prototype header is no longer biased and we have to revoke
1155   // the bias on this object.
1156   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1157   jccb(Assembler::notZero, try_revoke_bias);
1158 
1159   // Biasing is still enabled for this data type. See whether the
1160   // epoch of the current bias is still valid, meaning that the epoch
1161   // bits of the mark word are equal to the epoch bits of the
1162   // prototype header. (Note that the prototype header's epoch bits
1163   // only change at a safepoint.) If not, attempt to rebias the object
1164   // toward the current thread. Note that we must be absolutely sure
1165   // that the current epoch is invalid in order to do this because
1166   // otherwise the manipulations it performs on the mark word are
1167   // illegal.
1168   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1169   jccb(Assembler::notZero, try_rebias);
1170 
1171   // The epoch of the current bias is still valid but we know nothing
1172   // about the owner; it might be set or it might be clear. Try to
1173   // acquire the bias of the object using an atomic operation. If this
1174   // fails we will go in to the runtime to revoke the object's bias.
1175   // Note that we first construct the presumed unbiased header so we
1176   // don't accidentally blow away another thread's valid bias.
1177   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1178   andptr(swap_reg,
1179          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1180 #ifdef _LP64
1181   movptr(tmp_reg, swap_reg);
1182   orptr(tmp_reg, r15_thread);
1183 #else
1184   get_thread(tmp_reg);
1185   orptr(tmp_reg, swap_reg);
1186 #endif
1187   if (os::is_MP()) {
1188     lock();
1189   }
1190   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1191   // If the biasing toward our thread failed, this means that
1192   // another thread succeeded in biasing it toward itself and we
1193   // need to revoke that bias. The revocation will occur in the
1194   // interpreter runtime in the slow case.
1195   if (counters != NULL) {
1196     cond_inc32(Assembler::zero,
1197                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1198   }
1199   if (slow_case != NULL) {
1200     jcc(Assembler::notZero, *slow_case);
1201   }
1202   jmp(done);
1203 
1204   bind(try_rebias);
1205   // At this point we know the epoch has expired, meaning that the
1206   // current "bias owner", if any, is actually invalid. Under these
1207   // circumstances _only_, we are allowed to use the current header's
1208   // value as the comparison value when doing the cas to acquire the
1209   // bias in the current epoch. In other words, we allow transfer of
1210   // the bias from one thread to another directly in this situation.
1211   //
1212   // FIXME: due to a lack of registers we currently blow away the age
1213   // bits in this situation. Should attempt to preserve them.
1214   load_prototype_header(tmp_reg, obj_reg);
1215 #ifdef _LP64
1216   orptr(tmp_reg, r15_thread);
1217 #else
1218   get_thread(swap_reg);
1219   orptr(tmp_reg, swap_reg);
1220   movptr(swap_reg, saved_mark_addr);
1221 #endif
1222   if (os::is_MP()) {
1223     lock();
1224   }
1225   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1226   // If the biasing toward our thread failed, then another thread
1227   // succeeded in biasing it toward itself and we need to revoke that
1228   // bias. The revocation will occur in the runtime in the slow case.
1229   if (counters != NULL) {
1230     cond_inc32(Assembler::zero,
1231                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1232   }
1233   if (slow_case != NULL) {
1234     jcc(Assembler::notZero, *slow_case);
1235   }
1236   jmp(done);
1237 
1238   bind(try_revoke_bias);
1239   // The prototype mark in the klass doesn't have the bias bit set any
1240   // more, indicating that objects of this data type are not supposed
1241   // to be biased any more. We are going to try to reset the mark of
1242   // this object to the prototype value and fall through to the
1243   // CAS-based locking scheme. Note that if our CAS fails, it means
1244   // that another thread raced us for the privilege of revoking the
1245   // bias of this particular object, so it's okay to continue in the
1246   // normal locking code.
1247   //
1248   // FIXME: due to a lack of registers we currently blow away the age
1249   // bits in this situation. Should attempt to preserve them.
1250   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1251   load_prototype_header(tmp_reg, obj_reg);
1252   if (os::is_MP()) {
1253     lock();
1254   }
1255   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1256   // Fall through to the normal CAS-based lock, because no matter what
1257   // the result of the above CAS, some thread must have succeeded in
1258   // removing the bias bit from the object's header.
1259   if (counters != NULL) {
1260     cond_inc32(Assembler::zero,
1261                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1262   }
1263 
1264   bind(cas_label);
1265 
1266   return null_check_offset;
1267 }
1268 
1269 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1270   assert(UseBiasedLocking, "why call this otherwise?");
1271 
1272   // Check for biased locking unlock case, which is a no-op
1273   // Note: we do not have to check the thread ID for two reasons.
1274   // First, the interpreter checks for IllegalMonitorStateException at
1275   // a higher level. Second, if the bias was revoked while we held the
1276   // lock, the object could not be rebiased toward another thread, so
1277   // the bias bit would be clear.
1278   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1279   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1280   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1281   jcc(Assembler::equal, done);
1282 }
1283 
1284 #ifdef COMPILER2
1285 
1286 #if INCLUDE_RTM_OPT
1287 
1288 // Update rtm_counters based on abort status
1289 // input: abort_status
1290 //        rtm_counters (RTMLockingCounters*)
1291 // flags are killed
1292 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1293 
1294   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1295   if (PrintPreciseRTMLockingStatistics) {
1296     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1297       Label check_abort;
1298       testl(abort_status, (1<<i));
1299       jccb(Assembler::equal, check_abort);
1300       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1301       bind(check_abort);
1302     }
1303   }
1304 }
1305 
1306 // Branch if (random & (count-1) != 0), count is 2^n
1307 // tmp, scr and flags are killed
1308 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1309   assert(tmp == rax, "");
1310   assert(scr == rdx, "");
1311   rdtsc(); // modifies EDX:EAX
1312   andptr(tmp, count-1);
1313   jccb(Assembler::notZero, brLabel);
1314 }
1315 
1316 // Perform abort ratio calculation, set no_rtm bit if high ratio
1317 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1318 // tmpReg, rtm_counters_Reg and flags are killed
1319 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1320                                                  Register rtm_counters_Reg,
1321                                                  RTMLockingCounters* rtm_counters,
1322                                                  Metadata* method_data) {
1323   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1324 
1325   if (RTMLockingCalculationDelay > 0) {
1326     // Delay calculation
1327     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1328     testptr(tmpReg, tmpReg);
1329     jccb(Assembler::equal, L_done);
1330   }
1331   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1332   //   Aborted transactions = abort_count * 100
1333   //   All transactions = total_count *  RTMTotalCountIncrRate
1334   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1335 
1336   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1337   cmpptr(tmpReg, RTMAbortThreshold);
1338   jccb(Assembler::below, L_check_always_rtm2);
1339   imulptr(tmpReg, tmpReg, 100);
1340 
1341   Register scrReg = rtm_counters_Reg;
1342   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1343   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1344   imulptr(scrReg, scrReg, RTMAbortRatio);
1345   cmpptr(tmpReg, scrReg);
1346   jccb(Assembler::below, L_check_always_rtm1);
1347   if (method_data != NULL) {
1348     // set rtm_state to "no rtm" in MDO
1349     mov_metadata(tmpReg, method_data);
1350     if (os::is_MP()) {
1351       lock();
1352     }
1353     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1354   }
1355   jmpb(L_done);
1356   bind(L_check_always_rtm1);
1357   // Reload RTMLockingCounters* address
1358   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1359   bind(L_check_always_rtm2);
1360   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1361   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1362   jccb(Assembler::below, L_done);
1363   if (method_data != NULL) {
1364     // set rtm_state to "always rtm" in MDO
1365     mov_metadata(tmpReg, method_data);
1366     if (os::is_MP()) {
1367       lock();
1368     }
1369     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1370   }
1371   bind(L_done);
1372 }
1373 
1374 // Update counters and perform abort ratio calculation
1375 // input:  abort_status_Reg
1376 // rtm_counters_Reg, flags are killed
1377 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1378                                    Register rtm_counters_Reg,
1379                                    RTMLockingCounters* rtm_counters,
1380                                    Metadata* method_data,
1381                                    bool profile_rtm) {
1382 
1383   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1384   // update rtm counters based on rax value at abort
1385   // reads abort_status_Reg, updates flags
1386   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1387   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1388   if (profile_rtm) {
1389     // Save abort status because abort_status_Reg is used by following code.
1390     if (RTMRetryCount > 0) {
1391       push(abort_status_Reg);
1392     }
1393     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1394     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1395     // restore abort status
1396     if (RTMRetryCount > 0) {
1397       pop(abort_status_Reg);
1398     }
1399   }
1400 }
1401 
1402 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1403 // inputs: retry_count_Reg
1404 //       : abort_status_Reg
1405 // output: retry_count_Reg decremented by 1
1406 // flags are killed
1407 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1408   Label doneRetry;
1409   assert(abort_status_Reg == rax, "");
1410   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1411   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1412   // if reason is in 0x6 and retry count != 0 then retry
1413   andptr(abort_status_Reg, 0x6);
1414   jccb(Assembler::zero, doneRetry);
1415   testl(retry_count_Reg, retry_count_Reg);
1416   jccb(Assembler::zero, doneRetry);
1417   pause();
1418   decrementl(retry_count_Reg);
1419   jmp(retryLabel);
1420   bind(doneRetry);
1421 }
1422 
1423 // Spin and retry if lock is busy,
1424 // inputs: box_Reg (monitor address)
1425 //       : retry_count_Reg
1426 // output: retry_count_Reg decremented by 1
1427 //       : clear z flag if retry count exceeded
1428 // tmp_Reg, scr_Reg, flags are killed
1429 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1430                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1431   Label SpinLoop, SpinExit, doneRetry;
1432   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1433 
1434   testl(retry_count_Reg, retry_count_Reg);
1435   jccb(Assembler::zero, doneRetry);
1436   decrementl(retry_count_Reg);
1437   movptr(scr_Reg, RTMSpinLoopCount);
1438 
1439   bind(SpinLoop);
1440   pause();
1441   decrementl(scr_Reg);
1442   jccb(Assembler::lessEqual, SpinExit);
1443   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1444   testptr(tmp_Reg, tmp_Reg);
1445   jccb(Assembler::notZero, SpinLoop);
1446 
1447   bind(SpinExit);
1448   jmp(retryLabel);
1449   bind(doneRetry);
1450   incrementl(retry_count_Reg); // clear z flag
1451 }
1452 
1453 // Use RTM for normal stack locks
1454 // Input: objReg (object to lock)
1455 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1456                                        Register retry_on_abort_count_Reg,
1457                                        RTMLockingCounters* stack_rtm_counters,
1458                                        Metadata* method_data, bool profile_rtm,
1459                                        Label& DONE_LABEL, Label& IsInflated) {
1460   assert(UseRTMForStackLocks, "why call this otherwise?");
1461   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1462   assert(tmpReg == rax, "");
1463   assert(scrReg == rdx, "");
1464   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1465 
1466   if (RTMRetryCount > 0) {
1467     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1468     bind(L_rtm_retry);
1469   }
1470   movptr(tmpReg, Address(objReg, 0));
1471   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1472   jcc(Assembler::notZero, IsInflated);
1473 
1474   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1475     Label L_noincrement;
1476     if (RTMTotalCountIncrRate > 1) {
1477       // tmpReg, scrReg and flags are killed
1478       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1479     }
1480     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1481     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1482     bind(L_noincrement);
1483   }
1484   xbegin(L_on_abort);
1485   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1486   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1487   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1488   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1489 
1490   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1491   if (UseRTMXendForLockBusy) {
1492     xend();
1493     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1494     jmp(L_decrement_retry);
1495   }
1496   else {
1497     xabort(0);
1498   }
1499   bind(L_on_abort);
1500   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1501     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1502   }
1503   bind(L_decrement_retry);
1504   if (RTMRetryCount > 0) {
1505     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1506     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1507   }
1508 }
1509 
1510 // Use RTM for inflating locks
1511 // inputs: objReg (object to lock)
1512 //         boxReg (on-stack box address (displaced header location) - KILLED)
1513 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1514 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1515                                           Register scrReg, Register retry_on_busy_count_Reg,
1516                                           Register retry_on_abort_count_Reg,
1517                                           RTMLockingCounters* rtm_counters,
1518                                           Metadata* method_data, bool profile_rtm,
1519                                           Label& DONE_LABEL) {
1520   assert(UseRTMLocking, "why call this otherwise?");
1521   assert(tmpReg == rax, "");
1522   assert(scrReg == rdx, "");
1523   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1524   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1525 
1526   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1527   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1528   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1529 
1530   if (RTMRetryCount > 0) {
1531     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1532     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1533     bind(L_rtm_retry);
1534   }
1535   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1536     Label L_noincrement;
1537     if (RTMTotalCountIncrRate > 1) {
1538       // tmpReg, scrReg and flags are killed
1539       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1540     }
1541     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1542     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1543     bind(L_noincrement);
1544   }
1545   xbegin(L_on_abort);
1546   movptr(tmpReg, Address(objReg, 0));
1547   movptr(tmpReg, Address(tmpReg, owner_offset));
1548   testptr(tmpReg, tmpReg);
1549   jcc(Assembler::zero, DONE_LABEL);
1550   if (UseRTMXendForLockBusy) {
1551     xend();
1552     jmp(L_decrement_retry);
1553   }
1554   else {
1555     xabort(0);
1556   }
1557   bind(L_on_abort);
1558   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1559   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1560     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1561   }
1562   if (RTMRetryCount > 0) {
1563     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1564     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1565   }
1566 
1567   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1568   testptr(tmpReg, tmpReg) ;
1569   jccb(Assembler::notZero, L_decrement_retry) ;
1570 
1571   // Appears unlocked - try to swing _owner from null to non-null.
1572   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1573 #ifdef _LP64
1574   Register threadReg = r15_thread;
1575 #else
1576   get_thread(scrReg);
1577   Register threadReg = scrReg;
1578 #endif
1579   if (os::is_MP()) {
1580     lock();
1581   }
1582   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1583 
1584   if (RTMRetryCount > 0) {
1585     // success done else retry
1586     jccb(Assembler::equal, DONE_LABEL) ;
1587     bind(L_decrement_retry);
1588     // Spin and retry if lock is busy.
1589     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1590   }
1591   else {
1592     bind(L_decrement_retry);
1593   }
1594 }
1595 
1596 #endif //  INCLUDE_RTM_OPT
1597 
1598 // Fast_Lock and Fast_Unlock used by C2
1599 
1600 // Because the transitions from emitted code to the runtime
1601 // monitorenter/exit helper stubs are so slow it's critical that
1602 // we inline both the stack-locking fast-path and the inflated fast path.
1603 //
1604 // See also: cmpFastLock and cmpFastUnlock.
1605 //
1606 // What follows is a specialized inline transliteration of the code
1607 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1608 // another option would be to emit TrySlowEnter and TrySlowExit methods
1609 // at startup-time.  These methods would accept arguments as
1610 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1611 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1612 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1613 // In practice, however, the # of lock sites is bounded and is usually small.
1614 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1615 // if the processor uses simple bimodal branch predictors keyed by EIP
1616 // Since the helper routines would be called from multiple synchronization
1617 // sites.
1618 //
1619 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1620 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1621 // to those specialized methods.  That'd give us a mostly platform-independent
1622 // implementation that the JITs could optimize and inline at their pleasure.
1623 // Done correctly, the only time we'd need to cross to native could would be
1624 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1625 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1626 // (b) explicit barriers or fence operations.
1627 //
1628 // TODO:
1629 //
1630 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1631 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1632 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1633 //    the lock operators would typically be faster than reifying Self.
1634 //
1635 // *  Ideally I'd define the primitives as:
1636 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1637 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1638 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1639 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1640 //    Furthermore the register assignments are overconstrained, possibly resulting in
1641 //    sub-optimal code near the synchronization site.
1642 //
1643 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1644 //    Alternately, use a better sp-proximity test.
1645 //
1646 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1647 //    Either one is sufficient to uniquely identify a thread.
1648 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1649 //
1650 // *  Intrinsify notify() and notifyAll() for the common cases where the
1651 //    object is locked by the calling thread but the waitlist is empty.
1652 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1653 //
1654 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1655 //    But beware of excessive branch density on AMD Opterons.
1656 //
1657 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1658 //    or failure of the fast-path.  If the fast-path fails then we pass
1659 //    control to the slow-path, typically in C.  In Fast_Lock and
1660 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1661 //    will emit a conditional branch immediately after the node.
1662 //    So we have branches to branches and lots of ICC.ZF games.
1663 //    Instead, it might be better to have C2 pass a "FailureLabel"
1664 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1665 //    will drop through the node.  ICC.ZF is undefined at exit.
1666 //    In the case of failure, the node will branch directly to the
1667 //    FailureLabel
1668 
1669 
1670 // obj: object to lock
1671 // box: on-stack box address (displaced header location) - KILLED
1672 // rax,: tmp -- KILLED
1673 // scr: tmp -- KILLED
1674 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1675                                Register scrReg, Register cx1Reg, Register cx2Reg,
1676                                BiasedLockingCounters* counters,
1677                                RTMLockingCounters* rtm_counters,
1678                                RTMLockingCounters* stack_rtm_counters,
1679                                Metadata* method_data,
1680                                bool use_rtm, bool profile_rtm) {
1681   // Ensure the register assignents are disjoint
1682   assert(tmpReg == rax, "");
1683 
1684   if (use_rtm) {
1685     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1686   } else {
1687     assert(cx1Reg == noreg, "");
1688     assert(cx2Reg == noreg, "");
1689     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1690   }
1691 
1692   if (counters != NULL) {
1693     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1694   }
1695   if (EmitSync & 1) {
1696       // set box->dhw = markOopDesc::unused_mark()
1697       // Force all sync thru slow-path: slow_enter() and slow_exit()
1698       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1699       cmpptr (rsp, (int32_t)NULL_WORD);
1700   } else {
1701     // Possible cases that we'll encounter in fast_lock
1702     // ------------------------------------------------
1703     // * Inflated
1704     //    -- unlocked
1705     //    -- Locked
1706     //       = by self
1707     //       = by other
1708     // * biased
1709     //    -- by Self
1710     //    -- by other
1711     // * neutral
1712     // * stack-locked
1713     //    -- by self
1714     //       = sp-proximity test hits
1715     //       = sp-proximity test generates false-negative
1716     //    -- by other
1717     //
1718 
1719     Label IsInflated, DONE_LABEL;
1720 
1721     // it's stack-locked, biased or neutral
1722     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1723     // order to reduce the number of conditional branches in the most common cases.
1724     // Beware -- there's a subtle invariant that fetch of the markword
1725     // at [FETCH], below, will never observe a biased encoding (*101b).
1726     // If this invariant is not held we risk exclusion (safety) failure.
1727     if (UseBiasedLocking && !UseOptoBiasInlining) {
1728       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1729     }
1730 
1731 #if INCLUDE_RTM_OPT
1732     if (UseRTMForStackLocks && use_rtm) {
1733       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1734                         stack_rtm_counters, method_data, profile_rtm,
1735                         DONE_LABEL, IsInflated);
1736     }
1737 #endif // INCLUDE_RTM_OPT
1738 
1739     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1740     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1741     jccb(Assembler::notZero, IsInflated);
1742 
1743     // Attempt stack-locking ...
1744     orptr (tmpReg, markOopDesc::unlocked_value);
1745     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1746     if (os::is_MP()) {
1747       lock();
1748     }
1749     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1750     if (counters != NULL) {
1751       cond_inc32(Assembler::equal,
1752                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1753     }
1754     jcc(Assembler::equal, DONE_LABEL);           // Success
1755 
1756     // Recursive locking.
1757     // The object is stack-locked: markword contains stack pointer to BasicLock.
1758     // Locked by current thread if difference with current SP is less than one page.
1759     subptr(tmpReg, rsp);
1760     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1761     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1762     movptr(Address(boxReg, 0), tmpReg);
1763     if (counters != NULL) {
1764       cond_inc32(Assembler::equal,
1765                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1766     }
1767     jmp(DONE_LABEL);
1768 
1769     bind(IsInflated);
1770     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1771 
1772 #if INCLUDE_RTM_OPT
1773     // Use the same RTM locking code in 32- and 64-bit VM.
1774     if (use_rtm) {
1775       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1776                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1777     } else {
1778 #endif // INCLUDE_RTM_OPT
1779 
1780 #ifndef _LP64
1781     // The object is inflated.
1782 
1783     // boxReg refers to the on-stack BasicLock in the current frame.
1784     // We'd like to write:
1785     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1786     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1787     // additional latency as we have another ST in the store buffer that must drain.
1788 
1789     if (EmitSync & 8192) {
1790        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1791        get_thread (scrReg);
1792        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1793        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1794        if (os::is_MP()) {
1795          lock();
1796        }
1797        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1798     } else
1799     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1800        // register juggle because we need tmpReg for cmpxchgptr below
1801        movptr(scrReg, boxReg);
1802        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1803 
1804        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1805        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1806           // prefetchw [eax + Offset(_owner)-2]
1807           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1808        }
1809 
1810        if ((EmitSync & 64) == 0) {
1811          // Optimistic form: consider XORL tmpReg,tmpReg
1812          movptr(tmpReg, NULL_WORD);
1813        } else {
1814          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1815          // Test-And-CAS instead of CAS
1816          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1817          testptr(tmpReg, tmpReg);                   // Locked ?
1818          jccb  (Assembler::notZero, DONE_LABEL);
1819        }
1820 
1821        // Appears unlocked - try to swing _owner from null to non-null.
1822        // Ideally, I'd manifest "Self" with get_thread and then attempt
1823        // to CAS the register containing Self into m->Owner.
1824        // But we don't have enough registers, so instead we can either try to CAS
1825        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1826        // we later store "Self" into m->Owner.  Transiently storing a stack address
1827        // (rsp or the address of the box) into  m->owner is harmless.
1828        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1829        if (os::is_MP()) {
1830          lock();
1831        }
1832        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1833        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1834        // If we weren't able to swing _owner from NULL to the BasicLock
1835        // then take the slow path.
1836        jccb  (Assembler::notZero, DONE_LABEL);
1837        // update _owner from BasicLock to thread
1838        get_thread (scrReg);                    // beware: clobbers ICCs
1839        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1840        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1841 
1842        // If the CAS fails we can either retry or pass control to the slow-path.
1843        // We use the latter tactic.
1844        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1845        // If the CAS was successful ...
1846        //   Self has acquired the lock
1847        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1848        // Intentional fall-through into DONE_LABEL ...
1849     } else {
1850        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1851        movptr(boxReg, tmpReg);
1852 
1853        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1854        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1855           // prefetchw [eax + Offset(_owner)-2]
1856           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1857        }
1858 
1859        if ((EmitSync & 64) == 0) {
1860          // Optimistic form
1861          xorptr  (tmpReg, tmpReg);
1862        } else {
1863          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1864          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1865          testptr(tmpReg, tmpReg);                   // Locked ?
1866          jccb  (Assembler::notZero, DONE_LABEL);
1867        }
1868 
1869        // Appears unlocked - try to swing _owner from null to non-null.
1870        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1871        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1872        get_thread (scrReg);
1873        if (os::is_MP()) {
1874          lock();
1875        }
1876        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1877 
1878        // If the CAS fails we can either retry or pass control to the slow-path.
1879        // We use the latter tactic.
1880        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1881        // If the CAS was successful ...
1882        //   Self has acquired the lock
1883        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1884        // Intentional fall-through into DONE_LABEL ...
1885     }
1886 #else // _LP64
1887     // It's inflated
1888     movq(scrReg, tmpReg);
1889     xorq(tmpReg, tmpReg);
1890 
1891     if (os::is_MP()) {
1892       lock();
1893     }
1894     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1895     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1896     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1897     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1898     // Intentional fall-through into DONE_LABEL ...
1899     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1900 #endif // _LP64
1901 #if INCLUDE_RTM_OPT
1902     } // use_rtm()
1903 #endif
1904     // DONE_LABEL is a hot target - we'd really like to place it at the
1905     // start of cache line by padding with NOPs.
1906     // See the AMD and Intel software optimization manuals for the
1907     // most efficient "long" NOP encodings.
1908     // Unfortunately none of our alignment mechanisms suffice.
1909     bind(DONE_LABEL);
1910 
1911     // At DONE_LABEL the icc ZFlag is set as follows ...
1912     // Fast_Unlock uses the same protocol.
1913     // ZFlag == 1 -> Success
1914     // ZFlag == 0 -> Failure - force control through the slow-path
1915   }
1916 }
1917 
1918 // obj: object to unlock
1919 // box: box address (displaced header location), killed.  Must be EAX.
1920 // tmp: killed, cannot be obj nor box.
1921 //
1922 // Some commentary on balanced locking:
1923 //
1924 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1925 // Methods that don't have provably balanced locking are forced to run in the
1926 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1927 // The interpreter provides two properties:
1928 // I1:  At return-time the interpreter automatically and quietly unlocks any
1929 //      objects acquired the current activation (frame).  Recall that the
1930 //      interpreter maintains an on-stack list of locks currently held by
1931 //      a frame.
1932 // I2:  If a method attempts to unlock an object that is not held by the
1933 //      the frame the interpreter throws IMSX.
1934 //
1935 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1936 // B() doesn't have provably balanced locking so it runs in the interpreter.
1937 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1938 // is still locked by A().
1939 //
1940 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1941 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1942 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1943 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1944 // Arguably given that the spec legislates the JNI case as undefined our implementation
1945 // could reasonably *avoid* checking owner in Fast_Unlock().
1946 // In the interest of performance we elide m->Owner==Self check in unlock.
1947 // A perfectly viable alternative is to elide the owner check except when
1948 // Xcheck:jni is enabled.
1949 
1950 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1951   assert(boxReg == rax, "");
1952   assert_different_registers(objReg, boxReg, tmpReg);
1953 
1954   if (EmitSync & 4) {
1955     // Disable - inhibit all inlining.  Force control through the slow-path
1956     cmpptr (rsp, 0);
1957   } else {
1958     Label DONE_LABEL, Stacked, CheckSucc;
1959 
1960     // Critically, the biased locking test must have precedence over
1961     // and appear before the (box->dhw == 0) recursive stack-lock test.
1962     if (UseBiasedLocking && !UseOptoBiasInlining) {
1963        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1964     }
1965 
1966 #if INCLUDE_RTM_OPT
1967     if (UseRTMForStackLocks && use_rtm) {
1968       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1969       Label L_regular_unlock;
1970       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1971       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1972       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1973       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1974       xend();                                       // otherwise end...
1975       jmp(DONE_LABEL);                              // ... and we're done
1976       bind(L_regular_unlock);
1977     }
1978 #endif
1979 
1980     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1981     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1982     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
1983     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1984     jccb  (Assembler::zero, Stacked);
1985 
1986     // It's inflated.
1987 #if INCLUDE_RTM_OPT
1988     if (use_rtm) {
1989       Label L_regular_inflated_unlock;
1990       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1991       movptr(boxReg, Address(tmpReg, owner_offset));
1992       testptr(boxReg, boxReg);
1993       jccb(Assembler::notZero, L_regular_inflated_unlock);
1994       xend();
1995       jmpb(DONE_LABEL);
1996       bind(L_regular_inflated_unlock);
1997     }
1998 #endif
1999 
2000     // Despite our balanced locking property we still check that m->_owner == Self
2001     // as java routines or native JNI code called by this thread might
2002     // have released the lock.
2003     // Refer to the comments in synchronizer.cpp for how we might encode extra
2004     // state in _succ so we can avoid fetching EntryList|cxq.
2005     //
2006     // I'd like to add more cases in fast_lock() and fast_unlock() --
2007     // such as recursive enter and exit -- but we have to be wary of
2008     // I$ bloat, T$ effects and BP$ effects.
2009     //
2010     // If there's no contention try a 1-0 exit.  That is, exit without
2011     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2012     // we detect and recover from the race that the 1-0 exit admits.
2013     //
2014     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2015     // before it STs null into _owner, releasing the lock.  Updates
2016     // to data protected by the critical section must be visible before
2017     // we drop the lock (and thus before any other thread could acquire
2018     // the lock and observe the fields protected by the lock).
2019     // IA32's memory-model is SPO, so STs are ordered with respect to
2020     // each other and there's no need for an explicit barrier (fence).
2021     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2022 #ifndef _LP64
2023     get_thread (boxReg);
2024     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2025       // prefetchw [ebx + Offset(_owner)-2]
2026       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2027     }
2028 
2029     // Note that we could employ various encoding schemes to reduce
2030     // the number of loads below (currently 4) to just 2 or 3.
2031     // Refer to the comments in synchronizer.cpp.
2032     // In practice the chain of fetches doesn't seem to impact performance, however.
2033     xorptr(boxReg, boxReg);
2034     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2035        // Attempt to reduce branch density - AMD's branch predictor.
2036        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2037        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2038        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2039        jccb  (Assembler::notZero, DONE_LABEL);
2040        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2041        jmpb  (DONE_LABEL);
2042     } else {
2043        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2044        jccb  (Assembler::notZero, DONE_LABEL);
2045        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2046        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2047        jccb  (Assembler::notZero, CheckSucc);
2048        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2049        jmpb  (DONE_LABEL);
2050     }
2051 
2052     // The Following code fragment (EmitSync & 65536) improves the performance of
2053     // contended applications and contended synchronization microbenchmarks.
2054     // Unfortunately the emission of the code - even though not executed - causes regressions
2055     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2056     // with an equal number of never-executed NOPs results in the same regression.
2057     // We leave it off by default.
2058 
2059     if ((EmitSync & 65536) != 0) {
2060        Label LSuccess, LGoSlowPath ;
2061 
2062        bind  (CheckSucc);
2063 
2064        // Optional pre-test ... it's safe to elide this
2065        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2066        jccb(Assembler::zero, LGoSlowPath);
2067 
2068        // We have a classic Dekker-style idiom:
2069        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2070        // There are a number of ways to implement the barrier:
2071        // (1) lock:andl &m->_owner, 0
2072        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2073        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2074        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2075        // (2) If supported, an explicit MFENCE is appealing.
2076        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2077        //     particularly if the write-buffer is full as might be the case if
2078        //     if stores closely precede the fence or fence-equivalent instruction.
2079        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2080        //     as the situation has changed with Nehalem and Shanghai.
2081        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2082        //     The $lines underlying the top-of-stack should be in M-state.
2083        //     The locked add instruction is serializing, of course.
2084        // (4) Use xchg, which is serializing
2085        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2086        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2087        //     The integer condition codes will tell us if succ was 0.
2088        //     Since _succ and _owner should reside in the same $line and
2089        //     we just stored into _owner, it's likely that the $line
2090        //     remains in M-state for the lock:orl.
2091        //
2092        // We currently use (3), although it's likely that switching to (2)
2093        // is correct for the future.
2094 
2095        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2096        if (os::is_MP()) {
2097          lock(); addptr(Address(rsp, 0), 0);
2098        }
2099        // Ratify _succ remains non-null
2100        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2101        jccb  (Assembler::notZero, LSuccess);
2102 
2103        xorptr(boxReg, boxReg);                  // box is really EAX
2104        if (os::is_MP()) { lock(); }
2105        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2106        // There's no successor so we tried to regrab the lock with the
2107        // placeholder value. If that didn't work, then another thread
2108        // grabbed the lock so we're done (and exit was a success).
2109        jccb  (Assembler::notEqual, LSuccess);
2110        // Since we're low on registers we installed rsp as a placeholding in _owner.
2111        // Now install Self over rsp.  This is safe as we're transitioning from
2112        // non-null to non=null
2113        get_thread (boxReg);
2114        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2115        // Intentional fall-through into LGoSlowPath ...
2116 
2117        bind  (LGoSlowPath);
2118        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2119        jmpb  (DONE_LABEL);
2120 
2121        bind  (LSuccess);
2122        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2123        jmpb  (DONE_LABEL);
2124     }
2125 
2126     bind (Stacked);
2127     // It's not inflated and it's not recursively stack-locked and it's not biased.
2128     // It must be stack-locked.
2129     // Try to reset the header to displaced header.
2130     // The "box" value on the stack is stable, so we can reload
2131     // and be assured we observe the same value as above.
2132     movptr(tmpReg, Address(boxReg, 0));
2133     if (os::is_MP()) {
2134       lock();
2135     }
2136     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2137     // Intention fall-thru into DONE_LABEL
2138 
2139     // DONE_LABEL is a hot target - we'd really like to place it at the
2140     // start of cache line by padding with NOPs.
2141     // See the AMD and Intel software optimization manuals for the
2142     // most efficient "long" NOP encodings.
2143     // Unfortunately none of our alignment mechanisms suffice.
2144     if ((EmitSync & 65536) == 0) {
2145        bind (CheckSucc);
2146     }
2147 #else // _LP64
2148     // It's inflated
2149     if (EmitSync & 1024) {
2150       // Emit code to check that _owner == Self
2151       // We could fold the _owner test into subsequent code more efficiently
2152       // than using a stand-alone check, but since _owner checking is off by
2153       // default we don't bother. We also might consider predicating the
2154       // _owner==Self check on Xcheck:jni or running on a debug build.
2155       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2156       xorptr(boxReg, r15_thread);
2157     } else {
2158       xorptr(boxReg, boxReg);
2159     }
2160     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2161     jccb  (Assembler::notZero, DONE_LABEL);
2162     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2163     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2164     jccb  (Assembler::notZero, CheckSucc);
2165     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2166     jmpb  (DONE_LABEL);
2167 
2168     if ((EmitSync & 65536) == 0) {
2169       // Try to avoid passing control into the slow_path ...
2170       Label LSuccess, LGoSlowPath ;
2171       bind  (CheckSucc);
2172 
2173       // The following optional optimization can be elided if necessary
2174       // Effectively: if (succ == null) goto SlowPath
2175       // The code reduces the window for a race, however,
2176       // and thus benefits performance.
2177       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2178       jccb  (Assembler::zero, LGoSlowPath);
2179 
2180       if ((EmitSync & 16) && os::is_MP()) {
2181         orptr(boxReg, boxReg);
2182         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2183       } else {
2184         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2185         if (os::is_MP()) {
2186           // Memory barrier/fence
2187           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2188           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2189           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2190           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2191           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2192           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2193           lock(); addl(Address(rsp, 0), 0);
2194         }
2195       }
2196       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2197       jccb  (Assembler::notZero, LSuccess);
2198 
2199       // Rare inopportune interleaving - race.
2200       // The successor vanished in the small window above.
2201       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2202       // We need to ensure progress and succession.
2203       // Try to reacquire the lock.
2204       // If that fails then the new owner is responsible for succession and this
2205       // thread needs to take no further action and can exit via the fast path (success).
2206       // If the re-acquire succeeds then pass control into the slow path.
2207       // As implemented, this latter mode is horrible because we generated more
2208       // coherence traffic on the lock *and* artifically extended the critical section
2209       // length while by virtue of passing control into the slow path.
2210 
2211       // box is really RAX -- the following CMPXCHG depends on that binding
2212       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2213       movptr(boxReg, (int32_t)NULL_WORD);
2214       if (os::is_MP()) { lock(); }
2215       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2216       // There's no successor so we tried to regrab the lock.
2217       // If that didn't work, then another thread grabbed the
2218       // lock so we're done (and exit was a success).
2219       jccb  (Assembler::notEqual, LSuccess);
2220       // Intentional fall-through into slow-path
2221 
2222       bind  (LGoSlowPath);
2223       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2224       jmpb  (DONE_LABEL);
2225 
2226       bind  (LSuccess);
2227       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2228       jmpb  (DONE_LABEL);
2229     }
2230 
2231     bind  (Stacked);
2232     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2233     if (os::is_MP()) { lock(); }
2234     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2235 
2236     if (EmitSync & 65536) {
2237        bind (CheckSucc);
2238     }
2239 #endif
2240     bind(DONE_LABEL);
2241   }
2242 }
2243 #endif // COMPILER2
2244 
2245 void MacroAssembler::c2bool(Register x) {
2246   // implements x == 0 ? 0 : 1
2247   // note: must only look at least-significant byte of x
2248   //       since C-style booleans are stored in one byte
2249   //       only! (was bug)
2250   andl(x, 0xFF);
2251   setb(Assembler::notZero, x);
2252 }
2253 
2254 // Wouldn't need if AddressLiteral version had new name
2255 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2256   Assembler::call(L, rtype);
2257 }
2258 
2259 void MacroAssembler::call(Register entry) {
2260   Assembler::call(entry);
2261 }
2262 
2263 void MacroAssembler::call(AddressLiteral entry) {
2264   if (reachable(entry)) {
2265     Assembler::call_literal(entry.target(), entry.rspec());
2266   } else {
2267     lea(rscratch1, entry);
2268     Assembler::call(rscratch1);
2269   }
2270 }
2271 
2272 void MacroAssembler::ic_call(address entry) {
2273   RelocationHolder rh = virtual_call_Relocation::spec(pc());
2274   movptr(rax, (intptr_t)Universe::non_oop_word());
2275   call(AddressLiteral(entry, rh));
2276 }
2277 
2278 // Implementation of call_VM versions
2279 
2280 void MacroAssembler::call_VM(Register oop_result,
2281                              address entry_point,
2282                              bool check_exceptions) {
2283   Label C, E;
2284   call(C, relocInfo::none);
2285   jmp(E);
2286 
2287   bind(C);
2288   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2289   ret(0);
2290 
2291   bind(E);
2292 }
2293 
2294 void MacroAssembler::call_VM(Register oop_result,
2295                              address entry_point,
2296                              Register arg_1,
2297                              bool check_exceptions) {
2298   Label C, E;
2299   call(C, relocInfo::none);
2300   jmp(E);
2301 
2302   bind(C);
2303   pass_arg1(this, arg_1);
2304   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2305   ret(0);
2306 
2307   bind(E);
2308 }
2309 
2310 void MacroAssembler::call_VM(Register oop_result,
2311                              address entry_point,
2312                              Register arg_1,
2313                              Register arg_2,
2314                              bool check_exceptions) {
2315   Label C, E;
2316   call(C, relocInfo::none);
2317   jmp(E);
2318 
2319   bind(C);
2320 
2321   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2322 
2323   pass_arg2(this, arg_2);
2324   pass_arg1(this, arg_1);
2325   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2326   ret(0);
2327 
2328   bind(E);
2329 }
2330 
2331 void MacroAssembler::call_VM(Register oop_result,
2332                              address entry_point,
2333                              Register arg_1,
2334                              Register arg_2,
2335                              Register arg_3,
2336                              bool check_exceptions) {
2337   Label C, E;
2338   call(C, relocInfo::none);
2339   jmp(E);
2340 
2341   bind(C);
2342 
2343   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2344   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2345   pass_arg3(this, arg_3);
2346 
2347   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2348   pass_arg2(this, arg_2);
2349 
2350   pass_arg1(this, arg_1);
2351   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2352   ret(0);
2353 
2354   bind(E);
2355 }
2356 
2357 void MacroAssembler::call_VM(Register oop_result,
2358                              Register last_java_sp,
2359                              address entry_point,
2360                              int number_of_arguments,
2361                              bool check_exceptions) {
2362   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2363   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, 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                              bool check_exceptions) {
2371   pass_arg1(this, arg_1);
2372   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2373 }
2374 
2375 void MacroAssembler::call_VM(Register oop_result,
2376                              Register last_java_sp,
2377                              address entry_point,
2378                              Register arg_1,
2379                              Register arg_2,
2380                              bool check_exceptions) {
2381 
2382   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2383   pass_arg2(this, arg_2);
2384   pass_arg1(this, arg_1);
2385   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2386 }
2387 
2388 void MacroAssembler::call_VM(Register oop_result,
2389                              Register last_java_sp,
2390                              address entry_point,
2391                              Register arg_1,
2392                              Register arg_2,
2393                              Register arg_3,
2394                              bool check_exceptions) {
2395   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2396   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2397   pass_arg3(this, arg_3);
2398   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2399   pass_arg2(this, arg_2);
2400   pass_arg1(this, arg_1);
2401   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2402 }
2403 
2404 void MacroAssembler::super_call_VM(Register oop_result,
2405                                    Register last_java_sp,
2406                                    address entry_point,
2407                                    int number_of_arguments,
2408                                    bool check_exceptions) {
2409   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2410   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, 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                                    bool check_exceptions) {
2418   pass_arg1(this, arg_1);
2419   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2420 }
2421 
2422 void MacroAssembler::super_call_VM(Register oop_result,
2423                                    Register last_java_sp,
2424                                    address entry_point,
2425                                    Register arg_1,
2426                                    Register arg_2,
2427                                    bool check_exceptions) {
2428 
2429   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2430   pass_arg2(this, arg_2);
2431   pass_arg1(this, arg_1);
2432   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2433 }
2434 
2435 void MacroAssembler::super_call_VM(Register oop_result,
2436                                    Register last_java_sp,
2437                                    address entry_point,
2438                                    Register arg_1,
2439                                    Register arg_2,
2440                                    Register arg_3,
2441                                    bool check_exceptions) {
2442   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2443   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2444   pass_arg3(this, arg_3);
2445   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2446   pass_arg2(this, arg_2);
2447   pass_arg1(this, arg_1);
2448   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2449 }
2450 
2451 void MacroAssembler::call_VM_base(Register oop_result,
2452                                   Register java_thread,
2453                                   Register last_java_sp,
2454                                   address  entry_point,
2455                                   int      number_of_arguments,
2456                                   bool     check_exceptions) {
2457   // determine java_thread register
2458   if (!java_thread->is_valid()) {
2459 #ifdef _LP64
2460     java_thread = r15_thread;
2461 #else
2462     java_thread = rdi;
2463     get_thread(java_thread);
2464 #endif // LP64
2465   }
2466   // determine last_java_sp register
2467   if (!last_java_sp->is_valid()) {
2468     last_java_sp = rsp;
2469   }
2470   // debugging support
2471   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2472   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2473 #ifdef ASSERT
2474   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2475   // r12 is the heapbase.
2476   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2477 #endif // ASSERT
2478 
2479   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2480   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2481 
2482   // push java thread (becomes first argument of C function)
2483 
2484   NOT_LP64(push(java_thread); number_of_arguments++);
2485   LP64_ONLY(mov(c_rarg0, r15_thread));
2486 
2487   // set last Java frame before call
2488   assert(last_java_sp != rbp, "can't use ebp/rbp");
2489 
2490   // Only interpreter should have to set fp
2491   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2492 
2493   // do the call, remove parameters
2494   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2495 
2496   // restore the thread (cannot use the pushed argument since arguments
2497   // may be overwritten by C code generated by an optimizing compiler);
2498   // however can use the register value directly if it is callee saved.
2499   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2500     // rdi & rsi (also r15) are callee saved -> nothing to do
2501 #ifdef ASSERT
2502     guarantee(java_thread != rax, "change this code");
2503     push(rax);
2504     { Label L;
2505       get_thread(rax);
2506       cmpptr(java_thread, rax);
2507       jcc(Assembler::equal, L);
2508       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2509       bind(L);
2510     }
2511     pop(rax);
2512 #endif
2513   } else {
2514     get_thread(java_thread);
2515   }
2516   // reset last Java frame
2517   // Only interpreter should have to clear fp
2518   reset_last_Java_frame(java_thread, true, false);
2519 
2520 #ifndef CC_INTERP
2521    // C++ interp handles this in the interpreter
2522   check_and_handle_popframe(java_thread);
2523   check_and_handle_earlyret(java_thread);
2524 #endif /* CC_INTERP */
2525 
2526   if (check_exceptions) {
2527     // check for pending exceptions (java_thread is set upon return)
2528     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2529 #ifndef _LP64
2530     jump_cc(Assembler::notEqual,
2531             RuntimeAddress(StubRoutines::forward_exception_entry()));
2532 #else
2533     // This used to conditionally jump to forward_exception however it is
2534     // possible if we relocate that the branch will not reach. So we must jump
2535     // around so we can always reach
2536 
2537     Label ok;
2538     jcc(Assembler::equal, ok);
2539     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2540     bind(ok);
2541 #endif // LP64
2542   }
2543 
2544   // get oop result if there is one and reset the value in the thread
2545   if (oop_result->is_valid()) {
2546     get_vm_result(oop_result, java_thread);
2547   }
2548 }
2549 
2550 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2551 
2552   // Calculate the value for last_Java_sp
2553   // somewhat subtle. call_VM does an intermediate call
2554   // which places a return address on the stack just under the
2555   // stack pointer as the user finsihed with it. This allows
2556   // use to retrieve last_Java_pc from last_Java_sp[-1].
2557   // On 32bit we then have to push additional args on the stack to accomplish
2558   // the actual requested call. On 64bit call_VM only can use register args
2559   // so the only extra space is the return address that call_VM created.
2560   // This hopefully explains the calculations here.
2561 
2562 #ifdef _LP64
2563   // We've pushed one address, correct last_Java_sp
2564   lea(rax, Address(rsp, wordSize));
2565 #else
2566   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2567 #endif // LP64
2568 
2569   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2570 
2571 }
2572 
2573 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2574   call_VM_leaf_base(entry_point, number_of_arguments);
2575 }
2576 
2577 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2578   pass_arg0(this, arg_0);
2579   call_VM_leaf(entry_point, 1);
2580 }
2581 
2582 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2583 
2584   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2585   pass_arg1(this, arg_1);
2586   pass_arg0(this, arg_0);
2587   call_VM_leaf(entry_point, 2);
2588 }
2589 
2590 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2591   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2592   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2593   pass_arg2(this, arg_2);
2594   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2595   pass_arg1(this, arg_1);
2596   pass_arg0(this, arg_0);
2597   call_VM_leaf(entry_point, 3);
2598 }
2599 
2600 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2601   pass_arg0(this, arg_0);
2602   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2603 }
2604 
2605 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2606 
2607   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2608   pass_arg1(this, arg_1);
2609   pass_arg0(this, arg_0);
2610   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2611 }
2612 
2613 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2614   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2615   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2616   pass_arg2(this, arg_2);
2617   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2618   pass_arg1(this, arg_1);
2619   pass_arg0(this, arg_0);
2620   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2621 }
2622 
2623 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2624   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2625   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2626   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2627   pass_arg3(this, arg_3);
2628   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2629   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2630   pass_arg2(this, arg_2);
2631   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2632   pass_arg1(this, arg_1);
2633   pass_arg0(this, arg_0);
2634   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2635 }
2636 
2637 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2638   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2639   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2640   verify_oop(oop_result, "broken oop in call_VM_base");
2641 }
2642 
2643 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2644   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2645   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2646 }
2647 
2648 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2649 }
2650 
2651 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2652 }
2653 
2654 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2655   if (reachable(src1)) {
2656     cmpl(as_Address(src1), imm);
2657   } else {
2658     lea(rscratch1, src1);
2659     cmpl(Address(rscratch1, 0), imm);
2660   }
2661 }
2662 
2663 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2664   assert(!src2.is_lval(), "use cmpptr");
2665   if (reachable(src2)) {
2666     cmpl(src1, as_Address(src2));
2667   } else {
2668     lea(rscratch1, src2);
2669     cmpl(src1, Address(rscratch1, 0));
2670   }
2671 }
2672 
2673 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2674   Assembler::cmpl(src1, imm);
2675 }
2676 
2677 void MacroAssembler::cmp32(Register src1, Address src2) {
2678   Assembler::cmpl(src1, src2);
2679 }
2680 
2681 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2682   ucomisd(opr1, opr2);
2683 
2684   Label L;
2685   if (unordered_is_less) {
2686     movl(dst, -1);
2687     jcc(Assembler::parity, L);
2688     jcc(Assembler::below , L);
2689     movl(dst, 0);
2690     jcc(Assembler::equal , L);
2691     increment(dst);
2692   } else { // unordered is greater
2693     movl(dst, 1);
2694     jcc(Assembler::parity, L);
2695     jcc(Assembler::above , L);
2696     movl(dst, 0);
2697     jcc(Assembler::equal , L);
2698     decrementl(dst);
2699   }
2700   bind(L);
2701 }
2702 
2703 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2704   ucomiss(opr1, opr2);
2705 
2706   Label L;
2707   if (unordered_is_less) {
2708     movl(dst, -1);
2709     jcc(Assembler::parity, L);
2710     jcc(Assembler::below , L);
2711     movl(dst, 0);
2712     jcc(Assembler::equal , L);
2713     increment(dst);
2714   } else { // unordered is greater
2715     movl(dst, 1);
2716     jcc(Assembler::parity, L);
2717     jcc(Assembler::above , L);
2718     movl(dst, 0);
2719     jcc(Assembler::equal , L);
2720     decrementl(dst);
2721   }
2722   bind(L);
2723 }
2724 
2725 
2726 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2727   if (reachable(src1)) {
2728     cmpb(as_Address(src1), imm);
2729   } else {
2730     lea(rscratch1, src1);
2731     cmpb(Address(rscratch1, 0), imm);
2732   }
2733 }
2734 
2735 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2736 #ifdef _LP64
2737   if (src2.is_lval()) {
2738     movptr(rscratch1, src2);
2739     Assembler::cmpq(src1, rscratch1);
2740   } else if (reachable(src2)) {
2741     cmpq(src1, as_Address(src2));
2742   } else {
2743     lea(rscratch1, src2);
2744     Assembler::cmpq(src1, Address(rscratch1, 0));
2745   }
2746 #else
2747   if (src2.is_lval()) {
2748     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2749   } else {
2750     cmpl(src1, as_Address(src2));
2751   }
2752 #endif // _LP64
2753 }
2754 
2755 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2756   assert(src2.is_lval(), "not a mem-mem compare");
2757 #ifdef _LP64
2758   // moves src2's literal address
2759   movptr(rscratch1, src2);
2760   Assembler::cmpq(src1, rscratch1);
2761 #else
2762   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2763 #endif // _LP64
2764 }
2765 
2766 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2767   if (reachable(adr)) {
2768     if (os::is_MP())
2769       lock();
2770     cmpxchgptr(reg, as_Address(adr));
2771   } else {
2772     lea(rscratch1, adr);
2773     if (os::is_MP())
2774       lock();
2775     cmpxchgptr(reg, Address(rscratch1, 0));
2776   }
2777 }
2778 
2779 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2780   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2781 }
2782 
2783 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2784   if (reachable(src)) {
2785     Assembler::comisd(dst, as_Address(src));
2786   } else {
2787     lea(rscratch1, src);
2788     Assembler::comisd(dst, Address(rscratch1, 0));
2789   }
2790 }
2791 
2792 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2793   if (reachable(src)) {
2794     Assembler::comiss(dst, as_Address(src));
2795   } else {
2796     lea(rscratch1, src);
2797     Assembler::comiss(dst, Address(rscratch1, 0));
2798   }
2799 }
2800 
2801 
2802 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2803   Condition negated_cond = negate_condition(cond);
2804   Label L;
2805   jcc(negated_cond, L);
2806   pushf(); // Preserve flags
2807   atomic_incl(counter_addr);
2808   popf();
2809   bind(L);
2810 }
2811 
2812 int MacroAssembler::corrected_idivl(Register reg) {
2813   // Full implementation of Java idiv and irem; checks for
2814   // special case as described in JVM spec., p.243 & p.271.
2815   // The function returns the (pc) offset of the idivl
2816   // instruction - may be needed for implicit exceptions.
2817   //
2818   //         normal case                           special case
2819   //
2820   // input : rax,: dividend                         min_int
2821   //         reg: divisor   (may not be rax,/rdx)   -1
2822   //
2823   // output: rax,: quotient  (= rax, idiv reg)       min_int
2824   //         rdx: remainder (= rax, irem reg)       0
2825   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2826   const int min_int = 0x80000000;
2827   Label normal_case, special_case;
2828 
2829   // check for special case
2830   cmpl(rax, min_int);
2831   jcc(Assembler::notEqual, normal_case);
2832   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2833   cmpl(reg, -1);
2834   jcc(Assembler::equal, special_case);
2835 
2836   // handle normal case
2837   bind(normal_case);
2838   cdql();
2839   int idivl_offset = offset();
2840   idivl(reg);
2841 
2842   // normal and special case exit
2843   bind(special_case);
2844 
2845   return idivl_offset;
2846 }
2847 
2848 
2849 
2850 void MacroAssembler::decrementl(Register reg, int value) {
2851   if (value == min_jint) {subl(reg, value) ; return; }
2852   if (value <  0) { incrementl(reg, -value); return; }
2853   if (value == 0) {                        ; return; }
2854   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2855   /* else */      { subl(reg, value)       ; return; }
2856 }
2857 
2858 void MacroAssembler::decrementl(Address dst, int value) {
2859   if (value == min_jint) {subl(dst, value) ; return; }
2860   if (value <  0) { incrementl(dst, -value); return; }
2861   if (value == 0) {                        ; return; }
2862   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2863   /* else */      { subl(dst, value)       ; return; }
2864 }
2865 
2866 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2867   assert (shift_value > 0, "illegal shift value");
2868   Label _is_positive;
2869   testl (reg, reg);
2870   jcc (Assembler::positive, _is_positive);
2871   int offset = (1 << shift_value) - 1 ;
2872 
2873   if (offset == 1) {
2874     incrementl(reg);
2875   } else {
2876     addl(reg, offset);
2877   }
2878 
2879   bind (_is_positive);
2880   sarl(reg, shift_value);
2881 }
2882 
2883 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2884   if (reachable(src)) {
2885     Assembler::divsd(dst, as_Address(src));
2886   } else {
2887     lea(rscratch1, src);
2888     Assembler::divsd(dst, Address(rscratch1, 0));
2889   }
2890 }
2891 
2892 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2893   if (reachable(src)) {
2894     Assembler::divss(dst, as_Address(src));
2895   } else {
2896     lea(rscratch1, src);
2897     Assembler::divss(dst, Address(rscratch1, 0));
2898   }
2899 }
2900 
2901 // !defined(COMPILER2) is because of stupid core builds
2902 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2903 void MacroAssembler::empty_FPU_stack() {
2904   if (VM_Version::supports_mmx()) {
2905     emms();
2906   } else {
2907     for (int i = 8; i-- > 0; ) ffree(i);
2908   }
2909 }
2910 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2911 
2912 
2913 // Defines obj, preserves var_size_in_bytes
2914 void MacroAssembler::eden_allocate(Register obj,
2915                                    Register var_size_in_bytes,
2916                                    int con_size_in_bytes,
2917                                    Register t1,
2918                                    Label& slow_case) {
2919   assert(obj == rax, "obj must be in rax, for cmpxchg");
2920   assert_different_registers(obj, var_size_in_bytes, t1);
2921   if (!Universe::heap()->supports_inline_contig_alloc()) {
2922     jmp(slow_case);
2923   } else {
2924     Register end = t1;
2925     Label retry;
2926     bind(retry);
2927     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2928     movptr(obj, heap_top);
2929     if (var_size_in_bytes == noreg) {
2930       lea(end, Address(obj, con_size_in_bytes));
2931     } else {
2932       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2933     }
2934     // if end < obj then we wrapped around => object too long => slow case
2935     cmpptr(end, obj);
2936     jcc(Assembler::below, slow_case);
2937     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2938     jcc(Assembler::above, slow_case);
2939     // Compare obj with the top addr, and if still equal, store the new top addr in
2940     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2941     // it otherwise. Use lock prefix for atomicity on MPs.
2942     locked_cmpxchgptr(end, heap_top);
2943     jcc(Assembler::notEqual, retry);
2944   }
2945 }
2946 
2947 void MacroAssembler::enter() {
2948   push(rbp);
2949   mov(rbp, rsp);
2950 }
2951 
2952 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2953 void MacroAssembler::fat_nop() {
2954   if (UseAddressNop) {
2955     addr_nop_5();
2956   } else {
2957     emit_int8(0x26); // es:
2958     emit_int8(0x2e); // cs:
2959     emit_int8(0x64); // fs:
2960     emit_int8(0x65); // gs:
2961     emit_int8((unsigned char)0x90);
2962   }
2963 }
2964 
2965 void MacroAssembler::fcmp(Register tmp) {
2966   fcmp(tmp, 1, true, true);
2967 }
2968 
2969 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2970   assert(!pop_right || pop_left, "usage error");
2971   if (VM_Version::supports_cmov()) {
2972     assert(tmp == noreg, "unneeded temp");
2973     if (pop_left) {
2974       fucomip(index);
2975     } else {
2976       fucomi(index);
2977     }
2978     if (pop_right) {
2979       fpop();
2980     }
2981   } else {
2982     assert(tmp != noreg, "need temp");
2983     if (pop_left) {
2984       if (pop_right) {
2985         fcompp();
2986       } else {
2987         fcomp(index);
2988       }
2989     } else {
2990       fcom(index);
2991     }
2992     // convert FPU condition into eflags condition via rax,
2993     save_rax(tmp);
2994     fwait(); fnstsw_ax();
2995     sahf();
2996     restore_rax(tmp);
2997   }
2998   // condition codes set as follows:
2999   //
3000   // CF (corresponds to C0) if x < y
3001   // PF (corresponds to C2) if unordered
3002   // ZF (corresponds to C3) if x = y
3003 }
3004 
3005 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3006   fcmp2int(dst, unordered_is_less, 1, true, true);
3007 }
3008 
3009 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3010   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3011   Label L;
3012   if (unordered_is_less) {
3013     movl(dst, -1);
3014     jcc(Assembler::parity, L);
3015     jcc(Assembler::below , L);
3016     movl(dst, 0);
3017     jcc(Assembler::equal , L);
3018     increment(dst);
3019   } else { // unordered is greater
3020     movl(dst, 1);
3021     jcc(Assembler::parity, L);
3022     jcc(Assembler::above , L);
3023     movl(dst, 0);
3024     jcc(Assembler::equal , L);
3025     decrementl(dst);
3026   }
3027   bind(L);
3028 }
3029 
3030 void MacroAssembler::fld_d(AddressLiteral src) {
3031   fld_d(as_Address(src));
3032 }
3033 
3034 void MacroAssembler::fld_s(AddressLiteral src) {
3035   fld_s(as_Address(src));
3036 }
3037 
3038 void MacroAssembler::fld_x(AddressLiteral src) {
3039   Assembler::fld_x(as_Address(src));
3040 }
3041 
3042 void MacroAssembler::fldcw(AddressLiteral src) {
3043   Assembler::fldcw(as_Address(src));
3044 }
3045 
3046 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3047   if (reachable(src)) {
3048     Assembler::mulpd(dst, as_Address(src));
3049   } else {
3050     lea(rscratch1, src);
3051     Assembler::mulpd(dst, Address(rscratch1, 0));
3052   }
3053 }
3054 
3055 void MacroAssembler::pow_exp_core_encoding() {
3056   // kills rax, rcx, rdx
3057   subptr(rsp,sizeof(jdouble));
3058   // computes 2^X. Stack: X ...
3059   // f2xm1 computes 2^X-1 but only operates on -1<=X<=1. Get int(X) and
3060   // keep it on the thread's stack to compute 2^int(X) later
3061   // then compute 2^(X-int(X)) as (2^(X-int(X)-1+1)
3062   // final result is obtained with: 2^X = 2^int(X) * 2^(X-int(X))
3063   fld_s(0);                 // Stack: X X ...
3064   frndint();                // Stack: int(X) X ...
3065   fsuba(1);                 // Stack: int(X) X-int(X) ...
3066   fistp_s(Address(rsp,0));  // move int(X) as integer to thread's stack. Stack: X-int(X) ...
3067   f2xm1();                  // Stack: 2^(X-int(X))-1 ...
3068   fld1();                   // Stack: 1 2^(X-int(X))-1 ...
3069   faddp(1);                 // Stack: 2^(X-int(X))
3070   // computes 2^(int(X)): add exponent bias (1023) to int(X), then
3071   // shift int(X)+1023 to exponent position.
3072   // Exponent is limited to 11 bits if int(X)+1023 does not fit in 11
3073   // bits, set result to NaN. 0x000 and 0x7FF are reserved exponent
3074   // values so detect them and set result to NaN.
3075   movl(rax,Address(rsp,0));
3076   movl(rcx, -2048); // 11 bit mask and valid NaN binary encoding
3077   addl(rax, 1023);
3078   movl(rdx,rax);
3079   shll(rax,20);
3080   // Check that 0 < int(X)+1023 < 2047. Otherwise set rax to NaN.
3081   addl(rdx,1);
3082   // Check that 1 < int(X)+1023+1 < 2048
3083   // in 3 steps:
3084   // 1- (int(X)+1023+1)&-2048 == 0 => 0 <= int(X)+1023+1 < 2048
3085   // 2- (int(X)+1023+1)&-2048 != 0
3086   // 3- (int(X)+1023+1)&-2048 != 1
3087   // Do 2- first because addl just updated the flags.
3088   cmov32(Assembler::equal,rax,rcx);
3089   cmpl(rdx,1);
3090   cmov32(Assembler::equal,rax,rcx);
3091   testl(rdx,rcx);
3092   cmov32(Assembler::notEqual,rax,rcx);
3093   movl(Address(rsp,4),rax);
3094   movl(Address(rsp,0),0);
3095   fmul_d(Address(rsp,0));   // Stack: 2^X ...
3096   addptr(rsp,sizeof(jdouble));
3097 }
3098 
3099 void MacroAssembler::increase_precision() {
3100   subptr(rsp, BytesPerWord);
3101   fnstcw(Address(rsp, 0));
3102   movl(rax, Address(rsp, 0));
3103   orl(rax, 0x300);
3104   push(rax);
3105   fldcw(Address(rsp, 0));
3106   pop(rax);
3107 }
3108 
3109 void MacroAssembler::restore_precision() {
3110   fldcw(Address(rsp, 0));
3111   addptr(rsp, BytesPerWord);
3112 }
3113 
3114 void MacroAssembler::fast_pow() {
3115   // computes X^Y = 2^(Y * log2(X))
3116   // if fast computation is not possible, result is NaN. Requires
3117   // fallback from user of this macro.
3118   // increase precision for intermediate steps of the computation
3119   BLOCK_COMMENT("fast_pow {");
3120   increase_precision();
3121   fyl2x();                 // Stack: (Y*log2(X)) ...
3122   pow_exp_core_encoding(); // Stack: exp(X) ...
3123   restore_precision();
3124   BLOCK_COMMENT("} fast_pow");
3125 }
3126 
3127 void MacroAssembler::pow_or_exp(int num_fpu_regs_in_use) {
3128   // kills rax, rcx, rdx
3129   // pow and exp needs 2 extra registers on the fpu stack.
3130   Label slow_case, done;
3131   Register tmp = noreg;
3132   if (!VM_Version::supports_cmov()) {
3133     // fcmp needs a temporary so preserve rdx,
3134     tmp = rdx;
3135   }
3136   Register tmp2 = rax;
3137   Register tmp3 = rcx;
3138 
3139   // Stack: X Y
3140   Label x_negative, y_not_2;
3141 
3142   static double two = 2.0;
3143   ExternalAddress two_addr((address)&two);
3144 
3145   // constant maybe too far on 64 bit
3146   lea(tmp2, two_addr);
3147   fld_d(Address(tmp2, 0));    // Stack: 2 X Y
3148   fcmp(tmp, 2, true, false);  // Stack: X Y
3149   jcc(Assembler::parity, y_not_2);
3150   jcc(Assembler::notEqual, y_not_2);
3151 
3152   fxch(); fpop();             // Stack: X
3153   fmul(0);                    // Stack: X*X
3154 
3155   jmp(done);
3156 
3157   bind(y_not_2);
3158 
3159   fldz();                     // Stack: 0 X Y
3160   fcmp(tmp, 1, true, false);  // Stack: X Y
3161   jcc(Assembler::above, x_negative);
3162 
3163   // X >= 0
3164 
3165   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3166   fld_s(1);                   // Stack: X Y X Y
3167   fast_pow();                 // Stack: X^Y X Y
3168   fcmp(tmp, 0, false, false); // Stack: X^Y X Y
3169   // X^Y not equal to itself: X^Y is NaN go to slow case.
3170   jcc(Assembler::parity, slow_case);
3171   // get rid of duplicate arguments. Stack: X^Y
3172   if (num_fpu_regs_in_use > 0) {
3173     fxch(); fpop();
3174     fxch(); fpop();
3175   } else {
3176     ffree(2);
3177     ffree(1);
3178   }
3179   jmp(done);
3180 
3181   // X <= 0
3182   bind(x_negative);
3183 
3184   fld_s(1);                   // Stack: Y X Y
3185   frndint();                  // Stack: int(Y) X Y
3186   fcmp(tmp, 2, false, false); // Stack: int(Y) X Y
3187   jcc(Assembler::notEqual, slow_case);
3188 
3189   subptr(rsp, 8);
3190 
3191   // For X^Y, when X < 0, Y has to be an integer and the final
3192   // result depends on whether it's odd or even. We just checked
3193   // that int(Y) == Y.  We move int(Y) to gp registers as a 64 bit
3194   // integer to test its parity. If int(Y) is huge and doesn't fit
3195   // in the 64 bit integer range, the integer indefinite value will
3196   // end up in the gp registers. Huge numbers are all even, the
3197   // integer indefinite number is even so it's fine.
3198 
3199 #ifdef ASSERT
3200   // Let's check we don't end up with an integer indefinite number
3201   // when not expected. First test for huge numbers: check whether
3202   // int(Y)+1 == int(Y) which is true for very large numbers and
3203   // those are all even. A 64 bit integer is guaranteed to not
3204   // overflow for numbers where y+1 != y (when precision is set to
3205   // double precision).
3206   Label y_not_huge;
3207 
3208   fld1();                     // Stack: 1 int(Y) X Y
3209   fadd(1);                    // Stack: 1+int(Y) int(Y) X Y
3210 
3211 #ifdef _LP64
3212   // trip to memory to force the precision down from double extended
3213   // precision
3214   fstp_d(Address(rsp, 0));
3215   fld_d(Address(rsp, 0));
3216 #endif
3217 
3218   fcmp(tmp, 1, true, false);  // Stack: int(Y) X Y
3219 #endif
3220 
3221   // move int(Y) as 64 bit integer to thread's stack
3222   fistp_d(Address(rsp,0));    // Stack: X Y
3223 
3224 #ifdef ASSERT
3225   jcc(Assembler::notEqual, y_not_huge);
3226 
3227   // Y is huge so we know it's even. It may not fit in a 64 bit
3228   // integer and we don't want the debug code below to see the
3229   // integer indefinite value so overwrite int(Y) on the thread's
3230   // stack with 0.
3231   movl(Address(rsp, 0), 0);
3232   movl(Address(rsp, 4), 0);
3233 
3234   bind(y_not_huge);
3235 #endif
3236 
3237   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3238   fld_s(1);                   // Stack: X Y X Y
3239   fabs();                     // Stack: abs(X) Y X Y
3240   fast_pow();                 // Stack: abs(X)^Y X Y
3241   fcmp(tmp, 0, false, false); // Stack: abs(X)^Y X Y
3242   // abs(X)^Y not equal to itself: abs(X)^Y is NaN go to slow case.
3243 
3244   pop(tmp2);
3245   NOT_LP64(pop(tmp3));
3246   jcc(Assembler::parity, slow_case);
3247 
3248 #ifdef ASSERT
3249   // Check that int(Y) is not integer indefinite value (int
3250   // overflow). Shouldn't happen because for values that would
3251   // overflow, 1+int(Y)==Y which was tested earlier.
3252 #ifndef _LP64
3253   {
3254     Label integer;
3255     testl(tmp2, tmp2);
3256     jcc(Assembler::notZero, integer);
3257     cmpl(tmp3, 0x80000000);
3258     jcc(Assembler::notZero, integer);
3259     STOP("integer indefinite value shouldn't be seen here");
3260     bind(integer);
3261   }
3262 #else
3263   {
3264     Label integer;
3265     mov(tmp3, tmp2); // preserve tmp2 for parity check below
3266     shlq(tmp3, 1);
3267     jcc(Assembler::carryClear, integer);
3268     jcc(Assembler::notZero, integer);
3269     STOP("integer indefinite value shouldn't be seen here");
3270     bind(integer);
3271   }
3272 #endif
3273 #endif
3274 
3275   // get rid of duplicate arguments. Stack: X^Y
3276   if (num_fpu_regs_in_use > 0) {
3277     fxch(); fpop();
3278     fxch(); fpop();
3279   } else {
3280     ffree(2);
3281     ffree(1);
3282   }
3283 
3284   testl(tmp2, 1);
3285   jcc(Assembler::zero, done); // X <= 0, Y even: X^Y = abs(X)^Y
3286   // X <= 0, Y even: X^Y = -abs(X)^Y
3287 
3288   fchs();                     // Stack: -abs(X)^Y Y
3289   jmp(done);
3290 
3291   // slow case: runtime call
3292   bind(slow_case);
3293 
3294   fpop();                       // pop incorrect result or int(Y)
3295 
3296   fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dpow), 2, num_fpu_regs_in_use);
3297 
3298   // Come here with result in F-TOS
3299   bind(done);
3300 }
3301 
3302 void MacroAssembler::fpop() {
3303   ffree();
3304   fincstp();
3305 }
3306 
3307 void MacroAssembler::load_float(Address src) {
3308   if (UseSSE >= 1) {
3309     movflt(xmm0, src);
3310   } else {
3311     LP64_ONLY(ShouldNotReachHere());
3312     NOT_LP64(fld_s(src));
3313   }
3314 }
3315 
3316 void MacroAssembler::store_float(Address dst) {
3317   if (UseSSE >= 1) {
3318     movflt(dst, xmm0);
3319   } else {
3320     LP64_ONLY(ShouldNotReachHere());
3321     NOT_LP64(fstp_s(dst));
3322   }
3323 }
3324 
3325 void MacroAssembler::load_double(Address src) {
3326   if (UseSSE >= 2) {
3327     movdbl(xmm0, src);
3328   } else {
3329     LP64_ONLY(ShouldNotReachHere());
3330     NOT_LP64(fld_d(src));
3331   }
3332 }
3333 
3334 void MacroAssembler::store_double(Address dst) {
3335   if (UseSSE >= 2) {
3336     movdbl(dst, xmm0);
3337   } else {
3338     LP64_ONLY(ShouldNotReachHere());
3339     NOT_LP64(fstp_d(dst));
3340   }
3341 }
3342 
3343 void MacroAssembler::fremr(Register tmp) {
3344   save_rax(tmp);
3345   { Label L;
3346     bind(L);
3347     fprem();
3348     fwait(); fnstsw_ax();
3349 #ifdef _LP64
3350     testl(rax, 0x400);
3351     jcc(Assembler::notEqual, L);
3352 #else
3353     sahf();
3354     jcc(Assembler::parity, L);
3355 #endif // _LP64
3356   }
3357   restore_rax(tmp);
3358   // Result is in ST0.
3359   // Note: fxch & fpop to get rid of ST1
3360   // (otherwise FPU stack could overflow eventually)
3361   fxch(1);
3362   fpop();
3363 }
3364 
3365 
3366 void MacroAssembler::incrementl(AddressLiteral dst) {
3367   if (reachable(dst)) {
3368     incrementl(as_Address(dst));
3369   } else {
3370     lea(rscratch1, dst);
3371     incrementl(Address(rscratch1, 0));
3372   }
3373 }
3374 
3375 void MacroAssembler::incrementl(ArrayAddress dst) {
3376   incrementl(as_Address(dst));
3377 }
3378 
3379 void MacroAssembler::incrementl(Register reg, int value) {
3380   if (value == min_jint) {addl(reg, value) ; return; }
3381   if (value <  0) { decrementl(reg, -value); return; }
3382   if (value == 0) {                        ; return; }
3383   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3384   /* else */      { addl(reg, value)       ; return; }
3385 }
3386 
3387 void MacroAssembler::incrementl(Address dst, int value) {
3388   if (value == min_jint) {addl(dst, value) ; return; }
3389   if (value <  0) { decrementl(dst, -value); return; }
3390   if (value == 0) {                        ; return; }
3391   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3392   /* else */      { addl(dst, value)       ; return; }
3393 }
3394 
3395 void MacroAssembler::jump(AddressLiteral dst) {
3396   if (reachable(dst)) {
3397     jmp_literal(dst.target(), dst.rspec());
3398   } else {
3399     lea(rscratch1, dst);
3400     jmp(rscratch1);
3401   }
3402 }
3403 
3404 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3405   if (reachable(dst)) {
3406     InstructionMark im(this);
3407     relocate(dst.reloc());
3408     const int short_size = 2;
3409     const int long_size = 6;
3410     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3411     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3412       // 0111 tttn #8-bit disp
3413       emit_int8(0x70 | cc);
3414       emit_int8((offs - short_size) & 0xFF);
3415     } else {
3416       // 0000 1111 1000 tttn #32-bit disp
3417       emit_int8(0x0F);
3418       emit_int8((unsigned char)(0x80 | cc));
3419       emit_int32(offs - long_size);
3420     }
3421   } else {
3422 #ifdef ASSERT
3423     warning("reversing conditional branch");
3424 #endif /* ASSERT */
3425     Label skip;
3426     jccb(reverse[cc], skip);
3427     lea(rscratch1, dst);
3428     Assembler::jmp(rscratch1);
3429     bind(skip);
3430   }
3431 }
3432 
3433 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3434   if (reachable(src)) {
3435     Assembler::ldmxcsr(as_Address(src));
3436   } else {
3437     lea(rscratch1, src);
3438     Assembler::ldmxcsr(Address(rscratch1, 0));
3439   }
3440 }
3441 
3442 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3443   int off;
3444   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3445     off = offset();
3446     movsbl(dst, src); // movsxb
3447   } else {
3448     off = load_unsigned_byte(dst, src);
3449     shll(dst, 24);
3450     sarl(dst, 24);
3451   }
3452   return off;
3453 }
3454 
3455 // Note: load_signed_short used to be called load_signed_word.
3456 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3457 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3458 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3459 int MacroAssembler::load_signed_short(Register dst, Address src) {
3460   int off;
3461   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3462     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3463     // version but this is what 64bit has always done. This seems to imply
3464     // that users are only using 32bits worth.
3465     off = offset();
3466     movswl(dst, src); // movsxw
3467   } else {
3468     off = load_unsigned_short(dst, src);
3469     shll(dst, 16);
3470     sarl(dst, 16);
3471   }
3472   return off;
3473 }
3474 
3475 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3476   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3477   // and "3.9 Partial Register Penalties", p. 22).
3478   int off;
3479   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3480     off = offset();
3481     movzbl(dst, src); // movzxb
3482   } else {
3483     xorl(dst, dst);
3484     off = offset();
3485     movb(dst, src);
3486   }
3487   return off;
3488 }
3489 
3490 // Note: load_unsigned_short used to be called load_unsigned_word.
3491 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3492   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3493   // and "3.9 Partial Register Penalties", p. 22).
3494   int off;
3495   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3496     off = offset();
3497     movzwl(dst, src); // movzxw
3498   } else {
3499     xorl(dst, dst);
3500     off = offset();
3501     movw(dst, src);
3502   }
3503   return off;
3504 }
3505 
3506 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3507   switch (size_in_bytes) {
3508 #ifndef _LP64
3509   case  8:
3510     assert(dst2 != noreg, "second dest register required");
3511     movl(dst,  src);
3512     movl(dst2, src.plus_disp(BytesPerInt));
3513     break;
3514 #else
3515   case  8:  movq(dst, src); break;
3516 #endif
3517   case  4:  movl(dst, src); break;
3518   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3519   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3520   default:  ShouldNotReachHere();
3521   }
3522 }
3523 
3524 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3525   switch (size_in_bytes) {
3526 #ifndef _LP64
3527   case  8:
3528     assert(src2 != noreg, "second source register required");
3529     movl(dst,                        src);
3530     movl(dst.plus_disp(BytesPerInt), src2);
3531     break;
3532 #else
3533   case  8:  movq(dst, src); break;
3534 #endif
3535   case  4:  movl(dst, src); break;
3536   case  2:  movw(dst, src); break;
3537   case  1:  movb(dst, src); break;
3538   default:  ShouldNotReachHere();
3539   }
3540 }
3541 
3542 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3543   if (reachable(dst)) {
3544     movl(as_Address(dst), src);
3545   } else {
3546     lea(rscratch1, dst);
3547     movl(Address(rscratch1, 0), src);
3548   }
3549 }
3550 
3551 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3552   if (reachable(src)) {
3553     movl(dst, as_Address(src));
3554   } else {
3555     lea(rscratch1, src);
3556     movl(dst, Address(rscratch1, 0));
3557   }
3558 }
3559 
3560 // C++ bool manipulation
3561 
3562 void MacroAssembler::movbool(Register dst, Address src) {
3563   if(sizeof(bool) == 1)
3564     movb(dst, src);
3565   else if(sizeof(bool) == 2)
3566     movw(dst, src);
3567   else if(sizeof(bool) == 4)
3568     movl(dst, src);
3569   else
3570     // unsupported
3571     ShouldNotReachHere();
3572 }
3573 
3574 void MacroAssembler::movbool(Address dst, bool boolconst) {
3575   if(sizeof(bool) == 1)
3576     movb(dst, (int) boolconst);
3577   else if(sizeof(bool) == 2)
3578     movw(dst, (int) boolconst);
3579   else if(sizeof(bool) == 4)
3580     movl(dst, (int) boolconst);
3581   else
3582     // unsupported
3583     ShouldNotReachHere();
3584 }
3585 
3586 void MacroAssembler::movbool(Address dst, Register src) {
3587   if(sizeof(bool) == 1)
3588     movb(dst, src);
3589   else if(sizeof(bool) == 2)
3590     movw(dst, src);
3591   else if(sizeof(bool) == 4)
3592     movl(dst, src);
3593   else
3594     // unsupported
3595     ShouldNotReachHere();
3596 }
3597 
3598 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3599   movb(as_Address(dst), src);
3600 }
3601 
3602 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3603   if (reachable(src)) {
3604     movdl(dst, as_Address(src));
3605   } else {
3606     lea(rscratch1, src);
3607     movdl(dst, Address(rscratch1, 0));
3608   }
3609 }
3610 
3611 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3612   if (reachable(src)) {
3613     movq(dst, as_Address(src));
3614   } else {
3615     lea(rscratch1, src);
3616     movq(dst, Address(rscratch1, 0));
3617   }
3618 }
3619 
3620 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3621   if (reachable(src)) {
3622     if (UseXmmLoadAndClearUpper) {
3623       movsd (dst, as_Address(src));
3624     } else {
3625       movlpd(dst, as_Address(src));
3626     }
3627   } else {
3628     lea(rscratch1, src);
3629     if (UseXmmLoadAndClearUpper) {
3630       movsd (dst, Address(rscratch1, 0));
3631     } else {
3632       movlpd(dst, Address(rscratch1, 0));
3633     }
3634   }
3635 }
3636 
3637 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3638   if (reachable(src)) {
3639     movss(dst, as_Address(src));
3640   } else {
3641     lea(rscratch1, src);
3642     movss(dst, Address(rscratch1, 0));
3643   }
3644 }
3645 
3646 void MacroAssembler::movptr(Register dst, Register src) {
3647   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3648 }
3649 
3650 void MacroAssembler::movptr(Register dst, Address src) {
3651   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3652 }
3653 
3654 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3655 void MacroAssembler::movptr(Register dst, intptr_t src) {
3656   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3657 }
3658 
3659 void MacroAssembler::movptr(Address dst, Register src) {
3660   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3661 }
3662 
3663 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3664   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3665     Assembler::vextractf32x4h(dst, src, 0);
3666   } else {
3667     Assembler::movdqu(dst, src);
3668   }
3669 }
3670 
3671 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3672   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3673     Assembler::vinsertf32x4h(dst, src, 0);
3674   } else {
3675     Assembler::movdqu(dst, src);
3676   }
3677 }
3678 
3679 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3680   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3681     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3682   } else {
3683     Assembler::movdqu(dst, src);
3684   }
3685 }
3686 
3687 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3688   if (reachable(src)) {
3689     movdqu(dst, as_Address(src));
3690   } else {
3691     lea(rscratch1, src);
3692     movdqu(dst, Address(rscratch1, 0));
3693   }
3694 }
3695 
3696 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3697   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3698     Assembler::vextractf64x4h(dst, src, 0);
3699   } else {
3700     Assembler::vmovdqu(dst, src);
3701   }
3702 }
3703 
3704 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3705   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3706     Assembler::vinsertf64x4h(dst, src, 0);
3707   } else {
3708     Assembler::vmovdqu(dst, src);
3709   }
3710 }
3711 
3712 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3713   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3714     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3715   }
3716   else {
3717     Assembler::vmovdqu(dst, src);
3718   }
3719 }
3720 
3721 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3722   if (reachable(src)) {
3723     vmovdqu(dst, as_Address(src));
3724   }
3725   else {
3726     lea(rscratch1, src);
3727     vmovdqu(dst, Address(rscratch1, 0));
3728   }
3729 }
3730 
3731 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3732   if (reachable(src)) {
3733     Assembler::movdqa(dst, as_Address(src));
3734   } else {
3735     lea(rscratch1, src);
3736     Assembler::movdqa(dst, Address(rscratch1, 0));
3737   }
3738 }
3739 
3740 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3741   if (reachable(src)) {
3742     Assembler::movsd(dst, as_Address(src));
3743   } else {
3744     lea(rscratch1, src);
3745     Assembler::movsd(dst, Address(rscratch1, 0));
3746   }
3747 }
3748 
3749 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3750   if (reachable(src)) {
3751     Assembler::movss(dst, as_Address(src));
3752   } else {
3753     lea(rscratch1, src);
3754     Assembler::movss(dst, Address(rscratch1, 0));
3755   }
3756 }
3757 
3758 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3759   if (reachable(src)) {
3760     Assembler::mulsd(dst, as_Address(src));
3761   } else {
3762     lea(rscratch1, src);
3763     Assembler::mulsd(dst, Address(rscratch1, 0));
3764   }
3765 }
3766 
3767 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3768   if (reachable(src)) {
3769     Assembler::mulss(dst, as_Address(src));
3770   } else {
3771     lea(rscratch1, src);
3772     Assembler::mulss(dst, Address(rscratch1, 0));
3773   }
3774 }
3775 
3776 void MacroAssembler::null_check(Register reg, int offset) {
3777   if (needs_explicit_null_check(offset)) {
3778     // provoke OS NULL exception if reg = NULL by
3779     // accessing M[reg] w/o changing any (non-CC) registers
3780     // NOTE: cmpl is plenty here to provoke a segv
3781     cmpptr(rax, Address(reg, 0));
3782     // Note: should probably use testl(rax, Address(reg, 0));
3783     //       may be shorter code (however, this version of
3784     //       testl needs to be implemented first)
3785   } else {
3786     // nothing to do, (later) access of M[reg + offset]
3787     // will provoke OS NULL exception if reg = NULL
3788   }
3789 }
3790 
3791 void MacroAssembler::os_breakpoint() {
3792   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3793   // (e.g., MSVC can't call ps() otherwise)
3794   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3795 }
3796 
3797 #ifdef _LP64
3798 #define XSTATE_BV 0x200
3799 #endif
3800 
3801 void MacroAssembler::pop_CPU_state() {
3802   pop_FPU_state();
3803   pop_IU_state();
3804 }
3805 
3806 void MacroAssembler::pop_FPU_state() {
3807 #ifndef _LP64
3808   frstor(Address(rsp, 0));
3809 #else
3810   fxrstor(Address(rsp, 0));
3811 #endif
3812   addptr(rsp, FPUStateSizeInWords * wordSize);
3813 }
3814 
3815 void MacroAssembler::pop_IU_state() {
3816   popa();
3817   LP64_ONLY(addq(rsp, 8));
3818   popf();
3819 }
3820 
3821 // Save Integer and Float state
3822 // Warning: Stack must be 16 byte aligned (64bit)
3823 void MacroAssembler::push_CPU_state() {
3824   push_IU_state();
3825   push_FPU_state();
3826 }
3827 
3828 void MacroAssembler::push_FPU_state() {
3829   subptr(rsp, FPUStateSizeInWords * wordSize);
3830 #ifndef _LP64
3831   fnsave(Address(rsp, 0));
3832   fwait();
3833 #else
3834   fxsave(Address(rsp, 0));
3835 #endif // LP64
3836 }
3837 
3838 void MacroAssembler::push_IU_state() {
3839   // Push flags first because pusha kills them
3840   pushf();
3841   // Make sure rsp stays 16-byte aligned
3842   LP64_ONLY(subq(rsp, 8));
3843   pusha();
3844 }
3845 
3846 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3847   // determine java_thread register
3848   if (!java_thread->is_valid()) {
3849     java_thread = rdi;
3850     get_thread(java_thread);
3851   }
3852   // we must set sp to zero to clear frame
3853   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3854   if (clear_fp) {
3855     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3856   }
3857 
3858   if (clear_pc)
3859     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3860 
3861 }
3862 
3863 void MacroAssembler::restore_rax(Register tmp) {
3864   if (tmp == noreg) pop(rax);
3865   else if (tmp != rax) mov(rax, tmp);
3866 }
3867 
3868 void MacroAssembler::round_to(Register reg, int modulus) {
3869   addptr(reg, modulus - 1);
3870   andptr(reg, -modulus);
3871 }
3872 
3873 void MacroAssembler::save_rax(Register tmp) {
3874   if (tmp == noreg) push(rax);
3875   else if (tmp != rax) mov(tmp, rax);
3876 }
3877 
3878 // Write serialization page so VM thread can do a pseudo remote membar.
3879 // We use the current thread pointer to calculate a thread specific
3880 // offset to write to within the page. This minimizes bus traffic
3881 // due to cache line collision.
3882 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3883   movl(tmp, thread);
3884   shrl(tmp, os::get_serialize_page_shift_count());
3885   andl(tmp, (os::vm_page_size() - sizeof(int)));
3886 
3887   Address index(noreg, tmp, Address::times_1);
3888   ExternalAddress page(os::get_memory_serialize_page());
3889 
3890   // Size of store must match masking code above
3891   movl(as_Address(ArrayAddress(page, index)), tmp);
3892 }
3893 
3894 // Calls to C land
3895 //
3896 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3897 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3898 // has to be reset to 0. This is required to allow proper stack traversal.
3899 void MacroAssembler::set_last_Java_frame(Register java_thread,
3900                                          Register last_java_sp,
3901                                          Register last_java_fp,
3902                                          address  last_java_pc) {
3903   // determine java_thread register
3904   if (!java_thread->is_valid()) {
3905     java_thread = rdi;
3906     get_thread(java_thread);
3907   }
3908   // determine last_java_sp register
3909   if (!last_java_sp->is_valid()) {
3910     last_java_sp = rsp;
3911   }
3912 
3913   // last_java_fp is optional
3914 
3915   if (last_java_fp->is_valid()) {
3916     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3917   }
3918 
3919   // last_java_pc is optional
3920 
3921   if (last_java_pc != NULL) {
3922     lea(Address(java_thread,
3923                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3924         InternalAddress(last_java_pc));
3925 
3926   }
3927   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3928 }
3929 
3930 void MacroAssembler::shlptr(Register dst, int imm8) {
3931   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3932 }
3933 
3934 void MacroAssembler::shrptr(Register dst, int imm8) {
3935   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3936 }
3937 
3938 void MacroAssembler::sign_extend_byte(Register reg) {
3939   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3940     movsbl(reg, reg); // movsxb
3941   } else {
3942     shll(reg, 24);
3943     sarl(reg, 24);
3944   }
3945 }
3946 
3947 void MacroAssembler::sign_extend_short(Register reg) {
3948   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3949     movswl(reg, reg); // movsxw
3950   } else {
3951     shll(reg, 16);
3952     sarl(reg, 16);
3953   }
3954 }
3955 
3956 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3957   assert(reachable(src), "Address should be reachable");
3958   testl(dst, as_Address(src));
3959 }
3960 
3961 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3962   int dst_enc = dst->encoding();
3963   int src_enc = src->encoding();
3964   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3965     Assembler::pcmpeqb(dst, src);
3966   } else if ((dst_enc < 16) && (src_enc < 16)) {
3967     Assembler::pcmpeqb(dst, src);
3968   } else if (src_enc < 16) {
3969     subptr(rsp, 64);
3970     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3971     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3972     Assembler::pcmpeqb(xmm0, src);
3973     movdqu(dst, xmm0);
3974     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3975     addptr(rsp, 64);
3976   } else if (dst_enc < 16) {
3977     subptr(rsp, 64);
3978     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3979     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3980     Assembler::pcmpeqb(dst, xmm0);
3981     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3982     addptr(rsp, 64);
3983   } else {
3984     subptr(rsp, 64);
3985     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3988     movdqu(xmm0, src);
3989     movdqu(xmm1, dst);
3990     Assembler::pcmpeqb(xmm1, xmm0);
3991     movdqu(dst, xmm1);
3992     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3993     addptr(rsp, 64);
3994     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3995     addptr(rsp, 64);
3996   }
3997 }
3998 
3999 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
4000   int dst_enc = dst->encoding();
4001   int src_enc = src->encoding();
4002   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4003     Assembler::pcmpeqw(dst, src);
4004   } else if ((dst_enc < 16) && (src_enc < 16)) {
4005     Assembler::pcmpeqw(dst, src);
4006   } else if (src_enc < 16) {
4007     subptr(rsp, 64);
4008     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4009     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4010     Assembler::pcmpeqw(xmm0, src);
4011     movdqu(dst, xmm0);
4012     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4013     addptr(rsp, 64);
4014   } else if (dst_enc < 16) {
4015     subptr(rsp, 64);
4016     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4017     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4018     Assembler::pcmpeqw(dst, xmm0);
4019     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4020     addptr(rsp, 64);
4021   } else {
4022     subptr(rsp, 64);
4023     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4024     subptr(rsp, 64);
4025     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4026     movdqu(xmm0, src);
4027     movdqu(xmm1, dst);
4028     Assembler::pcmpeqw(xmm1, xmm0);
4029     movdqu(dst, xmm1);
4030     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4031     addptr(rsp, 64);
4032     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4033     addptr(rsp, 64);
4034   }
4035 }
4036 
4037 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
4038   int dst_enc = dst->encoding();
4039   if (dst_enc < 16) {
4040     Assembler::pcmpestri(dst, src, imm8);
4041   } else {
4042     subptr(rsp, 64);
4043     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4044     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4045     Assembler::pcmpestri(xmm0, src, imm8);
4046     movdqu(dst, xmm0);
4047     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4048     addptr(rsp, 64);
4049   }
4050 }
4051 
4052 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
4053   int dst_enc = dst->encoding();
4054   int src_enc = src->encoding();
4055   if ((dst_enc < 16) && (src_enc < 16)) {
4056     Assembler::pcmpestri(dst, src, imm8);
4057   } else if (src_enc < 16) {
4058     subptr(rsp, 64);
4059     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4060     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4061     Assembler::pcmpestri(xmm0, src, imm8);
4062     movdqu(dst, xmm0);
4063     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4064     addptr(rsp, 64);
4065   } else if (dst_enc < 16) {
4066     subptr(rsp, 64);
4067     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4068     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4069     Assembler::pcmpestri(dst, xmm0, imm8);
4070     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4071     addptr(rsp, 64);
4072   } else {
4073     subptr(rsp, 64);
4074     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4075     subptr(rsp, 64);
4076     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4077     movdqu(xmm0, src);
4078     movdqu(xmm1, dst);
4079     Assembler::pcmpestri(xmm1, xmm0, imm8);
4080     movdqu(dst, xmm1);
4081     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4082     addptr(rsp, 64);
4083     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4084     addptr(rsp, 64);
4085   }
4086 }
4087 
4088 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4089   int dst_enc = dst->encoding();
4090   int src_enc = src->encoding();
4091   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4092     Assembler::pmovzxbw(dst, src);
4093   } else if ((dst_enc < 16) && (src_enc < 16)) {
4094     Assembler::pmovzxbw(dst, src);
4095   } else if (src_enc < 16) {
4096     subptr(rsp, 64);
4097     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4098     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4099     Assembler::pmovzxbw(xmm0, src);
4100     movdqu(dst, xmm0);
4101     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4102     addptr(rsp, 64);
4103   } else if (dst_enc < 16) {
4104     subptr(rsp, 64);
4105     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4106     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4107     Assembler::pmovzxbw(dst, xmm0);
4108     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4109     addptr(rsp, 64);
4110   } else {
4111     subptr(rsp, 64);
4112     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4113     subptr(rsp, 64);
4114     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4115     movdqu(xmm0, src);
4116     movdqu(xmm1, dst);
4117     Assembler::pmovzxbw(xmm1, xmm0);
4118     movdqu(dst, xmm1);
4119     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4120     addptr(rsp, 64);
4121     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4122     addptr(rsp, 64);
4123   }
4124 }
4125 
4126 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4127   int dst_enc = dst->encoding();
4128   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4129     Assembler::pmovzxbw(dst, src);
4130   } else if (dst_enc < 16) {
4131     Assembler::pmovzxbw(dst, src);
4132   } else {
4133     subptr(rsp, 64);
4134     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4135     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4136     Assembler::pmovzxbw(xmm0, src);
4137     movdqu(dst, xmm0);
4138     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4139     addptr(rsp, 64);
4140   }
4141 }
4142 
4143 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4144   int src_enc = src->encoding();
4145   if (src_enc < 16) {
4146     Assembler::pmovmskb(dst, src);
4147   } else {
4148     subptr(rsp, 64);
4149     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4150     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4151     Assembler::pmovmskb(dst, xmm0);
4152     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4153     addptr(rsp, 64);
4154   }
4155 }
4156 
4157 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4158   int dst_enc = dst->encoding();
4159   int src_enc = src->encoding();
4160   if ((dst_enc < 16) && (src_enc < 16)) {
4161     Assembler::ptest(dst, src);
4162   } else if (src_enc < 16) {
4163     subptr(rsp, 64);
4164     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4165     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4166     Assembler::ptest(xmm0, src);
4167     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4168     addptr(rsp, 64);
4169   } else if (dst_enc < 16) {
4170     subptr(rsp, 64);
4171     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4172     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4173     Assembler::ptest(dst, xmm0);
4174     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4175     addptr(rsp, 64);
4176   } else {
4177     subptr(rsp, 64);
4178     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4179     subptr(rsp, 64);
4180     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4181     movdqu(xmm0, src);
4182     movdqu(xmm1, dst);
4183     Assembler::ptest(xmm1, xmm0);
4184     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4185     addptr(rsp, 64);
4186     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4187     addptr(rsp, 64);
4188   }
4189 }
4190 
4191 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4192   if (reachable(src)) {
4193     Assembler::sqrtsd(dst, as_Address(src));
4194   } else {
4195     lea(rscratch1, src);
4196     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4197   }
4198 }
4199 
4200 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4201   if (reachable(src)) {
4202     Assembler::sqrtss(dst, as_Address(src));
4203   } else {
4204     lea(rscratch1, src);
4205     Assembler::sqrtss(dst, Address(rscratch1, 0));
4206   }
4207 }
4208 
4209 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4210   if (reachable(src)) {
4211     Assembler::subsd(dst, as_Address(src));
4212   } else {
4213     lea(rscratch1, src);
4214     Assembler::subsd(dst, Address(rscratch1, 0));
4215   }
4216 }
4217 
4218 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4219   if (reachable(src)) {
4220     Assembler::subss(dst, as_Address(src));
4221   } else {
4222     lea(rscratch1, src);
4223     Assembler::subss(dst, Address(rscratch1, 0));
4224   }
4225 }
4226 
4227 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4228   if (reachable(src)) {
4229     Assembler::ucomisd(dst, as_Address(src));
4230   } else {
4231     lea(rscratch1, src);
4232     Assembler::ucomisd(dst, Address(rscratch1, 0));
4233   }
4234 }
4235 
4236 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4237   if (reachable(src)) {
4238     Assembler::ucomiss(dst, as_Address(src));
4239   } else {
4240     lea(rscratch1, src);
4241     Assembler::ucomiss(dst, Address(rscratch1, 0));
4242   }
4243 }
4244 
4245 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4246   // Used in sign-bit flipping with aligned address.
4247   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4248   if (reachable(src)) {
4249     Assembler::xorpd(dst, as_Address(src));
4250   } else {
4251     lea(rscratch1, src);
4252     Assembler::xorpd(dst, Address(rscratch1, 0));
4253   }
4254 }
4255 
4256 void MacroAssembler::xorpd(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   }
4260   else {
4261     Assembler::xorpd(dst, src);
4262   }
4263 }
4264 
4265 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4266   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4267     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4268   } else {
4269     Assembler::xorps(dst, src);
4270   }
4271 }
4272 
4273 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4274   // Used in sign-bit flipping with aligned address.
4275   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4276   if (reachable(src)) {
4277     Assembler::xorps(dst, as_Address(src));
4278   } else {
4279     lea(rscratch1, src);
4280     Assembler::xorps(dst, Address(rscratch1, 0));
4281   }
4282 }
4283 
4284 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4285   // Used in sign-bit flipping with aligned address.
4286   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4287   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4288   if (reachable(src)) {
4289     Assembler::pshufb(dst, as_Address(src));
4290   } else {
4291     lea(rscratch1, src);
4292     Assembler::pshufb(dst, Address(rscratch1, 0));
4293   }
4294 }
4295 
4296 // AVX 3-operands instructions
4297 
4298 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4299   if (reachable(src)) {
4300     vaddsd(dst, nds, as_Address(src));
4301   } else {
4302     lea(rscratch1, src);
4303     vaddsd(dst, nds, Address(rscratch1, 0));
4304   }
4305 }
4306 
4307 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4308   if (reachable(src)) {
4309     vaddss(dst, nds, as_Address(src));
4310   } else {
4311     lea(rscratch1, src);
4312     vaddss(dst, nds, Address(rscratch1, 0));
4313   }
4314 }
4315 
4316 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4317   int dst_enc = dst->encoding();
4318   int nds_enc = nds->encoding();
4319   int src_enc = src->encoding();
4320   if ((dst_enc < 16) && (nds_enc < 16)) {
4321     vandps(dst, nds, negate_field, vector_len);
4322   } else if ((src_enc < 16) && (dst_enc < 16)) {
4323     movss(src, nds);
4324     vandps(dst, src, negate_field, vector_len);
4325   } else if (src_enc < 16) {
4326     movss(src, nds);
4327     vandps(src, src, negate_field, vector_len);
4328     movss(dst, src);
4329   } else if (dst_enc < 16) {
4330     movdqu(src, xmm0);
4331     movss(xmm0, nds);
4332     vandps(dst, xmm0, negate_field, vector_len);
4333     movdqu(xmm0, src);
4334   } else if (nds_enc < 16) {
4335     movdqu(src, xmm0);
4336     vandps(xmm0, nds, negate_field, vector_len);
4337     movss(dst, xmm0);
4338     movdqu(xmm0, src);
4339   } else {
4340     movdqu(src, xmm0);
4341     movss(xmm0, nds);
4342     vandps(xmm0, xmm0, negate_field, vector_len);
4343     movss(dst, xmm0);
4344     movdqu(xmm0, src);
4345   }
4346 }
4347 
4348 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4349   int dst_enc = dst->encoding();
4350   int nds_enc = nds->encoding();
4351   int src_enc = src->encoding();
4352   if ((dst_enc < 16) && (nds_enc < 16)) {
4353     vandpd(dst, nds, negate_field, vector_len);
4354   } else if ((src_enc < 16) && (dst_enc < 16)) {
4355     movsd(src, nds);
4356     vandpd(dst, src, negate_field, vector_len);
4357   } else if (src_enc < 16) {
4358     movsd(src, nds);
4359     vandpd(src, src, negate_field, vector_len);
4360     movsd(dst, src);
4361   } else if (dst_enc < 16) {
4362     movdqu(src, xmm0);
4363     movsd(xmm0, nds);
4364     vandpd(dst, xmm0, negate_field, vector_len);
4365     movdqu(xmm0, src);
4366   } else if (nds_enc < 16) {
4367     movdqu(src, xmm0);
4368     vandpd(xmm0, nds, negate_field, vector_len);
4369     movsd(dst, xmm0);
4370     movdqu(xmm0, src);
4371   } else {
4372     movdqu(src, xmm0);
4373     movsd(xmm0, nds);
4374     vandpd(xmm0, xmm0, negate_field, vector_len);
4375     movsd(dst, xmm0);
4376     movdqu(xmm0, src);
4377   }
4378 }
4379 
4380 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4381   int dst_enc = dst->encoding();
4382   int nds_enc = nds->encoding();
4383   int src_enc = src->encoding();
4384   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4385     Assembler::vpaddb(dst, nds, src, vector_len);
4386   } else if ((dst_enc < 16) && (src_enc < 16)) {
4387     Assembler::vpaddb(dst, dst, src, vector_len);
4388   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4389     // use nds as scratch for src
4390     evmovdqul(nds, src, Assembler::AVX_512bit);
4391     Assembler::vpaddb(dst, dst, nds, vector_len);
4392   } else if ((src_enc < 16) && (nds_enc < 16)) {
4393     // use nds as scratch for dst
4394     evmovdqul(nds, dst, Assembler::AVX_512bit);
4395     Assembler::vpaddb(nds, nds, src, vector_len);
4396     evmovdqul(dst, nds, Assembler::AVX_512bit);
4397   } else if (dst_enc < 16) {
4398     // use nds as scatch for xmm0 to hold src
4399     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4400     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4401     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4402     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4403   } else {
4404     // worse case scenario, all regs are in the upper bank
4405     subptr(rsp, 64);
4406     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4407     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4408     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4409     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4410     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4411     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4412     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4413     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4414     addptr(rsp, 64);
4415   }
4416 }
4417 
4418 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4419   int dst_enc = dst->encoding();
4420   int nds_enc = nds->encoding();
4421   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4422     Assembler::vpaddb(dst, nds, src, vector_len);
4423   } else if (dst_enc < 16) {
4424     Assembler::vpaddb(dst, dst, src, vector_len);
4425   } else if (nds_enc < 16) {
4426     // implies dst_enc in upper bank with src as scratch
4427     evmovdqul(nds, dst, Assembler::AVX_512bit);
4428     Assembler::vpaddb(nds, nds, src, vector_len);
4429     evmovdqul(dst, nds, Assembler::AVX_512bit);
4430   } else {
4431     // worse case scenario, all regs in upper bank
4432     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4433     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4434     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4435     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4436   }
4437 }
4438 
4439 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4440   int dst_enc = dst->encoding();
4441   int nds_enc = nds->encoding();
4442   int src_enc = src->encoding();
4443   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4444     Assembler::vpaddw(dst, nds, src, vector_len);
4445   } else if ((dst_enc < 16) && (src_enc < 16)) {
4446     Assembler::vpaddw(dst, dst, src, vector_len);
4447   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4448     // use nds as scratch for src
4449     evmovdqul(nds, src, Assembler::AVX_512bit);
4450     Assembler::vpaddw(dst, dst, nds, vector_len);
4451   } else if ((src_enc < 16) && (nds_enc < 16)) {
4452     // use nds as scratch for dst
4453     evmovdqul(nds, dst, Assembler::AVX_512bit);
4454     Assembler::vpaddw(nds, nds, src, vector_len);
4455     evmovdqul(dst, nds, Assembler::AVX_512bit);
4456   } else if (dst_enc < 16) {
4457     // use nds as scatch for xmm0 to hold src
4458     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4459     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4460     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4461     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4462   } else {
4463     // worse case scenario, all regs are in the upper bank
4464     subptr(rsp, 64);
4465     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4466     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4467     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4468     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4469     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4470     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4471     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4472     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4473     addptr(rsp, 64);
4474   }
4475 }
4476 
4477 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4478   int dst_enc = dst->encoding();
4479   int nds_enc = nds->encoding();
4480   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4481     Assembler::vpaddw(dst, nds, src, vector_len);
4482   } else if (dst_enc < 16) {
4483     Assembler::vpaddw(dst, dst, src, vector_len);
4484   } else if (nds_enc < 16) {
4485     // implies dst_enc in upper bank with src as scratch
4486     evmovdqul(nds, dst, Assembler::AVX_512bit);
4487     Assembler::vpaddw(nds, nds, src, vector_len);
4488     evmovdqul(dst, nds, Assembler::AVX_512bit);
4489   } else {
4490     // worse case scenario, all regs in upper bank
4491     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4492     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4493     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4494     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4495   }
4496 }
4497 
4498 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4499   int dst_enc = dst->encoding();
4500   int src_enc = src->encoding();
4501   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4502     Assembler::vpbroadcastw(dst, src);
4503   } else if ((dst_enc < 16) && (src_enc < 16)) {
4504     Assembler::vpbroadcastw(dst, src);
4505   } else if (src_enc < 16) {
4506     subptr(rsp, 64);
4507     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4508     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4509     Assembler::vpbroadcastw(xmm0, src);
4510     movdqu(dst, xmm0);
4511     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4512     addptr(rsp, 64);
4513   } else if (dst_enc < 16) {
4514     subptr(rsp, 64);
4515     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4516     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4517     Assembler::vpbroadcastw(dst, xmm0);
4518     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4519     addptr(rsp, 64);
4520   } else {
4521     subptr(rsp, 64);
4522     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4523     subptr(rsp, 64);
4524     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4525     movdqu(xmm0, src);
4526     movdqu(xmm1, dst);
4527     Assembler::vpbroadcastw(xmm1, xmm0);
4528     movdqu(dst, xmm1);
4529     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4530     addptr(rsp, 64);
4531     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4532     addptr(rsp, 64);
4533   }
4534 }
4535 
4536 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4537   int dst_enc = dst->encoding();
4538   int nds_enc = nds->encoding();
4539   int src_enc = src->encoding();
4540   assert(dst_enc == nds_enc, "");
4541   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4542     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4543   } else if ((dst_enc < 16) && (src_enc < 16)) {
4544     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4545   } else if (src_enc < 16) {
4546     subptr(rsp, 64);
4547     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4548     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4549     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4550     movdqu(dst, xmm0);
4551     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4552     addptr(rsp, 64);
4553   } else if (dst_enc < 16) {
4554     subptr(rsp, 64);
4555     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4556     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4557     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4558     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4559     addptr(rsp, 64);
4560   } else {
4561     subptr(rsp, 64);
4562     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4563     subptr(rsp, 64);
4564     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4565     movdqu(xmm0, src);
4566     movdqu(xmm1, dst);
4567     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4568     movdqu(dst, xmm1);
4569     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4570     addptr(rsp, 64);
4571     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4572     addptr(rsp, 64);
4573   }
4574 }
4575 
4576 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4577   int dst_enc = dst->encoding();
4578   int nds_enc = nds->encoding();
4579   int src_enc = src->encoding();
4580   assert(dst_enc == nds_enc, "");
4581   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4582     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4583   } else if ((dst_enc < 16) && (src_enc < 16)) {
4584     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4585   } else if (src_enc < 16) {
4586     subptr(rsp, 64);
4587     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4588     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4589     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4590     movdqu(dst, xmm0);
4591     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4592     addptr(rsp, 64);
4593   } else if (dst_enc < 16) {
4594     subptr(rsp, 64);
4595     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4596     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4597     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4598     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4599     addptr(rsp, 64);
4600   } else {
4601     subptr(rsp, 64);
4602     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4603     subptr(rsp, 64);
4604     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4605     movdqu(xmm0, src);
4606     movdqu(xmm1, dst);
4607     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4608     movdqu(dst, xmm1);
4609     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4610     addptr(rsp, 64);
4611     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4612     addptr(rsp, 64);
4613   }
4614 }
4615 
4616 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4617   int dst_enc = dst->encoding();
4618   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4619     Assembler::vpmovzxbw(dst, src, vector_len);
4620   } else if (dst_enc < 16) {
4621     Assembler::vpmovzxbw(dst, src, vector_len);
4622   } else {
4623     subptr(rsp, 64);
4624     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4625     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4626     Assembler::vpmovzxbw(xmm0, src, vector_len);
4627     movdqu(dst, xmm0);
4628     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4629     addptr(rsp, 64);
4630   }
4631 }
4632 
4633 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4634   int src_enc = src->encoding();
4635   if (src_enc < 16) {
4636     Assembler::vpmovmskb(dst, src);
4637   } else {
4638     subptr(rsp, 64);
4639     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4640     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4641     Assembler::vpmovmskb(dst, xmm0);
4642     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4643     addptr(rsp, 64);
4644   }
4645 }
4646 
4647 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4648   int dst_enc = dst->encoding();
4649   int nds_enc = nds->encoding();
4650   int src_enc = src->encoding();
4651   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4652     Assembler::vpmullw(dst, nds, src, vector_len);
4653   } else if ((dst_enc < 16) && (src_enc < 16)) {
4654     Assembler::vpmullw(dst, dst, src, vector_len);
4655   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4656     // use nds as scratch for src
4657     evmovdqul(nds, src, Assembler::AVX_512bit);
4658     Assembler::vpmullw(dst, dst, nds, vector_len);
4659   } else if ((src_enc < 16) && (nds_enc < 16)) {
4660     // use nds as scratch for dst
4661     evmovdqul(nds, dst, Assembler::AVX_512bit);
4662     Assembler::vpmullw(nds, nds, src, vector_len);
4663     evmovdqul(dst, nds, Assembler::AVX_512bit);
4664   } else if (dst_enc < 16) {
4665     // use nds as scatch for xmm0 to hold src
4666     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4667     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4668     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4669     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4670   } else {
4671     // worse case scenario, all regs are in the upper bank
4672     subptr(rsp, 64);
4673     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4674     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4675     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4676     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4677     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4678     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4679     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4680     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4681     addptr(rsp, 64);
4682   }
4683 }
4684 
4685 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4686   int dst_enc = dst->encoding();
4687   int nds_enc = nds->encoding();
4688   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4689     Assembler::vpmullw(dst, nds, src, vector_len);
4690   } else if (dst_enc < 16) {
4691     Assembler::vpmullw(dst, dst, src, vector_len);
4692   } else if (nds_enc < 16) {
4693     // implies dst_enc in upper bank with src as scratch
4694     evmovdqul(nds, dst, Assembler::AVX_512bit);
4695     Assembler::vpmullw(nds, nds, src, vector_len);
4696     evmovdqul(dst, nds, Assembler::AVX_512bit);
4697   } else {
4698     // worse case scenario, all regs in upper bank
4699     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4700     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4701     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4702     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4703   }
4704 }
4705 
4706 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4707   int dst_enc = dst->encoding();
4708   int nds_enc = nds->encoding();
4709   int src_enc = src->encoding();
4710   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4711     Assembler::vpsubb(dst, nds, src, vector_len);
4712   } else if ((dst_enc < 16) && (src_enc < 16)) {
4713     Assembler::vpsubb(dst, dst, src, vector_len);
4714   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4715     // use nds as scratch for src
4716     evmovdqul(nds, src, Assembler::AVX_512bit);
4717     Assembler::vpsubb(dst, dst, nds, vector_len);
4718   } else if ((src_enc < 16) && (nds_enc < 16)) {
4719     // use nds as scratch for dst
4720     evmovdqul(nds, dst, Assembler::AVX_512bit);
4721     Assembler::vpsubb(nds, nds, src, vector_len);
4722     evmovdqul(dst, nds, Assembler::AVX_512bit);
4723   } else if (dst_enc < 16) {
4724     // use nds as scatch for xmm0 to hold src
4725     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4726     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4727     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4728     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4729   } else {
4730     // worse case scenario, all regs are in the upper bank
4731     subptr(rsp, 64);
4732     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4733     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4734     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4735     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4736     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4737     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4738     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4739     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4740     addptr(rsp, 64);
4741   }
4742 }
4743 
4744 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4745   int dst_enc = dst->encoding();
4746   int nds_enc = nds->encoding();
4747   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4748     Assembler::vpsubb(dst, nds, src, vector_len);
4749   } else if (dst_enc < 16) {
4750     Assembler::vpsubb(dst, dst, src, vector_len);
4751   } else if (nds_enc < 16) {
4752     // implies dst_enc in upper bank with src as scratch
4753     evmovdqul(nds, dst, Assembler::AVX_512bit);
4754     Assembler::vpsubb(nds, nds, src, vector_len);
4755     evmovdqul(dst, nds, Assembler::AVX_512bit);
4756   } else {
4757     // worse case scenario, all regs in upper bank
4758     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4759     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4760     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4761     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4762   }
4763 }
4764 
4765 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4766   int dst_enc = dst->encoding();
4767   int nds_enc = nds->encoding();
4768   int src_enc = src->encoding();
4769   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4770     Assembler::vpsubw(dst, nds, src, vector_len);
4771   } else if ((dst_enc < 16) && (src_enc < 16)) {
4772     Assembler::vpsubw(dst, dst, src, vector_len);
4773   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4774     // use nds as scratch for src
4775     evmovdqul(nds, src, Assembler::AVX_512bit);
4776     Assembler::vpsubw(dst, dst, nds, vector_len);
4777   } else if ((src_enc < 16) && (nds_enc < 16)) {
4778     // use nds as scratch for dst
4779     evmovdqul(nds, dst, Assembler::AVX_512bit);
4780     Assembler::vpsubw(nds, nds, src, vector_len);
4781     evmovdqul(dst, nds, Assembler::AVX_512bit);
4782   } else if (dst_enc < 16) {
4783     // use nds as scatch for xmm0 to hold src
4784     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4785     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4786     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4787     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4788   } else {
4789     // worse case scenario, all regs are in the upper bank
4790     subptr(rsp, 64);
4791     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4792     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4793     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4794     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4795     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4796     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4797     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4798     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4799     addptr(rsp, 64);
4800   }
4801 }
4802 
4803 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4804   int dst_enc = dst->encoding();
4805   int nds_enc = nds->encoding();
4806   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4807     Assembler::vpsubw(dst, nds, src, vector_len);
4808   } else if (dst_enc < 16) {
4809     Assembler::vpsubw(dst, dst, src, vector_len);
4810   } else if (nds_enc < 16) {
4811     // implies dst_enc in upper bank with src as scratch
4812     evmovdqul(nds, dst, Assembler::AVX_512bit);
4813     Assembler::vpsubw(nds, nds, src, vector_len);
4814     evmovdqul(dst, nds, Assembler::AVX_512bit);
4815   } else {
4816     // worse case scenario, all regs in upper bank
4817     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4818     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4819     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4820     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4821   }
4822 }
4823 
4824 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4825   int dst_enc = dst->encoding();
4826   int nds_enc = nds->encoding();
4827   int shift_enc = shift->encoding();
4828   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4829     Assembler::vpsraw(dst, nds, shift, vector_len);
4830   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4831     Assembler::vpsraw(dst, dst, shift, vector_len);
4832   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4833     // use nds_enc as scratch with shift
4834     evmovdqul(nds, shift, Assembler::AVX_512bit);
4835     Assembler::vpsraw(dst, dst, nds, vector_len);
4836   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4837     // use nds as scratch with dst
4838     evmovdqul(nds, dst, Assembler::AVX_512bit);
4839     Assembler::vpsraw(nds, nds, shift, vector_len);
4840     evmovdqul(dst, nds, Assembler::AVX_512bit);
4841   } else if (dst_enc < 16) {
4842     // use nds to save a copy of xmm0 and hold shift
4843     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4844     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4845     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4846     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4847   } else if (nds_enc < 16) {
4848     // use nds as dest as temps
4849     evmovdqul(nds, dst, Assembler::AVX_512bit);
4850     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4851     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4852     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4853     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4854     evmovdqul(dst, nds, Assembler::AVX_512bit);
4855   } else {
4856     // worse case scenario, all regs are in the upper bank
4857     subptr(rsp, 64);
4858     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4859     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4860     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4861     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4862     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4863     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4864     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4865     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4866     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4867     addptr(rsp, 64);
4868   }
4869 }
4870 
4871 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4872   int dst_enc = dst->encoding();
4873   int nds_enc = nds->encoding();
4874   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4875     Assembler::vpsraw(dst, nds, shift, vector_len);
4876   } else if (dst_enc < 16) {
4877     Assembler::vpsraw(dst, dst, shift, vector_len);
4878   } else if (nds_enc < 16) {
4879     // use nds as scratch
4880     evmovdqul(nds, dst, Assembler::AVX_512bit);
4881     Assembler::vpsraw(nds, nds, shift, vector_len);
4882     evmovdqul(dst, nds, Assembler::AVX_512bit);
4883   } else {
4884     // use nds as scratch for xmm0
4885     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4886     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4887     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4888     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4889   }
4890 }
4891 
4892 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4893   int dst_enc = dst->encoding();
4894   int nds_enc = nds->encoding();
4895   int shift_enc = shift->encoding();
4896   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4897     Assembler::vpsrlw(dst, nds, shift, vector_len);
4898   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4899     Assembler::vpsrlw(dst, dst, shift, vector_len);
4900   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4901     // use nds_enc as scratch with shift
4902     evmovdqul(nds, shift, Assembler::AVX_512bit);
4903     Assembler::vpsrlw(dst, dst, nds, vector_len);
4904   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4905     // use nds as scratch with dst
4906     evmovdqul(nds, dst, Assembler::AVX_512bit);
4907     Assembler::vpsrlw(nds, nds, shift, vector_len);
4908     evmovdqul(dst, nds, Assembler::AVX_512bit);
4909   } else if (dst_enc < 16) {
4910     // use nds to save a copy of xmm0 and hold shift
4911     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4912     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4913     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4914     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4915   } else if (nds_enc < 16) {
4916     // use nds as dest as temps
4917     evmovdqul(nds, dst, Assembler::AVX_512bit);
4918     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4919     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4920     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4921     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4922     evmovdqul(dst, nds, Assembler::AVX_512bit);
4923   } else {
4924     // worse case scenario, all regs are in the upper bank
4925     subptr(rsp, 64);
4926     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4927     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4928     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4929     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4930     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4931     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4932     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4933     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4934     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4935     addptr(rsp, 64);
4936   }
4937 }
4938 
4939 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4940   int dst_enc = dst->encoding();
4941   int nds_enc = nds->encoding();
4942   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4943     Assembler::vpsrlw(dst, nds, shift, vector_len);
4944   } else if (dst_enc < 16) {
4945     Assembler::vpsrlw(dst, dst, shift, vector_len);
4946   } else if (nds_enc < 16) {
4947     // use nds as scratch
4948     evmovdqul(nds, dst, Assembler::AVX_512bit);
4949     Assembler::vpsrlw(nds, nds, shift, vector_len);
4950     evmovdqul(dst, nds, Assembler::AVX_512bit);
4951   } else {
4952     // use nds as scratch for xmm0
4953     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4954     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4955     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4956     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4957   }
4958 }
4959 
4960 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4961   int dst_enc = dst->encoding();
4962   int nds_enc = nds->encoding();
4963   int shift_enc = shift->encoding();
4964   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4965     Assembler::vpsllw(dst, nds, shift, vector_len);
4966   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4967     Assembler::vpsllw(dst, dst, shift, vector_len);
4968   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4969     // use nds_enc as scratch with shift
4970     evmovdqul(nds, shift, Assembler::AVX_512bit);
4971     Assembler::vpsllw(dst, dst, nds, vector_len);
4972   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4973     // use nds as scratch with dst
4974     evmovdqul(nds, dst, Assembler::AVX_512bit);
4975     Assembler::vpsllw(nds, nds, shift, vector_len);
4976     evmovdqul(dst, nds, Assembler::AVX_512bit);
4977   } else if (dst_enc < 16) {
4978     // use nds to save a copy of xmm0 and hold shift
4979     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4980     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4981     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4982     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4983   } else if (nds_enc < 16) {
4984     // use nds as dest as temps
4985     evmovdqul(nds, dst, Assembler::AVX_512bit);
4986     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4987     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4988     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4989     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4990     evmovdqul(dst, nds, Assembler::AVX_512bit);
4991   } else {
4992     // worse case scenario, all regs are in the upper bank
4993     subptr(rsp, 64);
4994     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4995     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4996     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4997     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4998     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4999     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
5000     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5001     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5002     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5003     addptr(rsp, 64);
5004   }
5005 }
5006 
5007 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
5008   int dst_enc = dst->encoding();
5009   int nds_enc = nds->encoding();
5010   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
5011     Assembler::vpsllw(dst, nds, shift, vector_len);
5012   } else if (dst_enc < 16) {
5013     Assembler::vpsllw(dst, dst, shift, vector_len);
5014   } else if (nds_enc < 16) {
5015     // use nds as scratch
5016     evmovdqul(nds, dst, Assembler::AVX_512bit);
5017     Assembler::vpsllw(nds, nds, shift, vector_len);
5018     evmovdqul(dst, nds, Assembler::AVX_512bit);
5019   } else {
5020     // use nds as scratch for xmm0
5021     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
5022     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5023     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
5024     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5025   }
5026 }
5027 
5028 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
5029   int dst_enc = dst->encoding();
5030   int src_enc = src->encoding();
5031   if ((dst_enc < 16) && (src_enc < 16)) {
5032     Assembler::vptest(dst, src);
5033   } else if (src_enc < 16) {
5034     subptr(rsp, 64);
5035     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5036     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5037     Assembler::vptest(xmm0, src);
5038     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5039     addptr(rsp, 64);
5040   } else if (dst_enc < 16) {
5041     subptr(rsp, 64);
5042     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5043     evmovdqul(xmm0, src, Assembler::AVX_512bit);
5044     Assembler::vptest(dst, xmm0);
5045     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5046     addptr(rsp, 64);
5047   } else {
5048     subptr(rsp, 64);
5049     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5050     subptr(rsp, 64);
5051     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5052     movdqu(xmm0, src);
5053     movdqu(xmm1, dst);
5054     Assembler::vptest(xmm1, xmm0);
5055     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5056     addptr(rsp, 64);
5057     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5058     addptr(rsp, 64);
5059   }
5060 }
5061 
5062 // This instruction exists within macros, ergo we cannot control its input
5063 // when emitted through those patterns.
5064 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
5065   if (VM_Version::supports_avx512nobw()) {
5066     int dst_enc = dst->encoding();
5067     int src_enc = src->encoding();
5068     if (dst_enc == src_enc) {
5069       if (dst_enc < 16) {
5070         Assembler::punpcklbw(dst, src);
5071       } else {
5072         subptr(rsp, 64);
5073         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5074         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5075         Assembler::punpcklbw(xmm0, xmm0);
5076         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5078         addptr(rsp, 64);
5079       }
5080     } else {
5081       if ((src_enc < 16) && (dst_enc < 16)) {
5082         Assembler::punpcklbw(dst, src);
5083       } else if (src_enc < 16) {
5084         subptr(rsp, 64);
5085         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5086         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5087         Assembler::punpcklbw(xmm0, src);
5088         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5089         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5090         addptr(rsp, 64);
5091       } else if (dst_enc < 16) {
5092         subptr(rsp, 64);
5093         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5094         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5095         Assembler::punpcklbw(dst, xmm0);
5096         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5097         addptr(rsp, 64);
5098       } else {
5099         subptr(rsp, 64);
5100         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5101         subptr(rsp, 64);
5102         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5103         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5104         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5105         Assembler::punpcklbw(xmm0, xmm1);
5106         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5107         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5108         addptr(rsp, 64);
5109         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5110         addptr(rsp, 64);
5111       }
5112     }
5113   } else {
5114     Assembler::punpcklbw(dst, src);
5115   }
5116 }
5117 
5118 // This instruction exists within macros, ergo we cannot control its input
5119 // when emitted through those patterns.
5120 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5121   if (VM_Version::supports_avx512nobw()) {
5122     int dst_enc = dst->encoding();
5123     int src_enc = src->encoding();
5124     if (dst_enc == src_enc) {
5125       if (dst_enc < 16) {
5126         Assembler::pshuflw(dst, src, mode);
5127       } else {
5128         subptr(rsp, 64);
5129         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5130         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5131         Assembler::pshuflw(xmm0, xmm0, mode);
5132         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5133         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5134         addptr(rsp, 64);
5135       }
5136     } else {
5137       if ((src_enc < 16) && (dst_enc < 16)) {
5138         Assembler::pshuflw(dst, src, mode);
5139       } else if (src_enc < 16) {
5140         subptr(rsp, 64);
5141         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5142         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5143         Assembler::pshuflw(xmm0, src, mode);
5144         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5145         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5146         addptr(rsp, 64);
5147       } else if (dst_enc < 16) {
5148         subptr(rsp, 64);
5149         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5150         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5151         Assembler::pshuflw(dst, xmm0, mode);
5152         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5153         addptr(rsp, 64);
5154       } else {
5155         subptr(rsp, 64);
5156         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5157         subptr(rsp, 64);
5158         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5159         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5160         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5161         Assembler::pshuflw(xmm0, xmm1, mode);
5162         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5163         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5164         addptr(rsp, 64);
5165         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5166         addptr(rsp, 64);
5167       }
5168     }
5169   } else {
5170     Assembler::pshuflw(dst, src, mode);
5171   }
5172 }
5173 
5174 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5175   if (reachable(src)) {
5176     vandpd(dst, nds, as_Address(src), vector_len);
5177   } else {
5178     lea(rscratch1, src);
5179     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5180   }
5181 }
5182 
5183 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5184   if (reachable(src)) {
5185     vandps(dst, nds, as_Address(src), vector_len);
5186   } else {
5187     lea(rscratch1, src);
5188     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5189   }
5190 }
5191 
5192 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5193   if (reachable(src)) {
5194     vdivsd(dst, nds, as_Address(src));
5195   } else {
5196     lea(rscratch1, src);
5197     vdivsd(dst, nds, Address(rscratch1, 0));
5198   }
5199 }
5200 
5201 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5202   if (reachable(src)) {
5203     vdivss(dst, nds, as_Address(src));
5204   } else {
5205     lea(rscratch1, src);
5206     vdivss(dst, nds, Address(rscratch1, 0));
5207   }
5208 }
5209 
5210 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5211   if (reachable(src)) {
5212     vmulsd(dst, nds, as_Address(src));
5213   } else {
5214     lea(rscratch1, src);
5215     vmulsd(dst, nds, Address(rscratch1, 0));
5216   }
5217 }
5218 
5219 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5220   if (reachable(src)) {
5221     vmulss(dst, nds, as_Address(src));
5222   } else {
5223     lea(rscratch1, src);
5224     vmulss(dst, nds, Address(rscratch1, 0));
5225   }
5226 }
5227 
5228 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5229   if (reachable(src)) {
5230     vsubsd(dst, nds, as_Address(src));
5231   } else {
5232     lea(rscratch1, src);
5233     vsubsd(dst, nds, Address(rscratch1, 0));
5234   }
5235 }
5236 
5237 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5238   if (reachable(src)) {
5239     vsubss(dst, nds, as_Address(src));
5240   } else {
5241     lea(rscratch1, src);
5242     vsubss(dst, nds, Address(rscratch1, 0));
5243   }
5244 }
5245 
5246 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5247   int nds_enc = nds->encoding();
5248   int dst_enc = dst->encoding();
5249   bool dst_upper_bank = (dst_enc > 15);
5250   bool nds_upper_bank = (nds_enc > 15);
5251   if (VM_Version::supports_avx512novl() &&
5252       (nds_upper_bank || dst_upper_bank)) {
5253     if (dst_upper_bank) {
5254       subptr(rsp, 64);
5255       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5256       movflt(xmm0, nds);
5257       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5258       movflt(dst, xmm0);
5259       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5260       addptr(rsp, 64);
5261     } else {
5262       movflt(dst, nds);
5263       vxorps(dst, dst, src, Assembler::AVX_128bit);
5264     }
5265   } else {
5266     vxorps(dst, nds, src, Assembler::AVX_128bit);
5267   }
5268 }
5269 
5270 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5271   int nds_enc = nds->encoding();
5272   int dst_enc = dst->encoding();
5273   bool dst_upper_bank = (dst_enc > 15);
5274   bool nds_upper_bank = (nds_enc > 15);
5275   if (VM_Version::supports_avx512novl() &&
5276       (nds_upper_bank || dst_upper_bank)) {
5277     if (dst_upper_bank) {
5278       subptr(rsp, 64);
5279       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5280       movdbl(xmm0, nds);
5281       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5282       movdbl(dst, xmm0);
5283       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5284       addptr(rsp, 64);
5285     } else {
5286       movdbl(dst, nds);
5287       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5288     }
5289   } else {
5290     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5291   }
5292 }
5293 
5294 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5295   if (reachable(src)) {
5296     vxorpd(dst, nds, as_Address(src), vector_len);
5297   } else {
5298     lea(rscratch1, src);
5299     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5300   }
5301 }
5302 
5303 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5304   if (reachable(src)) {
5305     vxorps(dst, nds, as_Address(src), vector_len);
5306   } else {
5307     lea(rscratch1, src);
5308     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5309   }
5310 }
5311 
5312 
5313 //////////////////////////////////////////////////////////////////////////////////
5314 #if INCLUDE_ALL_GCS
5315 
5316 void MacroAssembler::g1_write_barrier_pre(Register obj,
5317                                           Register pre_val,
5318                                           Register thread,
5319                                           Register tmp,
5320                                           bool tosca_live,
5321                                           bool expand_call) {
5322 
5323   // If expand_call is true then we expand the call_VM_leaf macro
5324   // directly to skip generating the check by
5325   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5326 
5327 #ifdef _LP64
5328   assert(thread == r15_thread, "must be");
5329 #endif // _LP64
5330 
5331   Label done;
5332   Label runtime;
5333 
5334   assert(pre_val != noreg, "check this code");
5335 
5336   if (obj != noreg) {
5337     assert_different_registers(obj, pre_val, tmp);
5338     assert(pre_val != rax, "check this code");
5339   }
5340 
5341   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5342                                        SATBMarkQueue::byte_offset_of_active()));
5343   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5344                                        SATBMarkQueue::byte_offset_of_index()));
5345   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5346                                        SATBMarkQueue::byte_offset_of_buf()));
5347 
5348 
5349   // Is marking active?
5350   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5351     cmpl(in_progress, 0);
5352   } else {
5353     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5354     cmpb(in_progress, 0);
5355   }
5356   jcc(Assembler::equal, done);
5357 
5358   // Do we need to load the previous value?
5359   if (obj != noreg) {
5360     load_heap_oop(pre_val, Address(obj, 0));
5361   }
5362 
5363   // Is the previous value null?
5364   cmpptr(pre_val, (int32_t) NULL_WORD);
5365   jcc(Assembler::equal, done);
5366 
5367   // Can we store original value in the thread's buffer?
5368   // Is index == 0?
5369   // (The index field is typed as size_t.)
5370 
5371   movptr(tmp, index);                   // tmp := *index_adr
5372   cmpptr(tmp, 0);                       // tmp == 0?
5373   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5374 
5375   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5376   movptr(index, tmp);                   // *index_adr := tmp
5377   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5378 
5379   // Record the previous value
5380   movptr(Address(tmp, 0), pre_val);
5381   jmp(done);
5382 
5383   bind(runtime);
5384   // save the live input values
5385   if(tosca_live) push(rax);
5386 
5387   if (obj != noreg && obj != rax)
5388     push(obj);
5389 
5390   if (pre_val != rax)
5391     push(pre_val);
5392 
5393   // Calling the runtime using the regular call_VM_leaf mechanism generates
5394   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5395   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5396   //
5397   // If we care generating the pre-barrier without a frame (e.g. in the
5398   // intrinsified Reference.get() routine) then ebp might be pointing to
5399   // the caller frame and so this check will most likely fail at runtime.
5400   //
5401   // Expanding the call directly bypasses the generation of the check.
5402   // So when we do not have have a full interpreter frame on the stack
5403   // expand_call should be passed true.
5404 
5405   NOT_LP64( push(thread); )
5406 
5407   if (expand_call) {
5408     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5409     pass_arg1(this, thread);
5410     pass_arg0(this, pre_val);
5411     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5412   } else {
5413     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5414   }
5415 
5416   NOT_LP64( pop(thread); )
5417 
5418   // save the live input values
5419   if (pre_val != rax)
5420     pop(pre_val);
5421 
5422   if (obj != noreg && obj != rax)
5423     pop(obj);
5424 
5425   if(tosca_live) pop(rax);
5426 
5427   bind(done);
5428 }
5429 
5430 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5431                                            Register new_val,
5432                                            Register thread,
5433                                            Register tmp,
5434                                            Register tmp2) {
5435 #ifdef _LP64
5436   assert(thread == r15_thread, "must be");
5437 #endif // _LP64
5438 
5439   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5440                                        DirtyCardQueue::byte_offset_of_index()));
5441   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5442                                        DirtyCardQueue::byte_offset_of_buf()));
5443 
5444   CardTableModRefBS* ct =
5445     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5446   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5447 
5448   Label done;
5449   Label runtime;
5450 
5451   // Does store cross heap regions?
5452 
5453   movptr(tmp, store_addr);
5454   xorptr(tmp, new_val);
5455   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5456   jcc(Assembler::equal, done);
5457 
5458   // crosses regions, storing NULL?
5459 
5460   cmpptr(new_val, (int32_t) NULL_WORD);
5461   jcc(Assembler::equal, done);
5462 
5463   // storing region crossing non-NULL, is card already dirty?
5464 
5465   const Register card_addr = tmp;
5466   const Register cardtable = tmp2;
5467 
5468   movptr(card_addr, store_addr);
5469   shrptr(card_addr, CardTableModRefBS::card_shift);
5470   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5471   // a valid address and therefore is not properly handled by the relocation code.
5472   movptr(cardtable, (intptr_t)ct->byte_map_base);
5473   addptr(card_addr, cardtable);
5474 
5475   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5476   jcc(Assembler::equal, done);
5477 
5478   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5479   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5480   jcc(Assembler::equal, done);
5481 
5482 
5483   // storing a region crossing, non-NULL oop, card is clean.
5484   // dirty card and log.
5485 
5486   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5487 
5488   cmpl(queue_index, 0);
5489   jcc(Assembler::equal, runtime);
5490   subl(queue_index, wordSize);
5491   movptr(tmp2, buffer);
5492 #ifdef _LP64
5493   movslq(rscratch1, queue_index);
5494   addq(tmp2, rscratch1);
5495   movq(Address(tmp2, 0), card_addr);
5496 #else
5497   addl(tmp2, queue_index);
5498   movl(Address(tmp2, 0), card_addr);
5499 #endif
5500   jmp(done);
5501 
5502   bind(runtime);
5503   // save the live input values
5504   push(store_addr);
5505   push(new_val);
5506 #ifdef _LP64
5507   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5508 #else
5509   push(thread);
5510   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5511   pop(thread);
5512 #endif
5513   pop(new_val);
5514   pop(store_addr);
5515 
5516   bind(done);
5517 }
5518 
5519 #endif // INCLUDE_ALL_GCS
5520 //////////////////////////////////////////////////////////////////////////////////
5521 
5522 
5523 void MacroAssembler::store_check(Register obj, Address dst) {
5524   store_check(obj);
5525 }
5526 
5527 void MacroAssembler::store_check(Register obj) {
5528   // Does a store check for the oop in register obj. The content of
5529   // register obj is destroyed afterwards.
5530   BarrierSet* bs = Universe::heap()->barrier_set();
5531   assert(bs->kind() == BarrierSet::CardTableForRS ||
5532          bs->kind() == BarrierSet::CardTableExtension,
5533          "Wrong barrier set kind");
5534 
5535   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5536   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5537 
5538   shrptr(obj, CardTableModRefBS::card_shift);
5539 
5540   Address card_addr;
5541 
5542   // The calculation for byte_map_base is as follows:
5543   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5544   // So this essentially converts an address to a displacement and it will
5545   // never need to be relocated. On 64bit however the value may be too
5546   // large for a 32bit displacement.
5547   intptr_t disp = (intptr_t) ct->byte_map_base;
5548   if (is_simm32(disp)) {
5549     card_addr = Address(noreg, obj, Address::times_1, disp);
5550   } else {
5551     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5552     // displacement and done in a single instruction given favorable mapping and a
5553     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5554     // entry and that entry is not properly handled by the relocation code.
5555     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5556     Address index(noreg, obj, Address::times_1);
5557     card_addr = as_Address(ArrayAddress(cardtable, index));
5558   }
5559 
5560   int dirty = CardTableModRefBS::dirty_card_val();
5561   if (UseCondCardMark) {
5562     Label L_already_dirty;
5563     if (UseConcMarkSweepGC) {
5564       membar(Assembler::StoreLoad);
5565     }
5566     cmpb(card_addr, dirty);
5567     jcc(Assembler::equal, L_already_dirty);
5568     movb(card_addr, dirty);
5569     bind(L_already_dirty);
5570   } else {
5571     movb(card_addr, dirty);
5572   }
5573 }
5574 
5575 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5576   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5577 }
5578 
5579 // Force generation of a 4 byte immediate value even if it fits into 8bit
5580 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5581   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5582 }
5583 
5584 void MacroAssembler::subptr(Register dst, Register src) {
5585   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5586 }
5587 
5588 // C++ bool manipulation
5589 void MacroAssembler::testbool(Register dst) {
5590   if(sizeof(bool) == 1)
5591     testb(dst, 0xff);
5592   else if(sizeof(bool) == 2) {
5593     // testw implementation needed for two byte bools
5594     ShouldNotReachHere();
5595   } else if(sizeof(bool) == 4)
5596     testl(dst, dst);
5597   else
5598     // unsupported
5599     ShouldNotReachHere();
5600 }
5601 
5602 void MacroAssembler::testptr(Register dst, Register src) {
5603   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5604 }
5605 
5606 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5607 void MacroAssembler::tlab_allocate(Register obj,
5608                                    Register var_size_in_bytes,
5609                                    int con_size_in_bytes,
5610                                    Register t1,
5611                                    Register t2,
5612                                    Label& slow_case) {
5613   assert_different_registers(obj, t1, t2);
5614   assert_different_registers(obj, var_size_in_bytes, t1);
5615   Register end = t2;
5616   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5617 
5618   verify_tlab();
5619 
5620   NOT_LP64(get_thread(thread));
5621 
5622   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5623   if (var_size_in_bytes == noreg) {
5624     lea(end, Address(obj, con_size_in_bytes));
5625   } else {
5626     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5627   }
5628   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5629   jcc(Assembler::above, slow_case);
5630 
5631   // update the tlab top pointer
5632   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5633 
5634   // recover var_size_in_bytes if necessary
5635   if (var_size_in_bytes == end) {
5636     subptr(var_size_in_bytes, obj);
5637   }
5638   verify_tlab();
5639 }
5640 
5641 // Preserves rbx, and rdx.
5642 Register MacroAssembler::tlab_refill(Label& retry,
5643                                      Label& try_eden,
5644                                      Label& slow_case) {
5645   Register top = rax;
5646   Register t1  = rcx;
5647   Register t2  = rsi;
5648   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5649   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5650   Label do_refill, discard_tlab;
5651 
5652   if (!Universe::heap()->supports_inline_contig_alloc()) {
5653     // No allocation in the shared eden.
5654     jmp(slow_case);
5655   }
5656 
5657   NOT_LP64(get_thread(thread_reg));
5658 
5659   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5660   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5661 
5662   // calculate amount of free space
5663   subptr(t1, top);
5664   shrptr(t1, LogHeapWordSize);
5665 
5666   // Retain tlab and allocate object in shared space if
5667   // the amount free in the tlab is too large to discard.
5668   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5669   jcc(Assembler::lessEqual, discard_tlab);
5670 
5671   // Retain
5672   // %%% yuck as movptr...
5673   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5674   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5675   if (TLABStats) {
5676     // increment number of slow_allocations
5677     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5678   }
5679   jmp(try_eden);
5680 
5681   bind(discard_tlab);
5682   if (TLABStats) {
5683     // increment number of refills
5684     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5685     // accumulate wastage -- t1 is amount free in tlab
5686     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5687   }
5688 
5689   // if tlab is currently allocated (top or end != null) then
5690   // fill [top, end + alignment_reserve) with array object
5691   testptr(top, top);
5692   jcc(Assembler::zero, do_refill);
5693 
5694   // set up the mark word
5695   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5696   // set the length to the remaining space
5697   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5698   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5699   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5700   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5701   // set klass to intArrayKlass
5702   // dubious reloc why not an oop reloc?
5703   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5704   // store klass last.  concurrent gcs assumes klass length is valid if
5705   // klass field is not null.
5706   store_klass(top, t1);
5707 
5708   movptr(t1, top);
5709   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5710   incr_allocated_bytes(thread_reg, t1, 0);
5711 
5712   // refill the tlab with an eden allocation
5713   bind(do_refill);
5714   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5715   shlptr(t1, LogHeapWordSize);
5716   // allocate new tlab, address returned in top
5717   eden_allocate(top, t1, 0, t2, slow_case);
5718 
5719   // Check that t1 was preserved in eden_allocate.
5720 #ifdef ASSERT
5721   if (UseTLAB) {
5722     Label ok;
5723     Register tsize = rsi;
5724     assert_different_registers(tsize, thread_reg, t1);
5725     push(tsize);
5726     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5727     shlptr(tsize, LogHeapWordSize);
5728     cmpptr(t1, tsize);
5729     jcc(Assembler::equal, ok);
5730     STOP("assert(t1 != tlab size)");
5731     should_not_reach_here();
5732 
5733     bind(ok);
5734     pop(tsize);
5735   }
5736 #endif
5737   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5738   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5739   addptr(top, t1);
5740   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5741   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5742   verify_tlab();
5743   jmp(retry);
5744 
5745   return thread_reg; // for use by caller
5746 }
5747 
5748 void MacroAssembler::incr_allocated_bytes(Register thread,
5749                                           Register var_size_in_bytes,
5750                                           int con_size_in_bytes,
5751                                           Register t1) {
5752   if (!thread->is_valid()) {
5753 #ifdef _LP64
5754     thread = r15_thread;
5755 #else
5756     assert(t1->is_valid(), "need temp reg");
5757     thread = t1;
5758     get_thread(thread);
5759 #endif
5760   }
5761 
5762 #ifdef _LP64
5763   if (var_size_in_bytes->is_valid()) {
5764     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5765   } else {
5766     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5767   }
5768 #else
5769   if (var_size_in_bytes->is_valid()) {
5770     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5771   } else {
5772     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5773   }
5774   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5775 #endif
5776 }
5777 
5778 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5779   pusha();
5780 
5781   // if we are coming from c1, xmm registers may be live
5782   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5783   if (UseAVX > 2) {
5784     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5785   }
5786 
5787   if (UseSSE == 1)  {
5788     subptr(rsp, sizeof(jdouble)*8);
5789     for (int n = 0; n < 8; n++) {
5790       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5791     }
5792   } else if (UseSSE >= 2)  {
5793     if (UseAVX > 2) {
5794       push(rbx);
5795       movl(rbx, 0xffff);
5796       kmovwl(k1, rbx);
5797       pop(rbx);
5798     }
5799 #ifdef COMPILER2
5800     if (MaxVectorSize > 16) {
5801       if(UseAVX > 2) {
5802         // Save upper half of ZMM registers
5803         subptr(rsp, 32*num_xmm_regs);
5804         for (int n = 0; n < num_xmm_regs; n++) {
5805           vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
5806         }
5807       }
5808       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5809       // Save upper half of YMM registers
5810       subptr(rsp, 16*num_xmm_regs);
5811       for (int n = 0; n < num_xmm_regs; n++) {
5812         vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
5813       }
5814     }
5815 #endif
5816     // Save whole 128bit (16 bytes) XMM registers
5817     subptr(rsp, 16*num_xmm_regs);
5818 #ifdef _LP64
5819     if (VM_Version::supports_evex()) {
5820       for (int n = 0; n < num_xmm_regs; n++) {
5821         vextractf32x4h(Address(rsp, n*16), as_XMMRegister(n), 0);
5822       }
5823     } else {
5824       for (int n = 0; n < num_xmm_regs; n++) {
5825         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5826       }
5827     }
5828 #else
5829     for (int n = 0; n < num_xmm_regs; n++) {
5830       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5831     }
5832 #endif
5833   }
5834 
5835   // Preserve registers across runtime call
5836   int incoming_argument_and_return_value_offset = -1;
5837   if (num_fpu_regs_in_use > 1) {
5838     // Must preserve all other FPU regs (could alternatively convert
5839     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5840     // FPU state, but can not trust C compiler)
5841     NEEDS_CLEANUP;
5842     // NOTE that in this case we also push the incoming argument(s) to
5843     // the stack and restore it later; we also use this stack slot to
5844     // hold the return value from dsin, dcos etc.
5845     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5846       subptr(rsp, sizeof(jdouble));
5847       fstp_d(Address(rsp, 0));
5848     }
5849     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5850     for (int i = nb_args-1; i >= 0; i--) {
5851       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5852     }
5853   }
5854 
5855   subptr(rsp, nb_args*sizeof(jdouble));
5856   for (int i = 0; i < nb_args; i++) {
5857     fstp_d(Address(rsp, i*sizeof(jdouble)));
5858   }
5859 
5860 #ifdef _LP64
5861   if (nb_args > 0) {
5862     movdbl(xmm0, Address(rsp, 0));
5863   }
5864   if (nb_args > 1) {
5865     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5866   }
5867   assert(nb_args <= 2, "unsupported number of args");
5868 #endif // _LP64
5869 
5870   // NOTE: we must not use call_VM_leaf here because that requires a
5871   // complete interpreter frame in debug mode -- same bug as 4387334
5872   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5873   // do proper 64bit abi
5874 
5875   NEEDS_CLEANUP;
5876   // Need to add stack banging before this runtime call if it needs to
5877   // be taken; however, there is no generic stack banging routine at
5878   // the MacroAssembler level
5879 
5880   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5881 
5882 #ifdef _LP64
5883   movsd(Address(rsp, 0), xmm0);
5884   fld_d(Address(rsp, 0));
5885 #endif // _LP64
5886   addptr(rsp, sizeof(jdouble)*nb_args);
5887   if (num_fpu_regs_in_use > 1) {
5888     // Must save return value to stack and then restore entire FPU
5889     // stack except incoming arguments
5890     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5891     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5892       fld_d(Address(rsp, 0));
5893       addptr(rsp, sizeof(jdouble));
5894     }
5895     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5896     addptr(rsp, sizeof(jdouble)*nb_args);
5897   }
5898 
5899   if (UseSSE == 1)  {
5900     for (int n = 0; n < 8; n++) {
5901       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5902     }
5903     addptr(rsp, sizeof(jdouble)*8);
5904   } else if (UseSSE >= 2)  {
5905     // Restore whole 128bit (16 bytes) XMM registers
5906 #ifdef _LP64
5907   if (VM_Version::supports_evex()) {
5908     for (int n = 0; n < num_xmm_regs; n++) {
5909       vinsertf32x4h(as_XMMRegister(n), Address(rsp, n*16), 0);
5910     }
5911   } else {
5912     for (int n = 0; n < num_xmm_regs; n++) {
5913       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5914     }
5915   }
5916 #else
5917   for (int n = 0; n < num_xmm_regs; n++) {
5918     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5919   }
5920 #endif
5921     addptr(rsp, 16*num_xmm_regs);
5922 
5923 #ifdef COMPILER2
5924     if (MaxVectorSize > 16) {
5925       // Restore upper half of YMM registers.
5926       for (int n = 0; n < num_xmm_regs; n++) {
5927         vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
5928       }
5929       addptr(rsp, 16*num_xmm_regs);
5930       if(UseAVX > 2) {
5931         for (int n = 0; n < num_xmm_regs; n++) {
5932           vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
5933         }
5934         addptr(rsp, 32*num_xmm_regs);
5935       }
5936     }
5937 #endif
5938   }
5939   popa();
5940 }
5941 
5942 static const double     pi_4 =  0.7853981633974483;
5943 
5944 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5945   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5946   // was attempted in this code; unfortunately it appears that the
5947   // switch to 80-bit precision and back causes this to be
5948   // unprofitable compared with simply performing a runtime call if
5949   // the argument is out of the (-pi/4, pi/4) range.
5950 
5951   Register tmp = noreg;
5952   if (!VM_Version::supports_cmov()) {
5953     // fcmp needs a temporary so preserve rbx,
5954     tmp = rbx;
5955     push(tmp);
5956   }
5957 
5958   Label slow_case, done;
5959   if (trig == 't') {
5960     ExternalAddress pi4_adr = (address)&pi_4;
5961     if (reachable(pi4_adr)) {
5962       // x ?<= pi/4
5963       fld_d(pi4_adr);
5964       fld_s(1);                // Stack:  X  PI/4  X
5965       fabs();                  // Stack: |X| PI/4  X
5966       fcmp(tmp);
5967       jcc(Assembler::above, slow_case);
5968 
5969       // fastest case: -pi/4 <= x <= pi/4
5970       ftan();
5971 
5972       jmp(done);
5973     }
5974   }
5975   // slow case: runtime call
5976   bind(slow_case);
5977 
5978   switch(trig) {
5979   case 's':
5980     {
5981       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
5982     }
5983     break;
5984   case 'c':
5985     {
5986       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
5987     }
5988     break;
5989   case 't':
5990     {
5991       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
5992     }
5993     break;
5994   default:
5995     assert(false, "bad intrinsic");
5996     break;
5997   }
5998 
5999   // Come here with result in F-TOS
6000   bind(done);
6001 
6002   if (tmp != noreg) {
6003     pop(tmp);
6004   }
6005 }
6006 
6007 
6008 // Look up the method for a megamorphic invokeinterface call.
6009 // The target method is determined by <intf_klass, itable_index>.
6010 // The receiver klass is in recv_klass.
6011 // On success, the result will be in method_result, and execution falls through.
6012 // On failure, execution transfers to the given label.
6013 void MacroAssembler::lookup_interface_method(Register recv_klass,
6014                                              Register intf_klass,
6015                                              RegisterOrConstant itable_index,
6016                                              Register method_result,
6017                                              Register scan_temp,
6018                                              Label& L_no_such_interface) {
6019   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
6020   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
6021          "caller must use same register for non-constant itable index as for method");
6022 
6023   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
6024   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
6025   int itentry_off = itableMethodEntry::method_offset_in_bytes();
6026   int scan_step   = itableOffsetEntry::size() * wordSize;
6027   int vte_size    = vtableEntry::size() * wordSize;
6028   Address::ScaleFactor times_vte_scale = Address::times_ptr;
6029   assert(vte_size == wordSize, "else adjust times_vte_scale");
6030 
6031   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
6032 
6033   // %%% Could store the aligned, prescaled offset in the klassoop.
6034   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
6035   if (HeapWordsPerLong > 1) {
6036     // Round up to align_object_offset boundary
6037     // see code for InstanceKlass::start_of_itable!
6038     round_to(scan_temp, BytesPerLong);
6039   }
6040 
6041   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
6042   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
6043   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
6044 
6045   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
6046   //   if (scan->interface() == intf) {
6047   //     result = (klass + scan->offset() + itable_index);
6048   //   }
6049   // }
6050   Label search, found_method;
6051 
6052   for (int peel = 1; peel >= 0; peel--) {
6053     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
6054     cmpptr(intf_klass, method_result);
6055 
6056     if (peel) {
6057       jccb(Assembler::equal, found_method);
6058     } else {
6059       jccb(Assembler::notEqual, search);
6060       // (invert the test to fall through to found_method...)
6061     }
6062 
6063     if (!peel)  break;
6064 
6065     bind(search);
6066 
6067     // Check that the previous entry is non-null.  A null entry means that
6068     // the receiver class doesn't implement the interface, and wasn't the
6069     // same as when the caller was compiled.
6070     testptr(method_result, method_result);
6071     jcc(Assembler::zero, L_no_such_interface);
6072     addptr(scan_temp, scan_step);
6073   }
6074 
6075   bind(found_method);
6076 
6077   // Got a hit.
6078   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
6079   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
6080 }
6081 
6082 
6083 // virtual method calling
6084 void MacroAssembler::lookup_virtual_method(Register recv_klass,
6085                                            RegisterOrConstant vtable_index,
6086                                            Register method_result) {
6087   const int base = InstanceKlass::vtable_start_offset() * wordSize;
6088   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
6089   Address vtable_entry_addr(recv_klass,
6090                             vtable_index, Address::times_ptr,
6091                             base + vtableEntry::method_offset_in_bytes());
6092   movptr(method_result, vtable_entry_addr);
6093 }
6094 
6095 
6096 void MacroAssembler::check_klass_subtype(Register sub_klass,
6097                            Register super_klass,
6098                            Register temp_reg,
6099                            Label& L_success) {
6100   Label L_failure;
6101   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
6102   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
6103   bind(L_failure);
6104 }
6105 
6106 
6107 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
6108                                                    Register super_klass,
6109                                                    Register temp_reg,
6110                                                    Label* L_success,
6111                                                    Label* L_failure,
6112                                                    Label* L_slow_path,
6113                                         RegisterOrConstant super_check_offset) {
6114   assert_different_registers(sub_klass, super_klass, temp_reg);
6115   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
6116   if (super_check_offset.is_register()) {
6117     assert_different_registers(sub_klass, super_klass,
6118                                super_check_offset.as_register());
6119   } else if (must_load_sco) {
6120     assert(temp_reg != noreg, "supply either a temp or a register offset");
6121   }
6122 
6123   Label L_fallthrough;
6124   int label_nulls = 0;
6125   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6126   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6127   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
6128   assert(label_nulls <= 1, "at most one NULL in the batch");
6129 
6130   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6131   int sco_offset = in_bytes(Klass::super_check_offset_offset());
6132   Address super_check_offset_addr(super_klass, sco_offset);
6133 
6134   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6135   // range of a jccb.  If this routine grows larger, reconsider at
6136   // least some of these.
6137 #define local_jcc(assembler_cond, label)                                \
6138   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6139   else                             jcc( assembler_cond, label) /*omit semi*/
6140 
6141   // Hacked jmp, which may only be used just before L_fallthrough.
6142 #define final_jmp(label)                                                \
6143   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6144   else                            jmp(label)                /*omit semi*/
6145 
6146   // If the pointers are equal, we are done (e.g., String[] elements).
6147   // This self-check enables sharing of secondary supertype arrays among
6148   // non-primary types such as array-of-interface.  Otherwise, each such
6149   // type would need its own customized SSA.
6150   // We move this check to the front of the fast path because many
6151   // type checks are in fact trivially successful in this manner,
6152   // so we get a nicely predicted branch right at the start of the check.
6153   cmpptr(sub_klass, super_klass);
6154   local_jcc(Assembler::equal, *L_success);
6155 
6156   // Check the supertype display:
6157   if (must_load_sco) {
6158     // Positive movl does right thing on LP64.
6159     movl(temp_reg, super_check_offset_addr);
6160     super_check_offset = RegisterOrConstant(temp_reg);
6161   }
6162   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6163   cmpptr(super_klass, super_check_addr); // load displayed supertype
6164 
6165   // This check has worked decisively for primary supers.
6166   // Secondary supers are sought in the super_cache ('super_cache_addr').
6167   // (Secondary supers are interfaces and very deeply nested subtypes.)
6168   // This works in the same check above because of a tricky aliasing
6169   // between the super_cache and the primary super display elements.
6170   // (The 'super_check_addr' can address either, as the case requires.)
6171   // Note that the cache is updated below if it does not help us find
6172   // what we need immediately.
6173   // So if it was a primary super, we can just fail immediately.
6174   // Otherwise, it's the slow path for us (no success at this point).
6175 
6176   if (super_check_offset.is_register()) {
6177     local_jcc(Assembler::equal, *L_success);
6178     cmpl(super_check_offset.as_register(), sc_offset);
6179     if (L_failure == &L_fallthrough) {
6180       local_jcc(Assembler::equal, *L_slow_path);
6181     } else {
6182       local_jcc(Assembler::notEqual, *L_failure);
6183       final_jmp(*L_slow_path);
6184     }
6185   } else if (super_check_offset.as_constant() == sc_offset) {
6186     // Need a slow path; fast failure is impossible.
6187     if (L_slow_path == &L_fallthrough) {
6188       local_jcc(Assembler::equal, *L_success);
6189     } else {
6190       local_jcc(Assembler::notEqual, *L_slow_path);
6191       final_jmp(*L_success);
6192     }
6193   } else {
6194     // No slow path; it's a fast decision.
6195     if (L_failure == &L_fallthrough) {
6196       local_jcc(Assembler::equal, *L_success);
6197     } else {
6198       local_jcc(Assembler::notEqual, *L_failure);
6199       final_jmp(*L_success);
6200     }
6201   }
6202 
6203   bind(L_fallthrough);
6204 
6205 #undef local_jcc
6206 #undef final_jmp
6207 }
6208 
6209 
6210 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6211                                                    Register super_klass,
6212                                                    Register temp_reg,
6213                                                    Register temp2_reg,
6214                                                    Label* L_success,
6215                                                    Label* L_failure,
6216                                                    bool set_cond_codes) {
6217   assert_different_registers(sub_klass, super_klass, temp_reg);
6218   if (temp2_reg != noreg)
6219     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6220 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6221 
6222   Label L_fallthrough;
6223   int label_nulls = 0;
6224   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6225   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6226   assert(label_nulls <= 1, "at most one NULL in the batch");
6227 
6228   // a couple of useful fields in sub_klass:
6229   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6230   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6231   Address secondary_supers_addr(sub_klass, ss_offset);
6232   Address super_cache_addr(     sub_klass, sc_offset);
6233 
6234   // Do a linear scan of the secondary super-klass chain.
6235   // This code is rarely used, so simplicity is a virtue here.
6236   // The repne_scan instruction uses fixed registers, which we must spill.
6237   // Don't worry too much about pre-existing connections with the input regs.
6238 
6239   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6240   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6241 
6242   // Get super_klass value into rax (even if it was in rdi or rcx).
6243   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6244   if (super_klass != rax || UseCompressedOops) {
6245     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6246     mov(rax, super_klass);
6247   }
6248   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6249   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6250 
6251 #ifndef PRODUCT
6252   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6253   ExternalAddress pst_counter_addr((address) pst_counter);
6254   NOT_LP64(  incrementl(pst_counter_addr) );
6255   LP64_ONLY( lea(rcx, pst_counter_addr) );
6256   LP64_ONLY( incrementl(Address(rcx, 0)) );
6257 #endif //PRODUCT
6258 
6259   // We will consult the secondary-super array.
6260   movptr(rdi, secondary_supers_addr);
6261   // Load the array length.  (Positive movl does right thing on LP64.)
6262   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6263   // Skip to start of data.
6264   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6265 
6266   // Scan RCX words at [RDI] for an occurrence of RAX.
6267   // Set NZ/Z based on last compare.
6268   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6269   // not change flags (only scas instruction which is repeated sets flags).
6270   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6271 
6272     testptr(rax,rax); // Set Z = 0
6273     repne_scan();
6274 
6275   // Unspill the temp. registers:
6276   if (pushed_rdi)  pop(rdi);
6277   if (pushed_rcx)  pop(rcx);
6278   if (pushed_rax)  pop(rax);
6279 
6280   if (set_cond_codes) {
6281     // Special hack for the AD files:  rdi is guaranteed non-zero.
6282     assert(!pushed_rdi, "rdi must be left non-NULL");
6283     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6284   }
6285 
6286   if (L_failure == &L_fallthrough)
6287         jccb(Assembler::notEqual, *L_failure);
6288   else  jcc(Assembler::notEqual, *L_failure);
6289 
6290   // Success.  Cache the super we found and proceed in triumph.
6291   movptr(super_cache_addr, super_klass);
6292 
6293   if (L_success != &L_fallthrough) {
6294     jmp(*L_success);
6295   }
6296 
6297 #undef IS_A_TEMP
6298 
6299   bind(L_fallthrough);
6300 }
6301 
6302 
6303 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6304   if (VM_Version::supports_cmov()) {
6305     cmovl(cc, dst, src);
6306   } else {
6307     Label L;
6308     jccb(negate_condition(cc), L);
6309     movl(dst, src);
6310     bind(L);
6311   }
6312 }
6313 
6314 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6315   if (VM_Version::supports_cmov()) {
6316     cmovl(cc, dst, src);
6317   } else {
6318     Label L;
6319     jccb(negate_condition(cc), L);
6320     movl(dst, src);
6321     bind(L);
6322   }
6323 }
6324 
6325 void MacroAssembler::verify_oop(Register reg, const char* s) {
6326   if (!VerifyOops) return;
6327 
6328   // Pass register number to verify_oop_subroutine
6329   const char* b = NULL;
6330   {
6331     ResourceMark rm;
6332     stringStream ss;
6333     ss.print("verify_oop: %s: %s", reg->name(), s);
6334     b = code_string(ss.as_string());
6335   }
6336   BLOCK_COMMENT("verify_oop {");
6337 #ifdef _LP64
6338   push(rscratch1);                    // save r10, trashed by movptr()
6339 #endif
6340   push(rax);                          // save rax,
6341   push(reg);                          // pass register argument
6342   ExternalAddress buffer((address) b);
6343   // avoid using pushptr, as it modifies scratch registers
6344   // and our contract is not to modify anything
6345   movptr(rax, buffer.addr());
6346   push(rax);
6347   // call indirectly to solve generation ordering problem
6348   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6349   call(rax);
6350   // Caller pops the arguments (oop, message) and restores rax, r10
6351   BLOCK_COMMENT("} verify_oop");
6352 }
6353 
6354 
6355 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6356                                                       Register tmp,
6357                                                       int offset) {
6358   intptr_t value = *delayed_value_addr;
6359   if (value != 0)
6360     return RegisterOrConstant(value + offset);
6361 
6362   // load indirectly to solve generation ordering problem
6363   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6364 
6365 #ifdef ASSERT
6366   { Label L;
6367     testptr(tmp, tmp);
6368     if (WizardMode) {
6369       const char* buf = NULL;
6370       {
6371         ResourceMark rm;
6372         stringStream ss;
6373         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6374         buf = code_string(ss.as_string());
6375       }
6376       jcc(Assembler::notZero, L);
6377       STOP(buf);
6378     } else {
6379       jccb(Assembler::notZero, L);
6380       hlt();
6381     }
6382     bind(L);
6383   }
6384 #endif
6385 
6386   if (offset != 0)
6387     addptr(tmp, offset);
6388 
6389   return RegisterOrConstant(tmp);
6390 }
6391 
6392 
6393 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6394                                          int extra_slot_offset) {
6395   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6396   int stackElementSize = Interpreter::stackElementSize;
6397   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6398 #ifdef ASSERT
6399   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6400   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6401 #endif
6402   Register             scale_reg    = noreg;
6403   Address::ScaleFactor scale_factor = Address::no_scale;
6404   if (arg_slot.is_constant()) {
6405     offset += arg_slot.as_constant() * stackElementSize;
6406   } else {
6407     scale_reg    = arg_slot.as_register();
6408     scale_factor = Address::times(stackElementSize);
6409   }
6410   offset += wordSize;           // return PC is on stack
6411   return Address(rsp, scale_reg, scale_factor, offset);
6412 }
6413 
6414 
6415 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6416   if (!VerifyOops) return;
6417 
6418   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6419   // Pass register number to verify_oop_subroutine
6420   const char* b = NULL;
6421   {
6422     ResourceMark rm;
6423     stringStream ss;
6424     ss.print("verify_oop_addr: %s", s);
6425     b = code_string(ss.as_string());
6426   }
6427 #ifdef _LP64
6428   push(rscratch1);                    // save r10, trashed by movptr()
6429 #endif
6430   push(rax);                          // save rax,
6431   // addr may contain rsp so we will have to adjust it based on the push
6432   // we just did (and on 64 bit we do two pushes)
6433   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6434   // stores rax into addr which is backwards of what was intended.
6435   if (addr.uses(rsp)) {
6436     lea(rax, addr);
6437     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6438   } else {
6439     pushptr(addr);
6440   }
6441 
6442   ExternalAddress buffer((address) b);
6443   // pass msg argument
6444   // avoid using pushptr, as it modifies scratch registers
6445   // and our contract is not to modify anything
6446   movptr(rax, buffer.addr());
6447   push(rax);
6448 
6449   // call indirectly to solve generation ordering problem
6450   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6451   call(rax);
6452   // Caller pops the arguments (addr, message) and restores rax, r10.
6453 }
6454 
6455 void MacroAssembler::verify_tlab() {
6456 #ifdef ASSERT
6457   if (UseTLAB && VerifyOops) {
6458     Label next, ok;
6459     Register t1 = rsi;
6460     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6461 
6462     push(t1);
6463     NOT_LP64(push(thread_reg));
6464     NOT_LP64(get_thread(thread_reg));
6465 
6466     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6467     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6468     jcc(Assembler::aboveEqual, next);
6469     STOP("assert(top >= start)");
6470     should_not_reach_here();
6471 
6472     bind(next);
6473     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6474     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6475     jcc(Assembler::aboveEqual, ok);
6476     STOP("assert(top <= end)");
6477     should_not_reach_here();
6478 
6479     bind(ok);
6480     NOT_LP64(pop(thread_reg));
6481     pop(t1);
6482   }
6483 #endif
6484 }
6485 
6486 class ControlWord {
6487  public:
6488   int32_t _value;
6489 
6490   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6491   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6492   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6493   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6494   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6495   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6496   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6497   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6498 
6499   void print() const {
6500     // rounding control
6501     const char* rc;
6502     switch (rounding_control()) {
6503       case 0: rc = "round near"; break;
6504       case 1: rc = "round down"; break;
6505       case 2: rc = "round up  "; break;
6506       case 3: rc = "chop      "; break;
6507     };
6508     // precision control
6509     const char* pc;
6510     switch (precision_control()) {
6511       case 0: pc = "24 bits "; break;
6512       case 1: pc = "reserved"; break;
6513       case 2: pc = "53 bits "; break;
6514       case 3: pc = "64 bits "; break;
6515     };
6516     // flags
6517     char f[9];
6518     f[0] = ' ';
6519     f[1] = ' ';
6520     f[2] = (precision   ()) ? 'P' : 'p';
6521     f[3] = (underflow   ()) ? 'U' : 'u';
6522     f[4] = (overflow    ()) ? 'O' : 'o';
6523     f[5] = (zero_divide ()) ? 'Z' : 'z';
6524     f[6] = (denormalized()) ? 'D' : 'd';
6525     f[7] = (invalid     ()) ? 'I' : 'i';
6526     f[8] = '\x0';
6527     // output
6528     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6529   }
6530 
6531 };
6532 
6533 class StatusWord {
6534  public:
6535   int32_t _value;
6536 
6537   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6538   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6539   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6540   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6541   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6542   int  top() const                     { return  (_value >> 11) & 7      ; }
6543   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6544   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6545   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6546   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6547   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6548   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6549   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6550   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6551 
6552   void print() const {
6553     // condition codes
6554     char c[5];
6555     c[0] = (C3()) ? '3' : '-';
6556     c[1] = (C2()) ? '2' : '-';
6557     c[2] = (C1()) ? '1' : '-';
6558     c[3] = (C0()) ? '0' : '-';
6559     c[4] = '\x0';
6560     // flags
6561     char f[9];
6562     f[0] = (error_status()) ? 'E' : '-';
6563     f[1] = (stack_fault ()) ? 'S' : '-';
6564     f[2] = (precision   ()) ? 'P' : '-';
6565     f[3] = (underflow   ()) ? 'U' : '-';
6566     f[4] = (overflow    ()) ? 'O' : '-';
6567     f[5] = (zero_divide ()) ? 'Z' : '-';
6568     f[6] = (denormalized()) ? 'D' : '-';
6569     f[7] = (invalid     ()) ? 'I' : '-';
6570     f[8] = '\x0';
6571     // output
6572     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6573   }
6574 
6575 };
6576 
6577 class TagWord {
6578  public:
6579   int32_t _value;
6580 
6581   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6582 
6583   void print() const {
6584     printf("%04x", _value & 0xFFFF);
6585   }
6586 
6587 };
6588 
6589 class FPU_Register {
6590  public:
6591   int32_t _m0;
6592   int32_t _m1;
6593   int16_t _ex;
6594 
6595   bool is_indefinite() const           {
6596     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6597   }
6598 
6599   void print() const {
6600     char  sign = (_ex < 0) ? '-' : '+';
6601     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6602     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6603   };
6604 
6605 };
6606 
6607 class FPU_State {
6608  public:
6609   enum {
6610     register_size       = 10,
6611     number_of_registers =  8,
6612     register_mask       =  7
6613   };
6614 
6615   ControlWord  _control_word;
6616   StatusWord   _status_word;
6617   TagWord      _tag_word;
6618   int32_t      _error_offset;
6619   int32_t      _error_selector;
6620   int32_t      _data_offset;
6621   int32_t      _data_selector;
6622   int8_t       _register[register_size * number_of_registers];
6623 
6624   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6625   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6626 
6627   const char* tag_as_string(int tag) const {
6628     switch (tag) {
6629       case 0: return "valid";
6630       case 1: return "zero";
6631       case 2: return "special";
6632       case 3: return "empty";
6633     }
6634     ShouldNotReachHere();
6635     return NULL;
6636   }
6637 
6638   void print() const {
6639     // print computation registers
6640     { int t = _status_word.top();
6641       for (int i = 0; i < number_of_registers; i++) {
6642         int j = (i - t) & register_mask;
6643         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6644         st(j)->print();
6645         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6646       }
6647     }
6648     printf("\n");
6649     // print control registers
6650     printf("ctrl = "); _control_word.print(); printf("\n");
6651     printf("stat = "); _status_word .print(); printf("\n");
6652     printf("tags = "); _tag_word    .print(); printf("\n");
6653   }
6654 
6655 };
6656 
6657 class Flag_Register {
6658  public:
6659   int32_t _value;
6660 
6661   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6662   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6663   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6664   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6665   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6666   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6667   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6668 
6669   void print() const {
6670     // flags
6671     char f[8];
6672     f[0] = (overflow       ()) ? 'O' : '-';
6673     f[1] = (direction      ()) ? 'D' : '-';
6674     f[2] = (sign           ()) ? 'S' : '-';
6675     f[3] = (zero           ()) ? 'Z' : '-';
6676     f[4] = (auxiliary_carry()) ? 'A' : '-';
6677     f[5] = (parity         ()) ? 'P' : '-';
6678     f[6] = (carry          ()) ? 'C' : '-';
6679     f[7] = '\x0';
6680     // output
6681     printf("%08x  flags = %s", _value, f);
6682   }
6683 
6684 };
6685 
6686 class IU_Register {
6687  public:
6688   int32_t _value;
6689 
6690   void print() const {
6691     printf("%08x  %11d", _value, _value);
6692   }
6693 
6694 };
6695 
6696 class IU_State {
6697  public:
6698   Flag_Register _eflags;
6699   IU_Register   _rdi;
6700   IU_Register   _rsi;
6701   IU_Register   _rbp;
6702   IU_Register   _rsp;
6703   IU_Register   _rbx;
6704   IU_Register   _rdx;
6705   IU_Register   _rcx;
6706   IU_Register   _rax;
6707 
6708   void print() const {
6709     // computation registers
6710     printf("rax,  = "); _rax.print(); printf("\n");
6711     printf("rbx,  = "); _rbx.print(); printf("\n");
6712     printf("rcx  = "); _rcx.print(); printf("\n");
6713     printf("rdx  = "); _rdx.print(); printf("\n");
6714     printf("rdi  = "); _rdi.print(); printf("\n");
6715     printf("rsi  = "); _rsi.print(); printf("\n");
6716     printf("rbp,  = "); _rbp.print(); printf("\n");
6717     printf("rsp  = "); _rsp.print(); printf("\n");
6718     printf("\n");
6719     // control registers
6720     printf("flgs = "); _eflags.print(); printf("\n");
6721   }
6722 };
6723 
6724 
6725 class CPU_State {
6726  public:
6727   FPU_State _fpu_state;
6728   IU_State  _iu_state;
6729 
6730   void print() const {
6731     printf("--------------------------------------------------\n");
6732     _iu_state .print();
6733     printf("\n");
6734     _fpu_state.print();
6735     printf("--------------------------------------------------\n");
6736   }
6737 
6738 };
6739 
6740 
6741 static void _print_CPU_state(CPU_State* state) {
6742   state->print();
6743 };
6744 
6745 
6746 void MacroAssembler::print_CPU_state() {
6747   push_CPU_state();
6748   push(rsp);                // pass CPU state
6749   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6750   addptr(rsp, wordSize);       // discard argument
6751   pop_CPU_state();
6752 }
6753 
6754 
6755 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6756   static int counter = 0;
6757   FPU_State* fs = &state->_fpu_state;
6758   counter++;
6759   // For leaf calls, only verify that the top few elements remain empty.
6760   // We only need 1 empty at the top for C2 code.
6761   if( stack_depth < 0 ) {
6762     if( fs->tag_for_st(7) != 3 ) {
6763       printf("FPR7 not empty\n");
6764       state->print();
6765       assert(false, "error");
6766       return false;
6767     }
6768     return true;                // All other stack states do not matter
6769   }
6770 
6771   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6772          "bad FPU control word");
6773 
6774   // compute stack depth
6775   int i = 0;
6776   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6777   int d = i;
6778   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6779   // verify findings
6780   if (i != FPU_State::number_of_registers) {
6781     // stack not contiguous
6782     printf("%s: stack not contiguous at ST%d\n", s, i);
6783     state->print();
6784     assert(false, "error");
6785     return false;
6786   }
6787   // check if computed stack depth corresponds to expected stack depth
6788   if (stack_depth < 0) {
6789     // expected stack depth is -stack_depth or less
6790     if (d > -stack_depth) {
6791       // too many elements on the stack
6792       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6793       state->print();
6794       assert(false, "error");
6795       return false;
6796     }
6797   } else {
6798     // expected stack depth is stack_depth
6799     if (d != stack_depth) {
6800       // wrong stack depth
6801       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6802       state->print();
6803       assert(false, "error");
6804       return false;
6805     }
6806   }
6807   // everything is cool
6808   return true;
6809 }
6810 
6811 
6812 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6813   if (!VerifyFPU) return;
6814   push_CPU_state();
6815   push(rsp);                // pass CPU state
6816   ExternalAddress msg((address) s);
6817   // pass message string s
6818   pushptr(msg.addr());
6819   push(stack_depth);        // pass stack depth
6820   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6821   addptr(rsp, 3 * wordSize);   // discard arguments
6822   // check for error
6823   { Label L;
6824     testl(rax, rax);
6825     jcc(Assembler::notZero, L);
6826     int3();                  // break if error condition
6827     bind(L);
6828   }
6829   pop_CPU_state();
6830 }
6831 
6832 void MacroAssembler::restore_cpu_control_state_after_jni() {
6833   // Either restore the MXCSR register after returning from the JNI Call
6834   // or verify that it wasn't changed (with -Xcheck:jni flag).
6835   if (VM_Version::supports_sse()) {
6836     if (RestoreMXCSROnJNICalls) {
6837       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6838     } else if (CheckJNICalls) {
6839       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6840     }
6841   }
6842   if (VM_Version::supports_avx()) {
6843     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6844     vzeroupper();
6845   }
6846 
6847 #ifndef _LP64
6848   // Either restore the x87 floating pointer control word after returning
6849   // from the JNI call or verify that it wasn't changed.
6850   if (CheckJNICalls) {
6851     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6852   }
6853 #endif // _LP64
6854 }
6855 
6856 
6857 void MacroAssembler::load_klass(Register dst, Register src) {
6858 #ifdef _LP64
6859   if (UseCompressedClassPointers) {
6860     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6861     decode_klass_not_null(dst);
6862   } else
6863 #endif
6864     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6865 }
6866 
6867 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6868   load_klass(dst, src);
6869   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6870 }
6871 
6872 void MacroAssembler::store_klass(Register dst, Register src) {
6873 #ifdef _LP64
6874   if (UseCompressedClassPointers) {
6875     encode_klass_not_null(src);
6876     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6877   } else
6878 #endif
6879     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6880 }
6881 
6882 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6883 #ifdef _LP64
6884   // FIXME: Must change all places where we try to load the klass.
6885   if (UseCompressedOops) {
6886     movl(dst, src);
6887     decode_heap_oop(dst);
6888   } else
6889 #endif
6890     movptr(dst, src);
6891 }
6892 
6893 // Doesn't do verfication, generates fixed size code
6894 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6895 #ifdef _LP64
6896   if (UseCompressedOops) {
6897     movl(dst, src);
6898     decode_heap_oop_not_null(dst);
6899   } else
6900 #endif
6901     movptr(dst, src);
6902 }
6903 
6904 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6905 #ifdef _LP64
6906   if (UseCompressedOops) {
6907     assert(!dst.uses(src), "not enough registers");
6908     encode_heap_oop(src);
6909     movl(dst, src);
6910   } else
6911 #endif
6912     movptr(dst, src);
6913 }
6914 
6915 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6916   assert_different_registers(src1, tmp);
6917 #ifdef _LP64
6918   if (UseCompressedOops) {
6919     bool did_push = false;
6920     if (tmp == noreg) {
6921       tmp = rax;
6922       push(tmp);
6923       did_push = true;
6924       assert(!src2.uses(rsp), "can't push");
6925     }
6926     load_heap_oop(tmp, src2);
6927     cmpptr(src1, tmp);
6928     if (did_push)  pop(tmp);
6929   } else
6930 #endif
6931     cmpptr(src1, src2);
6932 }
6933 
6934 // Used for storing NULLs.
6935 void MacroAssembler::store_heap_oop_null(Address dst) {
6936 #ifdef _LP64
6937   if (UseCompressedOops) {
6938     movl(dst, (int32_t)NULL_WORD);
6939   } else {
6940     movslq(dst, (int32_t)NULL_WORD);
6941   }
6942 #else
6943   movl(dst, (int32_t)NULL_WORD);
6944 #endif
6945 }
6946 
6947 #ifdef _LP64
6948 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6949   if (UseCompressedClassPointers) {
6950     // Store to klass gap in destination
6951     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6952   }
6953 }
6954 
6955 #ifdef ASSERT
6956 void MacroAssembler::verify_heapbase(const char* msg) {
6957   assert (UseCompressedOops, "should be compressed");
6958   assert (Universe::heap() != NULL, "java heap should be initialized");
6959   if (CheckCompressedOops) {
6960     Label ok;
6961     push(rscratch1); // cmpptr trashes rscratch1
6962     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6963     jcc(Assembler::equal, ok);
6964     STOP(msg);
6965     bind(ok);
6966     pop(rscratch1);
6967   }
6968 }
6969 #endif
6970 
6971 // Algorithm must match oop.inline.hpp encode_heap_oop.
6972 void MacroAssembler::encode_heap_oop(Register r) {
6973 #ifdef ASSERT
6974   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6975 #endif
6976   verify_oop(r, "broken oop in encode_heap_oop");
6977   if (Universe::narrow_oop_base() == NULL) {
6978     if (Universe::narrow_oop_shift() != 0) {
6979       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6980       shrq(r, LogMinObjAlignmentInBytes);
6981     }
6982     return;
6983   }
6984   testq(r, r);
6985   cmovq(Assembler::equal, r, r12_heapbase);
6986   subq(r, r12_heapbase);
6987   shrq(r, LogMinObjAlignmentInBytes);
6988 }
6989 
6990 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6991 #ifdef ASSERT
6992   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6993   if (CheckCompressedOops) {
6994     Label ok;
6995     testq(r, r);
6996     jcc(Assembler::notEqual, ok);
6997     STOP("null oop passed to encode_heap_oop_not_null");
6998     bind(ok);
6999   }
7000 #endif
7001   verify_oop(r, "broken oop in encode_heap_oop_not_null");
7002   if (Universe::narrow_oop_base() != NULL) {
7003     subq(r, r12_heapbase);
7004   }
7005   if (Universe::narrow_oop_shift() != 0) {
7006     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7007     shrq(r, LogMinObjAlignmentInBytes);
7008   }
7009 }
7010 
7011 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
7012 #ifdef ASSERT
7013   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
7014   if (CheckCompressedOops) {
7015     Label ok;
7016     testq(src, src);
7017     jcc(Assembler::notEqual, ok);
7018     STOP("null oop passed to encode_heap_oop_not_null2");
7019     bind(ok);
7020   }
7021 #endif
7022   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
7023   if (dst != src) {
7024     movq(dst, src);
7025   }
7026   if (Universe::narrow_oop_base() != NULL) {
7027     subq(dst, r12_heapbase);
7028   }
7029   if (Universe::narrow_oop_shift() != 0) {
7030     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7031     shrq(dst, LogMinObjAlignmentInBytes);
7032   }
7033 }
7034 
7035 void  MacroAssembler::decode_heap_oop(Register r) {
7036 #ifdef ASSERT
7037   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
7038 #endif
7039   if (Universe::narrow_oop_base() == NULL) {
7040     if (Universe::narrow_oop_shift() != 0) {
7041       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7042       shlq(r, LogMinObjAlignmentInBytes);
7043     }
7044   } else {
7045     Label done;
7046     shlq(r, LogMinObjAlignmentInBytes);
7047     jccb(Assembler::equal, done);
7048     addq(r, r12_heapbase);
7049     bind(done);
7050   }
7051   verify_oop(r, "broken oop in decode_heap_oop");
7052 }
7053 
7054 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
7055   // Note: it will change flags
7056   assert (UseCompressedOops, "should only be used for compressed headers");
7057   assert (Universe::heap() != NULL, "java heap should be initialized");
7058   // Cannot assert, unverified entry point counts instructions (see .ad file)
7059   // vtableStubs also counts instructions in pd_code_size_limit.
7060   // Also do not verify_oop as this is called by verify_oop.
7061   if (Universe::narrow_oop_shift() != 0) {
7062     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7063     shlq(r, LogMinObjAlignmentInBytes);
7064     if (Universe::narrow_oop_base() != NULL) {
7065       addq(r, r12_heapbase);
7066     }
7067   } else {
7068     assert (Universe::narrow_oop_base() == NULL, "sanity");
7069   }
7070 }
7071 
7072 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
7073   // Note: it will change flags
7074   assert (UseCompressedOops, "should only be used for compressed headers");
7075   assert (Universe::heap() != NULL, "java heap should be initialized");
7076   // Cannot assert, unverified entry point counts instructions (see .ad file)
7077   // vtableStubs also counts instructions in pd_code_size_limit.
7078   // Also do not verify_oop as this is called by verify_oop.
7079   if (Universe::narrow_oop_shift() != 0) {
7080     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
7081     if (LogMinObjAlignmentInBytes == Address::times_8) {
7082       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
7083     } else {
7084       if (dst != src) {
7085         movq(dst, src);
7086       }
7087       shlq(dst, LogMinObjAlignmentInBytes);
7088       if (Universe::narrow_oop_base() != NULL) {
7089         addq(dst, r12_heapbase);
7090       }
7091     }
7092   } else {
7093     assert (Universe::narrow_oop_base() == NULL, "sanity");
7094     if (dst != src) {
7095       movq(dst, src);
7096     }
7097   }
7098 }
7099 
7100 void MacroAssembler::encode_klass_not_null(Register r) {
7101   if (Universe::narrow_klass_base() != NULL) {
7102     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7103     assert(r != r12_heapbase, "Encoding a klass in r12");
7104     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7105     subq(r, r12_heapbase);
7106   }
7107   if (Universe::narrow_klass_shift() != 0) {
7108     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7109     shrq(r, LogKlassAlignmentInBytes);
7110   }
7111   if (Universe::narrow_klass_base() != NULL) {
7112     reinit_heapbase();
7113   }
7114 }
7115 
7116 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7117   if (dst == src) {
7118     encode_klass_not_null(src);
7119   } else {
7120     if (Universe::narrow_klass_base() != NULL) {
7121       mov64(dst, (int64_t)Universe::narrow_klass_base());
7122       negq(dst);
7123       addq(dst, src);
7124     } else {
7125       movptr(dst, src);
7126     }
7127     if (Universe::narrow_klass_shift() != 0) {
7128       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7129       shrq(dst, LogKlassAlignmentInBytes);
7130     }
7131   }
7132 }
7133 
7134 // Function instr_size_for_decode_klass_not_null() counts the instructions
7135 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7136 // when (Universe::heap() != NULL).  Hence, if the instructions they
7137 // generate change, then this method needs to be updated.
7138 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7139   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7140   if (Universe::narrow_klass_base() != NULL) {
7141     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7142     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7143   } else {
7144     // longest load decode klass function, mov64, leaq
7145     return 16;
7146   }
7147 }
7148 
7149 // !!! If the instructions that get generated here change then function
7150 // instr_size_for_decode_klass_not_null() needs to get updated.
7151 void  MacroAssembler::decode_klass_not_null(Register r) {
7152   // Note: it will change flags
7153   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7154   assert(r != r12_heapbase, "Decoding a klass in r12");
7155   // Cannot assert, unverified entry point counts instructions (see .ad file)
7156   // vtableStubs also counts instructions in pd_code_size_limit.
7157   // Also do not verify_oop as this is called by verify_oop.
7158   if (Universe::narrow_klass_shift() != 0) {
7159     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7160     shlq(r, LogKlassAlignmentInBytes);
7161   }
7162   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7163   if (Universe::narrow_klass_base() != NULL) {
7164     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7165     addq(r, r12_heapbase);
7166     reinit_heapbase();
7167   }
7168 }
7169 
7170 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7171   // Note: it will change flags
7172   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7173   if (dst == src) {
7174     decode_klass_not_null(dst);
7175   } else {
7176     // Cannot assert, unverified entry point counts instructions (see .ad file)
7177     // vtableStubs also counts instructions in pd_code_size_limit.
7178     // Also do not verify_oop as this is called by verify_oop.
7179     mov64(dst, (int64_t)Universe::narrow_klass_base());
7180     if (Universe::narrow_klass_shift() != 0) {
7181       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7182       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7183       leaq(dst, Address(dst, src, Address::times_8, 0));
7184     } else {
7185       addq(dst, src);
7186     }
7187   }
7188 }
7189 
7190 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7191   assert (UseCompressedOops, "should only be used for compressed headers");
7192   assert (Universe::heap() != NULL, "java heap should be initialized");
7193   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7194   int oop_index = oop_recorder()->find_index(obj);
7195   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7196   mov_narrow_oop(dst, oop_index, rspec);
7197 }
7198 
7199 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7200   assert (UseCompressedOops, "should only be used for compressed headers");
7201   assert (Universe::heap() != NULL, "java heap should be initialized");
7202   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7203   int oop_index = oop_recorder()->find_index(obj);
7204   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7205   mov_narrow_oop(dst, oop_index, rspec);
7206 }
7207 
7208 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7209   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7210   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7211   int klass_index = oop_recorder()->find_index(k);
7212   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7213   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7214 }
7215 
7216 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7217   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7218   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7219   int klass_index = oop_recorder()->find_index(k);
7220   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7221   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7222 }
7223 
7224 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7225   assert (UseCompressedOops, "should only be used for compressed headers");
7226   assert (Universe::heap() != NULL, "java heap should be initialized");
7227   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7228   int oop_index = oop_recorder()->find_index(obj);
7229   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7230   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7231 }
7232 
7233 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7234   assert (UseCompressedOops, "should only be used for compressed headers");
7235   assert (Universe::heap() != NULL, "java heap should be initialized");
7236   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7237   int oop_index = oop_recorder()->find_index(obj);
7238   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7239   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7240 }
7241 
7242 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7243   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7244   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7245   int klass_index = oop_recorder()->find_index(k);
7246   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7247   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7248 }
7249 
7250 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7251   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7252   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7253   int klass_index = oop_recorder()->find_index(k);
7254   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7255   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7256 }
7257 
7258 void MacroAssembler::reinit_heapbase() {
7259   if (UseCompressedOops || UseCompressedClassPointers) {
7260     if (Universe::heap() != NULL) {
7261       if (Universe::narrow_oop_base() == NULL) {
7262         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7263       } else {
7264         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7265       }
7266     } else {
7267       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7268     }
7269   }
7270 }
7271 
7272 #endif // _LP64
7273 
7274 
7275 // C2 compiled method's prolog code.
7276 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7277 
7278   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7279   // NativeJump::patch_verified_entry will be able to patch out the entry
7280   // code safely. The push to verify stack depth is ok at 5 bytes,
7281   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7282   // stack bang then we must use the 6 byte frame allocation even if
7283   // we have no frame. :-(
7284   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7285 
7286   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7287   // Remove word for return addr
7288   framesize -= wordSize;
7289   stack_bang_size -= wordSize;
7290 
7291   // Calls to C2R adapters often do not accept exceptional returns.
7292   // We require that their callers must bang for them.  But be careful, because
7293   // some VM calls (such as call site linkage) can use several kilobytes of
7294   // stack.  But the stack safety zone should account for that.
7295   // See bugs 4446381, 4468289, 4497237.
7296   if (stack_bang_size > 0) {
7297     generate_stack_overflow_check(stack_bang_size);
7298 
7299     // We always push rbp, so that on return to interpreter rbp, will be
7300     // restored correctly and we can correct the stack.
7301     push(rbp);
7302     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7303     if (PreserveFramePointer) {
7304       mov(rbp, rsp);
7305     }
7306     // Remove word for ebp
7307     framesize -= wordSize;
7308 
7309     // Create frame
7310     if (framesize) {
7311       subptr(rsp, framesize);
7312     }
7313   } else {
7314     // Create frame (force generation of a 4 byte immediate value)
7315     subptr_imm32(rsp, framesize);
7316 
7317     // Save RBP register now.
7318     framesize -= wordSize;
7319     movptr(Address(rsp, framesize), rbp);
7320     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7321     if (PreserveFramePointer) {
7322       movptr(rbp, rsp);
7323       if (framesize > 0) {
7324         addptr(rbp, framesize);
7325       }
7326     }
7327   }
7328 
7329   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7330     framesize -= wordSize;
7331     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7332   }
7333 
7334 #ifndef _LP64
7335   // If method sets FPU control word do it now
7336   if (fp_mode_24b) {
7337     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7338   }
7339   if (UseSSE >= 2 && VerifyFPU) {
7340     verify_FPU(0, "FPU stack must be clean on entry");
7341   }
7342 #endif
7343 
7344 #ifdef ASSERT
7345   if (VerifyStackAtCalls) {
7346     Label L;
7347     push(rax);
7348     mov(rax, rsp);
7349     andptr(rax, StackAlignmentInBytes-1);
7350     cmpptr(rax, StackAlignmentInBytes-wordSize);
7351     pop(rax);
7352     jcc(Assembler::equal, L);
7353     STOP("Stack is not properly aligned!");
7354     bind(L);
7355   }
7356 #endif
7357 
7358 }
7359 
7360 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
7361   // cnt - number of qwords (8-byte words).
7362   // base - start address, qword aligned.
7363   assert(base==rdi, "base register must be edi for rep stos");
7364   assert(tmp==rax,   "tmp register must be eax for rep stos");
7365   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7366 
7367   xorptr(tmp, tmp);
7368   if (UseFastStosb) {
7369     shlptr(cnt,3); // convert to number of bytes
7370     rep_stosb();
7371   } else {
7372     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
7373     rep_stos();
7374   }
7375 }
7376 
7377 #ifdef COMPILER2
7378 
7379 // IndexOf for constant substrings with size >= 8 chars
7380 // which don't need to be loaded through stack.
7381 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7382                                       Register cnt1, Register cnt2,
7383                                       int int_cnt2,  Register result,
7384                                       XMMRegister vec, Register tmp,
7385                                       int ae) {
7386   ShortBranchVerifier sbv(this);
7387   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7388   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7389   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7390 
7391   // This method uses the pcmpestri instruction with bound registers
7392   //   inputs:
7393   //     xmm - substring
7394   //     rax - substring length (elements count)
7395   //     mem - scanned string
7396   //     rdx - string length (elements count)
7397   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7398   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7399   //   outputs:
7400   //     rcx - matched index in string
7401   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7402   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7403   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7404   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7405   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7406 
7407   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7408         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7409         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7410 
7411   // Note, inline_string_indexOf() generates checks:
7412   // if (substr.count > string.count) return -1;
7413   // if (substr.count == 0) return 0;
7414   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7415 
7416   // Load substring.
7417   if (ae == StrIntrinsicNode::UL) {
7418     pmovzxbw(vec, Address(str2, 0));
7419   } else {
7420     movdqu(vec, Address(str2, 0));
7421   }
7422   movl(cnt2, int_cnt2);
7423   movptr(result, str1); // string addr
7424 
7425   if (int_cnt2 > stride) {
7426     jmpb(SCAN_TO_SUBSTR);
7427 
7428     // Reload substr for rescan, this code
7429     // is executed only for large substrings (> 8 chars)
7430     bind(RELOAD_SUBSTR);
7431     if (ae == StrIntrinsicNode::UL) {
7432       pmovzxbw(vec, Address(str2, 0));
7433     } else {
7434       movdqu(vec, Address(str2, 0));
7435     }
7436     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7437 
7438     bind(RELOAD_STR);
7439     // We came here after the beginning of the substring was
7440     // matched but the rest of it was not so we need to search
7441     // again. Start from the next element after the previous match.
7442 
7443     // cnt2 is number of substring reminding elements and
7444     // cnt1 is number of string reminding elements when cmp failed.
7445     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7446     subl(cnt1, cnt2);
7447     addl(cnt1, int_cnt2);
7448     movl(cnt2, int_cnt2); // Now restore cnt2
7449 
7450     decrementl(cnt1);     // Shift to next element
7451     cmpl(cnt1, cnt2);
7452     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7453 
7454     addptr(result, (1<<scale1));
7455 
7456   } // (int_cnt2 > 8)
7457 
7458   // Scan string for start of substr in 16-byte vectors
7459   bind(SCAN_TO_SUBSTR);
7460   pcmpestri(vec, Address(result, 0), mode);
7461   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7462   subl(cnt1, stride);
7463   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7464   cmpl(cnt1, cnt2);
7465   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7466   addptr(result, 16);
7467   jmpb(SCAN_TO_SUBSTR);
7468 
7469   // Found a potential substr
7470   bind(FOUND_CANDIDATE);
7471   // Matched whole vector if first element matched (tmp(rcx) == 0).
7472   if (int_cnt2 == stride) {
7473     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7474   } else { // int_cnt2 > 8
7475     jccb(Assembler::overflow, FOUND_SUBSTR);
7476   }
7477   // After pcmpestri tmp(rcx) contains matched element index
7478   // Compute start addr of substr
7479   lea(result, Address(result, tmp, scale1));
7480 
7481   // Make sure string is still long enough
7482   subl(cnt1, tmp);
7483   cmpl(cnt1, cnt2);
7484   if (int_cnt2 == stride) {
7485     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7486   } else { // int_cnt2 > 8
7487     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7488   }
7489   // Left less then substring.
7490 
7491   bind(RET_NOT_FOUND);
7492   movl(result, -1);
7493   jmpb(EXIT);
7494 
7495   if (int_cnt2 > stride) {
7496     // This code is optimized for the case when whole substring
7497     // is matched if its head is matched.
7498     bind(MATCH_SUBSTR_HEAD);
7499     pcmpestri(vec, Address(result, 0), mode);
7500     // Reload only string if does not match
7501     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7502 
7503     Label CONT_SCAN_SUBSTR;
7504     // Compare the rest of substring (> 8 chars).
7505     bind(FOUND_SUBSTR);
7506     // First 8 chars are already matched.
7507     negptr(cnt2);
7508     addptr(cnt2, stride);
7509 
7510     bind(SCAN_SUBSTR);
7511     subl(cnt1, stride);
7512     cmpl(cnt2, -stride); // Do not read beyond substring
7513     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7514     // Back-up strings to avoid reading beyond substring:
7515     // cnt1 = cnt1 - cnt2 + 8
7516     addl(cnt1, cnt2); // cnt2 is negative
7517     addl(cnt1, stride);
7518     movl(cnt2, stride); negptr(cnt2);
7519     bind(CONT_SCAN_SUBSTR);
7520     if (int_cnt2 < (int)G) {
7521       int tail_off1 = int_cnt2<<scale1;
7522       int tail_off2 = int_cnt2<<scale2;
7523       if (ae == StrIntrinsicNode::UL) {
7524         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7525       } else {
7526         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7527       }
7528       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7529     } else {
7530       // calculate index in register to avoid integer overflow (int_cnt2*2)
7531       movl(tmp, int_cnt2);
7532       addptr(tmp, cnt2);
7533       if (ae == StrIntrinsicNode::UL) {
7534         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7535       } else {
7536         movdqu(vec, Address(str2, tmp, scale2, 0));
7537       }
7538       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7539     }
7540     // Need to reload strings pointers if not matched whole vector
7541     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7542     addptr(cnt2, stride);
7543     jcc(Assembler::negative, SCAN_SUBSTR);
7544     // Fall through if found full substring
7545 
7546   } // (int_cnt2 > 8)
7547 
7548   bind(RET_FOUND);
7549   // Found result if we matched full small substring.
7550   // Compute substr offset
7551   subptr(result, str1);
7552   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7553     shrl(result, 1); // index
7554   }
7555   bind(EXIT);
7556 
7557 } // string_indexofC8
7558 
7559 // Small strings are loaded through stack if they cross page boundary.
7560 void MacroAssembler::string_indexof(Register str1, Register str2,
7561                                     Register cnt1, Register cnt2,
7562                                     int int_cnt2,  Register result,
7563                                     XMMRegister vec, Register tmp,
7564                                     int ae) {
7565   ShortBranchVerifier sbv(this);
7566   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7567   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7568   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7569 
7570   //
7571   // int_cnt2 is length of small (< 8 chars) constant substring
7572   // or (-1) for non constant substring in which case its length
7573   // is in cnt2 register.
7574   //
7575   // Note, inline_string_indexOf() generates checks:
7576   // if (substr.count > string.count) return -1;
7577   // if (substr.count == 0) return 0;
7578   //
7579   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7580   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7581   // This method uses the pcmpestri instruction with bound registers
7582   //   inputs:
7583   //     xmm - substring
7584   //     rax - substring length (elements count)
7585   //     mem - scanned string
7586   //     rdx - string length (elements count)
7587   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7588   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7589   //   outputs:
7590   //     rcx - matched index in string
7591   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7592   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7593   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7594   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7595 
7596   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7597         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7598         FOUND_CANDIDATE;
7599 
7600   { //========================================================
7601     // We don't know where these strings are located
7602     // and we can't read beyond them. Load them through stack.
7603     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7604 
7605     movptr(tmp, rsp); // save old SP
7606 
7607     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7608       if (int_cnt2 == (1>>scale2)) { // One byte
7609         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7610         load_unsigned_byte(result, Address(str2, 0));
7611         movdl(vec, result); // move 32 bits
7612       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7613         // Not enough header space in 32-bit VM: 12+3 = 15.
7614         movl(result, Address(str2, -1));
7615         shrl(result, 8);
7616         movdl(vec, result); // move 32 bits
7617       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7618         load_unsigned_short(result, Address(str2, 0));
7619         movdl(vec, result); // move 32 bits
7620       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7621         movdl(vec, Address(str2, 0)); // move 32 bits
7622       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7623         movq(vec, Address(str2, 0));  // move 64 bits
7624       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7625         // Array header size is 12 bytes in 32-bit VM
7626         // + 6 bytes for 3 chars == 18 bytes,
7627         // enough space to load vec and shift.
7628         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7629         if (ae == StrIntrinsicNode::UL) {
7630           int tail_off = int_cnt2-8;
7631           pmovzxbw(vec, Address(str2, tail_off));
7632           psrldq(vec, -2*tail_off);
7633         }
7634         else {
7635           int tail_off = int_cnt2*(1<<scale2);
7636           movdqu(vec, Address(str2, tail_off-16));
7637           psrldq(vec, 16-tail_off);
7638         }
7639       }
7640     } else { // not constant substring
7641       cmpl(cnt2, stride);
7642       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7643 
7644       // We can read beyond string if srt+16 does not cross page boundary
7645       // since heaps are aligned and mapped by pages.
7646       assert(os::vm_page_size() < (int)G, "default page should be small");
7647       movl(result, str2); // We need only low 32 bits
7648       andl(result, (os::vm_page_size()-1));
7649       cmpl(result, (os::vm_page_size()-16));
7650       jccb(Assembler::belowEqual, CHECK_STR);
7651 
7652       // Move small strings to stack to allow load 16 bytes into vec.
7653       subptr(rsp, 16);
7654       int stk_offset = wordSize-(1<<scale2);
7655       push(cnt2);
7656 
7657       bind(COPY_SUBSTR);
7658       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7659         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7660         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7661       } else if (ae == StrIntrinsicNode::UU) {
7662         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7663         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7664       }
7665       decrement(cnt2);
7666       jccb(Assembler::notZero, COPY_SUBSTR);
7667 
7668       pop(cnt2);
7669       movptr(str2, rsp);  // New substring address
7670     } // non constant
7671 
7672     bind(CHECK_STR);
7673     cmpl(cnt1, stride);
7674     jccb(Assembler::aboveEqual, BIG_STRINGS);
7675 
7676     // Check cross page boundary.
7677     movl(result, str1); // We need only low 32 bits
7678     andl(result, (os::vm_page_size()-1));
7679     cmpl(result, (os::vm_page_size()-16));
7680     jccb(Assembler::belowEqual, BIG_STRINGS);
7681 
7682     subptr(rsp, 16);
7683     int stk_offset = -(1<<scale1);
7684     if (int_cnt2 < 0) { // not constant
7685       push(cnt2);
7686       stk_offset += wordSize;
7687     }
7688     movl(cnt2, cnt1);
7689 
7690     bind(COPY_STR);
7691     if (ae == StrIntrinsicNode::LL) {
7692       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7693       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7694     } else {
7695       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7696       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7697     }
7698     decrement(cnt2);
7699     jccb(Assembler::notZero, COPY_STR);
7700 
7701     if (int_cnt2 < 0) { // not constant
7702       pop(cnt2);
7703     }
7704     movptr(str1, rsp);  // New string address
7705 
7706     bind(BIG_STRINGS);
7707     // Load substring.
7708     if (int_cnt2 < 0) { // -1
7709       if (ae == StrIntrinsicNode::UL) {
7710         pmovzxbw(vec, Address(str2, 0));
7711       } else {
7712         movdqu(vec, Address(str2, 0));
7713       }
7714       push(cnt2);       // substr count
7715       push(str2);       // substr addr
7716       push(str1);       // string addr
7717     } else {
7718       // Small (< 8 chars) constant substrings are loaded already.
7719       movl(cnt2, int_cnt2);
7720     }
7721     push(tmp);  // original SP
7722 
7723   } // Finished loading
7724 
7725   //========================================================
7726   // Start search
7727   //
7728 
7729   movptr(result, str1); // string addr
7730 
7731   if (int_cnt2  < 0) {  // Only for non constant substring
7732     jmpb(SCAN_TO_SUBSTR);
7733 
7734     // SP saved at sp+0
7735     // String saved at sp+1*wordSize
7736     // Substr saved at sp+2*wordSize
7737     // Substr count saved at sp+3*wordSize
7738 
7739     // Reload substr for rescan, this code
7740     // is executed only for large substrings (> 8 chars)
7741     bind(RELOAD_SUBSTR);
7742     movptr(str2, Address(rsp, 2*wordSize));
7743     movl(cnt2, Address(rsp, 3*wordSize));
7744     if (ae == StrIntrinsicNode::UL) {
7745       pmovzxbw(vec, Address(str2, 0));
7746     } else {
7747       movdqu(vec, Address(str2, 0));
7748     }
7749     // We came here after the beginning of the substring was
7750     // matched but the rest of it was not so we need to search
7751     // again. Start from the next element after the previous match.
7752     subptr(str1, result); // Restore counter
7753     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7754       shrl(str1, 1);
7755     }
7756     addl(cnt1, str1);
7757     decrementl(cnt1);   // Shift to next element
7758     cmpl(cnt1, cnt2);
7759     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7760 
7761     addptr(result, (1<<scale1));
7762   } // non constant
7763 
7764   // Scan string for start of substr in 16-byte vectors
7765   bind(SCAN_TO_SUBSTR);
7766   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7767   pcmpestri(vec, Address(result, 0), mode);
7768   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7769   subl(cnt1, stride);
7770   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7771   cmpl(cnt1, cnt2);
7772   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7773   addptr(result, 16);
7774 
7775   bind(ADJUST_STR);
7776   cmpl(cnt1, stride); // Do not read beyond string
7777   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7778   // Back-up string to avoid reading beyond string.
7779   lea(result, Address(result, cnt1, scale1, -16));
7780   movl(cnt1, stride);
7781   jmpb(SCAN_TO_SUBSTR);
7782 
7783   // Found a potential substr
7784   bind(FOUND_CANDIDATE);
7785   // After pcmpestri tmp(rcx) contains matched element index
7786 
7787   // Make sure string is still long enough
7788   subl(cnt1, tmp);
7789   cmpl(cnt1, cnt2);
7790   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7791   // Left less then substring.
7792 
7793   bind(RET_NOT_FOUND);
7794   movl(result, -1);
7795   jmpb(CLEANUP);
7796 
7797   bind(FOUND_SUBSTR);
7798   // Compute start addr of substr
7799   lea(result, Address(result, tmp, scale1));
7800   if (int_cnt2 > 0) { // Constant substring
7801     // Repeat search for small substring (< 8 chars)
7802     // from new point without reloading substring.
7803     // Have to check that we don't read beyond string.
7804     cmpl(tmp, stride-int_cnt2);
7805     jccb(Assembler::greater, ADJUST_STR);
7806     // Fall through if matched whole substring.
7807   } else { // non constant
7808     assert(int_cnt2 == -1, "should be != 0");
7809 
7810     addl(tmp, cnt2);
7811     // Found result if we matched whole substring.
7812     cmpl(tmp, stride);
7813     jccb(Assembler::lessEqual, RET_FOUND);
7814 
7815     // Repeat search for small substring (<= 8 chars)
7816     // from new point 'str1' without reloading substring.
7817     cmpl(cnt2, stride);
7818     // Have to check that we don't read beyond string.
7819     jccb(Assembler::lessEqual, ADJUST_STR);
7820 
7821     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7822     // Compare the rest of substring (> 8 chars).
7823     movptr(str1, result);
7824 
7825     cmpl(tmp, cnt2);
7826     // First 8 chars are already matched.
7827     jccb(Assembler::equal, CHECK_NEXT);
7828 
7829     bind(SCAN_SUBSTR);
7830     pcmpestri(vec, Address(str1, 0), mode);
7831     // Need to reload strings pointers if not matched whole vector
7832     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7833 
7834     bind(CHECK_NEXT);
7835     subl(cnt2, stride);
7836     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7837     addptr(str1, 16);
7838     if (ae == StrIntrinsicNode::UL) {
7839       addptr(str2, 8);
7840     } else {
7841       addptr(str2, 16);
7842     }
7843     subl(cnt1, stride);
7844     cmpl(cnt2, stride); // Do not read beyond substring
7845     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7846     // Back-up strings to avoid reading beyond substring.
7847 
7848     if (ae == StrIntrinsicNode::UL) {
7849       lea(str2, Address(str2, cnt2, scale2, -8));
7850       lea(str1, Address(str1, cnt2, scale1, -16));
7851     } else {
7852       lea(str2, Address(str2, cnt2, scale2, -16));
7853       lea(str1, Address(str1, cnt2, scale1, -16));
7854     }
7855     subl(cnt1, cnt2);
7856     movl(cnt2, stride);
7857     addl(cnt1, stride);
7858     bind(CONT_SCAN_SUBSTR);
7859     if (ae == StrIntrinsicNode::UL) {
7860       pmovzxbw(vec, Address(str2, 0));
7861     } else {
7862       movdqu(vec, Address(str2, 0));
7863     }
7864     jmpb(SCAN_SUBSTR);
7865 
7866     bind(RET_FOUND_LONG);
7867     movptr(str1, Address(rsp, wordSize));
7868   } // non constant
7869 
7870   bind(RET_FOUND);
7871   // Compute substr offset
7872   subptr(result, str1);
7873   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7874     shrl(result, 1); // index
7875   }
7876   bind(CLEANUP);
7877   pop(rsp); // restore SP
7878 
7879 } // string_indexof
7880 
7881 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7882                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7883   ShortBranchVerifier sbv(this);
7884   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7885   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7886 
7887   int stride = 8;
7888 
7889   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7890         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7891         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7892         FOUND_SEQ_CHAR, DONE_LABEL;
7893 
7894   movptr(result, str1);
7895   if (UseAVX >= 2) {
7896     cmpl(cnt1, stride);
7897     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7898     cmpl(cnt1, 2*stride);
7899     jccb(Assembler::less, SCAN_TO_8_CHAR_INIT);
7900     movdl(vec1, ch);
7901     vpbroadcastw(vec1, vec1);
7902     vpxor(vec2, vec2);
7903     movl(tmp, cnt1);
7904     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7905     andl(cnt1,0x0000000F);  //tail count (in chars)
7906 
7907     bind(SCAN_TO_16_CHAR_LOOP);
7908     vmovdqu(vec3, Address(result, 0));
7909     vpcmpeqw(vec3, vec3, vec1, 1);
7910     vptest(vec2, vec3);
7911     jcc(Assembler::carryClear, FOUND_CHAR);
7912     addptr(result, 32);
7913     subl(tmp, 2*stride);
7914     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7915     jmp(SCAN_TO_8_CHAR);
7916     bind(SCAN_TO_8_CHAR_INIT);
7917     movdl(vec1, ch);
7918     pshuflw(vec1, vec1, 0x00);
7919     pshufd(vec1, vec1, 0);
7920     pxor(vec2, vec2);
7921   }
7922   bind(SCAN_TO_8_CHAR);
7923   cmpl(cnt1, stride);
7924   if (UseAVX >= 2) {
7925     jccb(Assembler::less, SCAN_TO_CHAR);
7926   } else {
7927     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7928     movdl(vec1, ch);
7929     pshuflw(vec1, vec1, 0x00);
7930     pshufd(vec1, vec1, 0);
7931     pxor(vec2, vec2);
7932   }
7933   movl(tmp, cnt1);
7934   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7935   andl(cnt1,0x00000007);  //tail count (in chars)
7936 
7937   bind(SCAN_TO_8_CHAR_LOOP);
7938   movdqu(vec3, Address(result, 0));
7939   pcmpeqw(vec3, vec1);
7940   ptest(vec2, vec3);
7941   jcc(Assembler::carryClear, FOUND_CHAR);
7942   addptr(result, 16);
7943   subl(tmp, stride);
7944   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7945   bind(SCAN_TO_CHAR);
7946   testl(cnt1, cnt1);
7947   jcc(Assembler::zero, RET_NOT_FOUND);
7948   bind(SCAN_TO_CHAR_LOOP);
7949   load_unsigned_short(tmp, Address(result, 0));
7950   cmpl(ch, tmp);
7951   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7952   addptr(result, 2);
7953   subl(cnt1, 1);
7954   jccb(Assembler::zero, RET_NOT_FOUND);
7955   jmp(SCAN_TO_CHAR_LOOP);
7956 
7957   bind(RET_NOT_FOUND);
7958   movl(result, -1);
7959   jmpb(DONE_LABEL);
7960 
7961   bind(FOUND_CHAR);
7962   if (UseAVX >= 2) {
7963     vpmovmskb(tmp, vec3);
7964   } else {
7965     pmovmskb(tmp, vec3);
7966   }
7967   bsfl(ch, tmp);
7968   addl(result, ch);
7969 
7970   bind(FOUND_SEQ_CHAR);
7971   subptr(result, str1);
7972   shrl(result, 1);
7973 
7974   bind(DONE_LABEL);
7975 } // string_indexof_char
7976 
7977 // helper function for string_compare
7978 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7979                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7980                                         Address::ScaleFactor scale2, Register index, int ae) {
7981   if (ae == StrIntrinsicNode::LL) {
7982     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7983     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7984   } else if (ae == StrIntrinsicNode::UU) {
7985     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7986     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7987   } else {
7988     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7989     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7990   }
7991 }
7992 
7993 // Compare strings, used for char[] and byte[].
7994 void MacroAssembler::string_compare(Register str1, Register str2,
7995                                     Register cnt1, Register cnt2, Register result,
7996                                     XMMRegister vec1, int ae) {
7997   ShortBranchVerifier sbv(this);
7998   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7999   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
8000   Address::ScaleFactor scale, scale1, scale2;
8001 
8002   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
8003     shrl(cnt2, 1);
8004   }
8005   // Compute the minimum of the string lengths and the
8006   // difference of the string lengths (stack).
8007   // Do the conditional move stuff
8008   movl(result, cnt1);
8009   subl(cnt1, cnt2);
8010   push(cnt1);
8011   cmov32(Assembler::lessEqual, cnt2, result);
8012 
8013   // Is the minimum length zero?
8014   testl(cnt2, cnt2);
8015   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8016   if (ae == StrIntrinsicNode::LL) {
8017     // Load first bytes
8018     load_unsigned_byte(result, Address(str1, 0));
8019     load_unsigned_byte(cnt1, Address(str2, 0));
8020   } else if (ae == StrIntrinsicNode::UU) {
8021     // Load first characters
8022     load_unsigned_short(result, Address(str1, 0));
8023     load_unsigned_short(cnt1, Address(str2, 0));
8024   } else {
8025     load_unsigned_byte(result, Address(str1, 0));
8026     load_unsigned_short(cnt1, Address(str2, 0));
8027   }
8028   subl(result, cnt1);
8029   jcc(Assembler::notZero,  POP_LABEL);
8030 
8031   if (ae == StrIntrinsicNode::UU) {
8032     // Divide length by 2 to get number of chars
8033     shrl(cnt2, 1);
8034   }
8035   cmpl(cnt2, 1);
8036   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8037 
8038   // Check if the strings start at the same location and setup scale and stride
8039   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8040     cmpptr(str1, str2);
8041     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
8042     if (ae == StrIntrinsicNode::LL) {
8043       scale = Address::times_1;
8044       stride = 16;
8045     } else {
8046       scale = Address::times_2;
8047       stride = 8;
8048     }
8049   } else {
8050     scale = Address::no_scale;  // not used
8051     scale1 = Address::times_1;
8052     scale2 = Address::times_2;
8053     stride = 8;
8054   }
8055 
8056   if (UseAVX >= 2 && UseSSE42Intrinsics) {
8057     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8058     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8059     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8060     Label COMPARE_TAIL_LONG;
8061     int pcmpmask = 0x19;
8062     if (ae == StrIntrinsicNode::LL) {
8063       pcmpmask &= ~0x01;
8064     }
8065 
8066     // Setup to compare 16-chars (32-bytes) vectors,
8067     // start from first character again because it has aligned address.
8068     if (ae == StrIntrinsicNode::LL) {
8069       stride2 = 32;
8070     } else {
8071       stride2 = 16;
8072     }
8073     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8074       adr_stride = stride << scale;
8075     } else {
8076       adr_stride1 = 8;  //stride << scale1;
8077       adr_stride2 = 16; //stride << scale2;
8078     }
8079 
8080     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8081     // rax and rdx are used by pcmpestri as elements counters
8082     movl(result, cnt2);
8083     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8084     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8085 
8086     // fast path : compare first 2 8-char vectors.
8087     bind(COMPARE_16_CHARS);
8088     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8089       movdqu(vec1, Address(str1, 0));
8090     } else {
8091       pmovzxbw(vec1, Address(str1, 0));
8092     }
8093     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8094     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8095 
8096     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8097       movdqu(vec1, Address(str1, adr_stride));
8098       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8099     } else {
8100       pmovzxbw(vec1, Address(str1, adr_stride1));
8101       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8102     }
8103     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8104     addl(cnt1, stride);
8105 
8106     // Compare the characters at index in cnt1
8107     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8108     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8109     subl(result, cnt2);
8110     jmp(POP_LABEL);
8111 
8112     // Setup the registers to start vector comparison loop
8113     bind(COMPARE_WIDE_VECTORS);
8114     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8115       lea(str1, Address(str1, result, scale));
8116       lea(str2, Address(str2, result, scale));
8117     } else {
8118       lea(str1, Address(str1, result, scale1));
8119       lea(str2, Address(str2, result, scale2));
8120     }
8121     subl(result, stride2);
8122     subl(cnt2, stride2);
8123     jccb(Assembler::zero, COMPARE_WIDE_TAIL);
8124     negptr(result);
8125 
8126     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8127     bind(COMPARE_WIDE_VECTORS_LOOP);
8128     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8129       vmovdqu(vec1, Address(str1, result, scale));
8130       vpxor(vec1, Address(str2, result, scale));
8131     } else {
8132       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8133       vpxor(vec1, Address(str2, result, scale2));
8134     }
8135     vptest(vec1, vec1);
8136     jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
8137     addptr(result, stride2);
8138     subl(cnt2, stride2);
8139     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8140     // clean upper bits of YMM registers
8141     vpxor(vec1, vec1);
8142 
8143     // compare wide vectors tail
8144     bind(COMPARE_WIDE_TAIL);
8145     testptr(result, result);
8146     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8147 
8148     movl(result, stride2);
8149     movl(cnt2, result);
8150     negptr(result);
8151     jmpb(COMPARE_WIDE_VECTORS_LOOP);
8152 
8153     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8154     bind(VECTOR_NOT_EQUAL);
8155     // clean upper bits of YMM registers
8156     vpxor(vec1, vec1);
8157     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8158       lea(str1, Address(str1, result, scale));
8159       lea(str2, Address(str2, result, scale));
8160     } else {
8161       lea(str1, Address(str1, result, scale1));
8162       lea(str2, Address(str2, result, scale2));
8163     }
8164     jmp(COMPARE_16_CHARS);
8165 
8166     // Compare tail chars, length between 1 to 15 chars
8167     bind(COMPARE_TAIL_LONG);
8168     movl(cnt2, result);
8169     cmpl(cnt2, stride);
8170     jccb(Assembler::less, COMPARE_SMALL_STR);
8171 
8172     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8173       movdqu(vec1, Address(str1, 0));
8174     } else {
8175       pmovzxbw(vec1, Address(str1, 0));
8176     }
8177     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8178     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8179     subptr(cnt2, stride);
8180     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8181     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8182       lea(str1, Address(str1, result, scale));
8183       lea(str2, Address(str2, result, scale));
8184     } else {
8185       lea(str1, Address(str1, result, scale1));
8186       lea(str2, Address(str2, result, scale2));
8187     }
8188     negptr(cnt2);
8189     jmpb(WHILE_HEAD_LABEL);
8190 
8191     bind(COMPARE_SMALL_STR);
8192   } else if (UseSSE42Intrinsics) {
8193     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8194     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8195     int pcmpmask = 0x19;
8196     // Setup to compare 8-char (16-byte) vectors,
8197     // start from first character again because it has aligned address.
8198     movl(result, cnt2);
8199     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8200     if (ae == StrIntrinsicNode::LL) {
8201       pcmpmask &= ~0x01;
8202     }
8203     jccb(Assembler::zero, COMPARE_TAIL);
8204     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8205       lea(str1, Address(str1, result, scale));
8206       lea(str2, Address(str2, result, scale));
8207     } else {
8208       lea(str1, Address(str1, result, scale1));
8209       lea(str2, Address(str2, result, scale2));
8210     }
8211     negptr(result);
8212 
8213     // pcmpestri
8214     //   inputs:
8215     //     vec1- substring
8216     //     rax - negative string length (elements count)
8217     //     mem - scanned string
8218     //     rdx - string length (elements count)
8219     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8220     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8221     //   outputs:
8222     //     rcx - first mismatched element index
8223     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8224 
8225     bind(COMPARE_WIDE_VECTORS);
8226     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8227       movdqu(vec1, Address(str1, result, scale));
8228       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8229     } else {
8230       pmovzxbw(vec1, Address(str1, result, scale1));
8231       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8232     }
8233     // After pcmpestri cnt1(rcx) contains mismatched element index
8234 
8235     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8236     addptr(result, stride);
8237     subptr(cnt2, stride);
8238     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8239 
8240     // compare wide vectors tail
8241     testptr(result, result);
8242     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8243 
8244     movl(cnt2, stride);
8245     movl(result, stride);
8246     negptr(result);
8247     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8248       movdqu(vec1, Address(str1, result, scale));
8249       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8250     } else {
8251       pmovzxbw(vec1, Address(str1, result, scale1));
8252       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8253     }
8254     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8255 
8256     // Mismatched characters in the vectors
8257     bind(VECTOR_NOT_EQUAL);
8258     addptr(cnt1, result);
8259     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8260     subl(result, cnt2);
8261     jmpb(POP_LABEL);
8262 
8263     bind(COMPARE_TAIL); // limit is zero
8264     movl(cnt2, result);
8265     // Fallthru to tail compare
8266   }
8267   // Shift str2 and str1 to the end of the arrays, negate min
8268   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8269     lea(str1, Address(str1, cnt2, scale));
8270     lea(str2, Address(str2, cnt2, scale));
8271   } else {
8272     lea(str1, Address(str1, cnt2, scale1));
8273     lea(str2, Address(str2, cnt2, scale2));
8274   }
8275   decrementl(cnt2);  // first character was compared already
8276   negptr(cnt2);
8277 
8278   // Compare the rest of the elements
8279   bind(WHILE_HEAD_LABEL);
8280   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8281   subl(result, cnt1);
8282   jccb(Assembler::notZero, POP_LABEL);
8283   increment(cnt2);
8284   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8285 
8286   // Strings are equal up to min length.  Return the length difference.
8287   bind(LENGTH_DIFF_LABEL);
8288   pop(result);
8289   if (ae == StrIntrinsicNode::UU) {
8290     // Divide diff by 2 to get number of chars
8291     sarl(result, 1);
8292   }
8293   jmpb(DONE_LABEL);
8294 
8295   // Discard the stored length difference
8296   bind(POP_LABEL);
8297   pop(cnt1);
8298 
8299   // That's it
8300   bind(DONE_LABEL);
8301   if(ae == StrIntrinsicNode::UL) {
8302     negl(result);
8303   }
8304 }
8305 
8306 // Search for Non-ASCII character (Negative byte value) in a byte array,
8307 // return true if it has any and false otherwise.
8308 void MacroAssembler::has_negatives(Register ary1, Register len,
8309                                    Register result, Register tmp1,
8310                                    XMMRegister vec1, XMMRegister vec2) {
8311 
8312   // rsi: byte array
8313   // rcx: len
8314   // rax: result
8315   ShortBranchVerifier sbv(this);
8316   assert_different_registers(ary1, len, result, tmp1);
8317   assert_different_registers(vec1, vec2);
8318   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8319 
8320   // len == 0
8321   testl(len, len);
8322   jcc(Assembler::zero, FALSE_LABEL);
8323 
8324   movl(result, len); // copy
8325 
8326   if (UseAVX >= 2 && UseSSE >= 2) {
8327     // With AVX2, use 32-byte vector compare
8328     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8329 
8330     // Compare 32-byte vectors
8331     andl(result, 0x0000001f);  //   tail count (in bytes)
8332     andl(len, 0xffffffe0);   // vector count (in bytes)
8333     jccb(Assembler::zero, COMPARE_TAIL);
8334 
8335     lea(ary1, Address(ary1, len, Address::times_1));
8336     negptr(len);
8337 
8338     movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8339     movdl(vec2, tmp1);
8340     vpbroadcastd(vec2, vec2);
8341 
8342     bind(COMPARE_WIDE_VECTORS);
8343     vmovdqu(vec1, Address(ary1, len, Address::times_1));
8344     vptest(vec1, vec2);
8345     jccb(Assembler::notZero, TRUE_LABEL);
8346     addptr(len, 32);
8347     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8348 
8349     testl(result, result);
8350     jccb(Assembler::zero, FALSE_LABEL);
8351 
8352     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8353     vptest(vec1, vec2);
8354     jccb(Assembler::notZero, TRUE_LABEL);
8355     jmpb(FALSE_LABEL);
8356 
8357     bind(COMPARE_TAIL); // len is zero
8358     movl(len, result);
8359     // Fallthru to tail compare
8360   } else if (UseSSE42Intrinsics) {
8361     assert(UseSSE >= 4, "SSE4 must be  for SSE4.2 intrinsics to be available");
8362     // With SSE4.2, use double quad vector compare
8363     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8364 
8365     // Compare 16-byte vectors
8366     andl(result, 0x0000000f);  //   tail count (in bytes)
8367     andl(len, 0xfffffff0);   // vector count (in bytes)
8368     jccb(Assembler::zero, COMPARE_TAIL);
8369 
8370     lea(ary1, Address(ary1, len, Address::times_1));
8371     negptr(len);
8372 
8373     movl(tmp1, 0x80808080);
8374     movdl(vec2, tmp1);
8375     pshufd(vec2, vec2, 0);
8376 
8377     bind(COMPARE_WIDE_VECTORS);
8378     movdqu(vec1, Address(ary1, len, Address::times_1));
8379     ptest(vec1, vec2);
8380     jccb(Assembler::notZero, TRUE_LABEL);
8381     addptr(len, 16);
8382     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8383 
8384     testl(result, result);
8385     jccb(Assembler::zero, FALSE_LABEL);
8386 
8387     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8388     ptest(vec1, vec2);
8389     jccb(Assembler::notZero, TRUE_LABEL);
8390     jmpb(FALSE_LABEL);
8391 
8392     bind(COMPARE_TAIL); // len is zero
8393     movl(len, result);
8394     // Fallthru to tail compare
8395   }
8396 
8397   // Compare 4-byte vectors
8398   andl(len, 0xfffffffc); // vector count (in bytes)
8399   jccb(Assembler::zero, COMPARE_CHAR);
8400 
8401   lea(ary1, Address(ary1, len, Address::times_1));
8402   negptr(len);
8403 
8404   bind(COMPARE_VECTORS);
8405   movl(tmp1, Address(ary1, len, Address::times_1));
8406   andl(tmp1, 0x80808080);
8407   jccb(Assembler::notZero, TRUE_LABEL);
8408   addptr(len, 4);
8409   jcc(Assembler::notZero, COMPARE_VECTORS);
8410 
8411   // Compare trailing char (final 2 bytes), if any
8412   bind(COMPARE_CHAR);
8413   testl(result, 0x2);   // tail  char
8414   jccb(Assembler::zero, COMPARE_BYTE);
8415   load_unsigned_short(tmp1, Address(ary1, 0));
8416   andl(tmp1, 0x00008080);
8417   jccb(Assembler::notZero, TRUE_LABEL);
8418   subptr(result, 2);
8419   lea(ary1, Address(ary1, 2));
8420 
8421   bind(COMPARE_BYTE);
8422   testl(result, 0x1);   // tail  byte
8423   jccb(Assembler::zero, FALSE_LABEL);
8424   load_unsigned_byte(tmp1, Address(ary1, 0));
8425   andl(tmp1, 0x00000080);
8426   jccb(Assembler::notEqual, TRUE_LABEL);
8427   jmpb(FALSE_LABEL);
8428 
8429   bind(TRUE_LABEL);
8430   movl(result, 1);   // return true
8431   jmpb(DONE);
8432 
8433   bind(FALSE_LABEL);
8434   xorl(result, result); // return false
8435 
8436   // That's it
8437   bind(DONE);
8438   if (UseAVX >= 2 && UseSSE >= 2) {
8439     // clean upper bits of YMM registers
8440     vpxor(vec1, vec1);
8441     vpxor(vec2, vec2);
8442   }
8443 }
8444 
8445 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8446 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8447                                    Register limit, Register result, Register chr,
8448                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8449   ShortBranchVerifier sbv(this);
8450   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8451 
8452   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8453   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8454 
8455   if (is_array_equ) {
8456     // Check the input args
8457     cmpptr(ary1, ary2);
8458     jcc(Assembler::equal, TRUE_LABEL);
8459 
8460     // Need additional checks for arrays_equals.
8461     testptr(ary1, ary1);
8462     jcc(Assembler::zero, FALSE_LABEL);
8463     testptr(ary2, ary2);
8464     jcc(Assembler::zero, FALSE_LABEL);
8465 
8466     // Check the lengths
8467     movl(limit, Address(ary1, length_offset));
8468     cmpl(limit, Address(ary2, length_offset));
8469     jcc(Assembler::notEqual, FALSE_LABEL);
8470   }
8471 
8472   // count == 0
8473   testl(limit, limit);
8474   jcc(Assembler::zero, TRUE_LABEL);
8475 
8476   if (is_array_equ) {
8477     // Load array address
8478     lea(ary1, Address(ary1, base_offset));
8479     lea(ary2, Address(ary2, base_offset));
8480   }
8481 
8482   if (is_array_equ && is_char) {
8483     // arrays_equals when used for char[].
8484     shll(limit, 1);      // byte count != 0
8485   }
8486   movl(result, limit); // copy
8487 
8488   if (UseAVX >= 2) {
8489     // With AVX2, use 32-byte vector compare
8490     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8491 
8492     // Compare 32-byte vectors
8493     andl(result, 0x0000001f);  //   tail count (in bytes)
8494     andl(limit, 0xffffffe0);   // vector count (in bytes)
8495     jccb(Assembler::zero, COMPARE_TAIL);
8496 
8497     lea(ary1, Address(ary1, limit, Address::times_1));
8498     lea(ary2, Address(ary2, limit, Address::times_1));
8499     negptr(limit);
8500 
8501     bind(COMPARE_WIDE_VECTORS);
8502     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8503     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8504     vpxor(vec1, vec2);
8505 
8506     vptest(vec1, vec1);
8507     jccb(Assembler::notZero, FALSE_LABEL);
8508     addptr(limit, 32);
8509     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8510 
8511     testl(result, result);
8512     jccb(Assembler::zero, TRUE_LABEL);
8513 
8514     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8515     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8516     vpxor(vec1, vec2);
8517 
8518     vptest(vec1, vec1);
8519     jccb(Assembler::notZero, FALSE_LABEL);
8520     jmpb(TRUE_LABEL);
8521 
8522     bind(COMPARE_TAIL); // limit is zero
8523     movl(limit, result);
8524     // Fallthru to tail compare
8525   } else if (UseSSE42Intrinsics) {
8526     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8527     // With SSE4.2, use double quad vector compare
8528     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8529 
8530     // Compare 16-byte vectors
8531     andl(result, 0x0000000f);  //   tail count (in bytes)
8532     andl(limit, 0xfffffff0);   // vector count (in bytes)
8533     jccb(Assembler::zero, COMPARE_TAIL);
8534 
8535     lea(ary1, Address(ary1, limit, Address::times_1));
8536     lea(ary2, Address(ary2, limit, Address::times_1));
8537     negptr(limit);
8538 
8539     bind(COMPARE_WIDE_VECTORS);
8540     movdqu(vec1, Address(ary1, limit, Address::times_1));
8541     movdqu(vec2, Address(ary2, limit, Address::times_1));
8542     pxor(vec1, vec2);
8543 
8544     ptest(vec1, vec1);
8545     jccb(Assembler::notZero, FALSE_LABEL);
8546     addptr(limit, 16);
8547     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8548 
8549     testl(result, result);
8550     jccb(Assembler::zero, TRUE_LABEL);
8551 
8552     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8553     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8554     pxor(vec1, vec2);
8555 
8556     ptest(vec1, vec1);
8557     jccb(Assembler::notZero, FALSE_LABEL);
8558     jmpb(TRUE_LABEL);
8559 
8560     bind(COMPARE_TAIL); // limit is zero
8561     movl(limit, result);
8562     // Fallthru to tail compare
8563   }
8564 
8565   // Compare 4-byte vectors
8566   andl(limit, 0xfffffffc); // vector count (in bytes)
8567   jccb(Assembler::zero, COMPARE_CHAR);
8568 
8569   lea(ary1, Address(ary1, limit, Address::times_1));
8570   lea(ary2, Address(ary2, limit, Address::times_1));
8571   negptr(limit);
8572 
8573   bind(COMPARE_VECTORS);
8574   movl(chr, Address(ary1, limit, Address::times_1));
8575   cmpl(chr, Address(ary2, limit, Address::times_1));
8576   jccb(Assembler::notEqual, FALSE_LABEL);
8577   addptr(limit, 4);
8578   jcc(Assembler::notZero, COMPARE_VECTORS);
8579 
8580   // Compare trailing char (final 2 bytes), if any
8581   bind(COMPARE_CHAR);
8582   testl(result, 0x2);   // tail  char
8583   jccb(Assembler::zero, COMPARE_BYTE);
8584   load_unsigned_short(chr, Address(ary1, 0));
8585   load_unsigned_short(limit, Address(ary2, 0));
8586   cmpl(chr, limit);
8587   jccb(Assembler::notEqual, FALSE_LABEL);
8588 
8589   if (is_array_equ && is_char) {
8590     bind(COMPARE_BYTE);
8591   } else {
8592     lea(ary1, Address(ary1, 2));
8593     lea(ary2, Address(ary2, 2));
8594 
8595     bind(COMPARE_BYTE);
8596     testl(result, 0x1);   // tail  byte
8597     jccb(Assembler::zero, TRUE_LABEL);
8598     load_unsigned_byte(chr, Address(ary1, 0));
8599     load_unsigned_byte(limit, Address(ary2, 0));
8600     cmpl(chr, limit);
8601     jccb(Assembler::notEqual, FALSE_LABEL);
8602   }
8603   bind(TRUE_LABEL);
8604   movl(result, 1);   // return true
8605   jmpb(DONE);
8606 
8607   bind(FALSE_LABEL);
8608   xorl(result, result); // return false
8609 
8610   // That's it
8611   bind(DONE);
8612   if (UseAVX >= 2) {
8613     // clean upper bits of YMM registers
8614     vpxor(vec1, vec1);
8615     vpxor(vec2, vec2);
8616   }
8617 }
8618 
8619 #endif
8620 
8621 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8622                                    Register to, Register value, Register count,
8623                                    Register rtmp, XMMRegister xtmp) {
8624   ShortBranchVerifier sbv(this);
8625   assert_different_registers(to, value, count, rtmp);
8626   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8627   Label L_fill_2_bytes, L_fill_4_bytes;
8628 
8629   int shift = -1;
8630   switch (t) {
8631     case T_BYTE:
8632       shift = 2;
8633       break;
8634     case T_SHORT:
8635       shift = 1;
8636       break;
8637     case T_INT:
8638       shift = 0;
8639       break;
8640     default: ShouldNotReachHere();
8641   }
8642 
8643   if (t == T_BYTE) {
8644     andl(value, 0xff);
8645     movl(rtmp, value);
8646     shll(rtmp, 8);
8647     orl(value, rtmp);
8648   }
8649   if (t == T_SHORT) {
8650     andl(value, 0xffff);
8651   }
8652   if (t == T_BYTE || t == T_SHORT) {
8653     movl(rtmp, value);
8654     shll(rtmp, 16);
8655     orl(value, rtmp);
8656   }
8657 
8658   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8659   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8660   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8661     // align source address at 4 bytes address boundary
8662     if (t == T_BYTE) {
8663       // One byte misalignment happens only for byte arrays
8664       testptr(to, 1);
8665       jccb(Assembler::zero, L_skip_align1);
8666       movb(Address(to, 0), value);
8667       increment(to);
8668       decrement(count);
8669       BIND(L_skip_align1);
8670     }
8671     // Two bytes misalignment happens only for byte and short (char) arrays
8672     testptr(to, 2);
8673     jccb(Assembler::zero, L_skip_align2);
8674     movw(Address(to, 0), value);
8675     addptr(to, 2);
8676     subl(count, 1<<(shift-1));
8677     BIND(L_skip_align2);
8678   }
8679   if (UseSSE < 2) {
8680     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8681     // Fill 32-byte chunks
8682     subl(count, 8 << shift);
8683     jcc(Assembler::less, L_check_fill_8_bytes);
8684     align(16);
8685 
8686     BIND(L_fill_32_bytes_loop);
8687 
8688     for (int i = 0; i < 32; i += 4) {
8689       movl(Address(to, i), value);
8690     }
8691 
8692     addptr(to, 32);
8693     subl(count, 8 << shift);
8694     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8695     BIND(L_check_fill_8_bytes);
8696     addl(count, 8 << shift);
8697     jccb(Assembler::zero, L_exit);
8698     jmpb(L_fill_8_bytes);
8699 
8700     //
8701     // length is too short, just fill qwords
8702     //
8703     BIND(L_fill_8_bytes_loop);
8704     movl(Address(to, 0), value);
8705     movl(Address(to, 4), value);
8706     addptr(to, 8);
8707     BIND(L_fill_8_bytes);
8708     subl(count, 1 << (shift + 1));
8709     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8710     // fall through to fill 4 bytes
8711   } else {
8712     Label L_fill_32_bytes;
8713     if (!UseUnalignedLoadStores) {
8714       // align to 8 bytes, we know we are 4 byte aligned to start
8715       testptr(to, 4);
8716       jccb(Assembler::zero, L_fill_32_bytes);
8717       movl(Address(to, 0), value);
8718       addptr(to, 4);
8719       subl(count, 1<<shift);
8720     }
8721     BIND(L_fill_32_bytes);
8722     {
8723       assert( UseSSE >= 2, "supported cpu only" );
8724       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8725       if (UseAVX > 2) {
8726         movl(rtmp, 0xffff);
8727         kmovwl(k1, rtmp);
8728       }
8729       movdl(xtmp, value);
8730       if (UseAVX > 2 && UseUnalignedLoadStores) {
8731         // Fill 64-byte chunks
8732         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8733         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8734 
8735         subl(count, 16 << shift);
8736         jcc(Assembler::less, L_check_fill_32_bytes);
8737         align(16);
8738 
8739         BIND(L_fill_64_bytes_loop);
8740         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8741         addptr(to, 64);
8742         subl(count, 16 << shift);
8743         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8744 
8745         BIND(L_check_fill_32_bytes);
8746         addl(count, 8 << shift);
8747         jccb(Assembler::less, L_check_fill_8_bytes);
8748         vmovdqu(Address(to, 0), xtmp);
8749         addptr(to, 32);
8750         subl(count, 8 << shift);
8751 
8752         BIND(L_check_fill_8_bytes);
8753       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8754         // Fill 64-byte chunks
8755         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8756         vpbroadcastd(xtmp, xtmp);
8757 
8758         subl(count, 16 << shift);
8759         jcc(Assembler::less, L_check_fill_32_bytes);
8760         align(16);
8761 
8762         BIND(L_fill_64_bytes_loop);
8763         vmovdqu(Address(to, 0), xtmp);
8764         vmovdqu(Address(to, 32), xtmp);
8765         addptr(to, 64);
8766         subl(count, 16 << shift);
8767         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8768 
8769         BIND(L_check_fill_32_bytes);
8770         addl(count, 8 << shift);
8771         jccb(Assembler::less, L_check_fill_8_bytes);
8772         vmovdqu(Address(to, 0), xtmp);
8773         addptr(to, 32);
8774         subl(count, 8 << shift);
8775 
8776         BIND(L_check_fill_8_bytes);
8777         // clean upper bits of YMM registers
8778         movdl(xtmp, value);
8779         pshufd(xtmp, xtmp, 0);
8780       } else {
8781         // Fill 32-byte chunks
8782         pshufd(xtmp, xtmp, 0);
8783 
8784         subl(count, 8 << shift);
8785         jcc(Assembler::less, L_check_fill_8_bytes);
8786         align(16);
8787 
8788         BIND(L_fill_32_bytes_loop);
8789 
8790         if (UseUnalignedLoadStores) {
8791           movdqu(Address(to, 0), xtmp);
8792           movdqu(Address(to, 16), xtmp);
8793         } else {
8794           movq(Address(to, 0), xtmp);
8795           movq(Address(to, 8), xtmp);
8796           movq(Address(to, 16), xtmp);
8797           movq(Address(to, 24), xtmp);
8798         }
8799 
8800         addptr(to, 32);
8801         subl(count, 8 << shift);
8802         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8803 
8804         BIND(L_check_fill_8_bytes);
8805       }
8806       addl(count, 8 << shift);
8807       jccb(Assembler::zero, L_exit);
8808       jmpb(L_fill_8_bytes);
8809 
8810       //
8811       // length is too short, just fill qwords
8812       //
8813       BIND(L_fill_8_bytes_loop);
8814       movq(Address(to, 0), xtmp);
8815       addptr(to, 8);
8816       BIND(L_fill_8_bytes);
8817       subl(count, 1 << (shift + 1));
8818       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8819     }
8820   }
8821   // fill trailing 4 bytes
8822   BIND(L_fill_4_bytes);
8823   testl(count, 1<<shift);
8824   jccb(Assembler::zero, L_fill_2_bytes);
8825   movl(Address(to, 0), value);
8826   if (t == T_BYTE || t == T_SHORT) {
8827     addptr(to, 4);
8828     BIND(L_fill_2_bytes);
8829     // fill trailing 2 bytes
8830     testl(count, 1<<(shift-1));
8831     jccb(Assembler::zero, L_fill_byte);
8832     movw(Address(to, 0), value);
8833     if (t == T_BYTE) {
8834       addptr(to, 2);
8835       BIND(L_fill_byte);
8836       // fill trailing byte
8837       testl(count, 1);
8838       jccb(Assembler::zero, L_exit);
8839       movb(Address(to, 0), value);
8840     } else {
8841       BIND(L_fill_byte);
8842     }
8843   } else {
8844     BIND(L_fill_2_bytes);
8845   }
8846   BIND(L_exit);
8847 }
8848 
8849 // encode char[] to byte[] in ISO_8859_1
8850 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8851                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8852                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8853                                       Register tmp5, Register result) {
8854   // rsi: src
8855   // rdi: dst
8856   // rdx: len
8857   // rcx: tmp5
8858   // rax: result
8859   ShortBranchVerifier sbv(this);
8860   assert_different_registers(src, dst, len, tmp5, result);
8861   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8862 
8863   // set result
8864   xorl(result, result);
8865   // check for zero length
8866   testl(len, len);
8867   jcc(Assembler::zero, L_done);
8868   movl(result, len);
8869 
8870   // Setup pointers
8871   lea(src, Address(src, len, Address::times_2)); // char[]
8872   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8873   negptr(len);
8874 
8875   if (UseSSE42Intrinsics || UseAVX >= 2) {
8876     assert(UseSSE42Intrinsics ? UseSSE >= 4 : true, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8877     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8878     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8879 
8880     if (UseAVX >= 2) {
8881       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8882       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8883       movdl(tmp1Reg, tmp5);
8884       vpbroadcastd(tmp1Reg, tmp1Reg);
8885       jmpb(L_chars_32_check);
8886 
8887       bind(L_copy_32_chars);
8888       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8889       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8890       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8891       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8892       jccb(Assembler::notZero, L_copy_32_chars_exit);
8893       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8894       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8895       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8896 
8897       bind(L_chars_32_check);
8898       addptr(len, 32);
8899       jccb(Assembler::lessEqual, L_copy_32_chars);
8900 
8901       bind(L_copy_32_chars_exit);
8902       subptr(len, 16);
8903       jccb(Assembler::greater, L_copy_16_chars_exit);
8904 
8905     } else if (UseSSE42Intrinsics) {
8906       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8907       movdl(tmp1Reg, tmp5);
8908       pshufd(tmp1Reg, tmp1Reg, 0);
8909       jmpb(L_chars_16_check);
8910     }
8911 
8912     bind(L_copy_16_chars);
8913     if (UseAVX >= 2) {
8914       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8915       vptest(tmp2Reg, tmp1Reg);
8916       jccb(Assembler::notZero, L_copy_16_chars_exit);
8917       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8918       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8919     } else {
8920       if (UseAVX > 0) {
8921         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8922         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8923         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8924       } else {
8925         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8926         por(tmp2Reg, tmp3Reg);
8927         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8928         por(tmp2Reg, tmp4Reg);
8929       }
8930       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8931       jccb(Assembler::notZero, L_copy_16_chars_exit);
8932       packuswb(tmp3Reg, tmp4Reg);
8933     }
8934     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8935 
8936     bind(L_chars_16_check);
8937     addptr(len, 16);
8938     jccb(Assembler::lessEqual, L_copy_16_chars);
8939 
8940     bind(L_copy_16_chars_exit);
8941     if (UseAVX >= 2) {
8942       // clean upper bits of YMM registers
8943       vpxor(tmp2Reg, tmp2Reg);
8944       vpxor(tmp3Reg, tmp3Reg);
8945       vpxor(tmp4Reg, tmp4Reg);
8946       movdl(tmp1Reg, tmp5);
8947       pshufd(tmp1Reg, tmp1Reg, 0);
8948     }
8949     subptr(len, 8);
8950     jccb(Assembler::greater, L_copy_8_chars_exit);
8951 
8952     bind(L_copy_8_chars);
8953     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8954     ptest(tmp3Reg, tmp1Reg);
8955     jccb(Assembler::notZero, L_copy_8_chars_exit);
8956     packuswb(tmp3Reg, tmp1Reg);
8957     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8958     addptr(len, 8);
8959     jccb(Assembler::lessEqual, L_copy_8_chars);
8960 
8961     bind(L_copy_8_chars_exit);
8962     subptr(len, 8);
8963     jccb(Assembler::zero, L_done);
8964   }
8965 
8966   bind(L_copy_1_char);
8967   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8968   testl(tmp5, 0xff00);      // check if Unicode char
8969   jccb(Assembler::notZero, L_copy_1_char_exit);
8970   movb(Address(dst, len, Address::times_1, 0), tmp5);
8971   addptr(len, 1);
8972   jccb(Assembler::less, L_copy_1_char);
8973 
8974   bind(L_copy_1_char_exit);
8975   addptr(result, len); // len is negative count of not processed elements
8976   bind(L_done);
8977 }
8978 
8979 #ifdef _LP64
8980 /**
8981  * Helper for multiply_to_len().
8982  */
8983 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8984   addq(dest_lo, src1);
8985   adcq(dest_hi, 0);
8986   addq(dest_lo, src2);
8987   adcq(dest_hi, 0);
8988 }
8989 
8990 /**
8991  * Multiply 64 bit by 64 bit first loop.
8992  */
8993 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8994                                            Register y, Register y_idx, Register z,
8995                                            Register carry, Register product,
8996                                            Register idx, Register kdx) {
8997   //
8998   //  jlong carry, x[], y[], z[];
8999   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9000   //    huge_128 product = y[idx] * x[xstart] + carry;
9001   //    z[kdx] = (jlong)product;
9002   //    carry  = (jlong)(product >>> 64);
9003   //  }
9004   //  z[xstart] = carry;
9005   //
9006 
9007   Label L_first_loop, L_first_loop_exit;
9008   Label L_one_x, L_one_y, L_multiply;
9009 
9010   decrementl(xstart);
9011   jcc(Assembler::negative, L_one_x);
9012 
9013   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9014   rorq(x_xstart, 32); // convert big-endian to little-endian
9015 
9016   bind(L_first_loop);
9017   decrementl(idx);
9018   jcc(Assembler::negative, L_first_loop_exit);
9019   decrementl(idx);
9020   jcc(Assembler::negative, L_one_y);
9021   movq(y_idx, Address(y, idx, Address::times_4,  0));
9022   rorq(y_idx, 32); // convert big-endian to little-endian
9023   bind(L_multiply);
9024   movq(product, x_xstart);
9025   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9026   addq(product, carry);
9027   adcq(rdx, 0);
9028   subl(kdx, 2);
9029   movl(Address(z, kdx, Address::times_4,  4), product);
9030   shrq(product, 32);
9031   movl(Address(z, kdx, Address::times_4,  0), product);
9032   movq(carry, rdx);
9033   jmp(L_first_loop);
9034 
9035   bind(L_one_y);
9036   movl(y_idx, Address(y,  0));
9037   jmp(L_multiply);
9038 
9039   bind(L_one_x);
9040   movl(x_xstart, Address(x,  0));
9041   jmp(L_first_loop);
9042 
9043   bind(L_first_loop_exit);
9044 }
9045 
9046 /**
9047  * Multiply 64 bit by 64 bit and add 128 bit.
9048  */
9049 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9050                                             Register yz_idx, Register idx,
9051                                             Register carry, Register product, int offset) {
9052   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9053   //     z[kdx] = (jlong)product;
9054 
9055   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9056   rorq(yz_idx, 32); // convert big-endian to little-endian
9057   movq(product, x_xstart);
9058   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9059   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9060   rorq(yz_idx, 32); // convert big-endian to little-endian
9061 
9062   add2_with_carry(rdx, product, carry, yz_idx);
9063 
9064   movl(Address(z, idx, Address::times_4,  offset+4), product);
9065   shrq(product, 32);
9066   movl(Address(z, idx, Address::times_4,  offset), product);
9067 
9068 }
9069 
9070 /**
9071  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9072  */
9073 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9074                                              Register yz_idx, Register idx, Register jdx,
9075                                              Register carry, Register product,
9076                                              Register carry2) {
9077   //   jlong carry, x[], y[], z[];
9078   //   int kdx = ystart+1;
9079   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9080   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9081   //     z[kdx+idx+1] = (jlong)product;
9082   //     jlong carry2  = (jlong)(product >>> 64);
9083   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9084   //     z[kdx+idx] = (jlong)product;
9085   //     carry  = (jlong)(product >>> 64);
9086   //   }
9087   //   idx += 2;
9088   //   if (idx > 0) {
9089   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9090   //     z[kdx+idx] = (jlong)product;
9091   //     carry  = (jlong)(product >>> 64);
9092   //   }
9093   //
9094 
9095   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9096 
9097   movl(jdx, idx);
9098   andl(jdx, 0xFFFFFFFC);
9099   shrl(jdx, 2);
9100 
9101   bind(L_third_loop);
9102   subl(jdx, 1);
9103   jcc(Assembler::negative, L_third_loop_exit);
9104   subl(idx, 4);
9105 
9106   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9107   movq(carry2, rdx);
9108 
9109   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9110   movq(carry, rdx);
9111   jmp(L_third_loop);
9112 
9113   bind (L_third_loop_exit);
9114 
9115   andl (idx, 0x3);
9116   jcc(Assembler::zero, L_post_third_loop_done);
9117 
9118   Label L_check_1;
9119   subl(idx, 2);
9120   jcc(Assembler::negative, L_check_1);
9121 
9122   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9123   movq(carry, rdx);
9124 
9125   bind (L_check_1);
9126   addl (idx, 0x2);
9127   andl (idx, 0x1);
9128   subl(idx, 1);
9129   jcc(Assembler::negative, L_post_third_loop_done);
9130 
9131   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9132   movq(product, x_xstart);
9133   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9134   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9135 
9136   add2_with_carry(rdx, product, yz_idx, carry);
9137 
9138   movl(Address(z, idx, Address::times_4,  0), product);
9139   shrq(product, 32);
9140 
9141   shlq(rdx, 32);
9142   orq(product, rdx);
9143   movq(carry, product);
9144 
9145   bind(L_post_third_loop_done);
9146 }
9147 
9148 /**
9149  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9150  *
9151  */
9152 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9153                                                   Register carry, Register carry2,
9154                                                   Register idx, Register jdx,
9155                                                   Register yz_idx1, Register yz_idx2,
9156                                                   Register tmp, Register tmp3, Register tmp4) {
9157   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9158 
9159   //   jlong carry, x[], y[], z[];
9160   //   int kdx = ystart+1;
9161   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9162   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9163   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9164   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9165   //     carry  = (jlong)(tmp4 >>> 64);
9166   //     z[kdx+idx+1] = (jlong)tmp3;
9167   //     z[kdx+idx] = (jlong)tmp4;
9168   //   }
9169   //   idx += 2;
9170   //   if (idx > 0) {
9171   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9172   //     z[kdx+idx] = (jlong)yz_idx1;
9173   //     carry  = (jlong)(yz_idx1 >>> 64);
9174   //   }
9175   //
9176 
9177   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9178 
9179   movl(jdx, idx);
9180   andl(jdx, 0xFFFFFFFC);
9181   shrl(jdx, 2);
9182 
9183   bind(L_third_loop);
9184   subl(jdx, 1);
9185   jcc(Assembler::negative, L_third_loop_exit);
9186   subl(idx, 4);
9187 
9188   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9189   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9190   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9191   rorxq(yz_idx2, yz_idx2, 32);
9192 
9193   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9194   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9195 
9196   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9197   rorxq(yz_idx1, yz_idx1, 32);
9198   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9199   rorxq(yz_idx2, yz_idx2, 32);
9200 
9201   if (VM_Version::supports_adx()) {
9202     adcxq(tmp3, carry);
9203     adoxq(tmp3, yz_idx1);
9204 
9205     adcxq(tmp4, tmp);
9206     adoxq(tmp4, yz_idx2);
9207 
9208     movl(carry, 0); // does not affect flags
9209     adcxq(carry2, carry);
9210     adoxq(carry2, carry);
9211   } else {
9212     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9213     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9214   }
9215   movq(carry, carry2);
9216 
9217   movl(Address(z, idx, Address::times_4, 12), tmp3);
9218   shrq(tmp3, 32);
9219   movl(Address(z, idx, Address::times_4,  8), tmp3);
9220 
9221   movl(Address(z, idx, Address::times_4,  4), tmp4);
9222   shrq(tmp4, 32);
9223   movl(Address(z, idx, Address::times_4,  0), tmp4);
9224 
9225   jmp(L_third_loop);
9226 
9227   bind (L_third_loop_exit);
9228 
9229   andl (idx, 0x3);
9230   jcc(Assembler::zero, L_post_third_loop_done);
9231 
9232   Label L_check_1;
9233   subl(idx, 2);
9234   jcc(Assembler::negative, L_check_1);
9235 
9236   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9237   rorxq(yz_idx1, yz_idx1, 32);
9238   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9239   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9240   rorxq(yz_idx2, yz_idx2, 32);
9241 
9242   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9243 
9244   movl(Address(z, idx, Address::times_4,  4), tmp3);
9245   shrq(tmp3, 32);
9246   movl(Address(z, idx, Address::times_4,  0), tmp3);
9247   movq(carry, tmp4);
9248 
9249   bind (L_check_1);
9250   addl (idx, 0x2);
9251   andl (idx, 0x1);
9252   subl(idx, 1);
9253   jcc(Assembler::negative, L_post_third_loop_done);
9254   movl(tmp4, Address(y, idx, Address::times_4,  0));
9255   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9256   movl(tmp4, Address(z, idx, Address::times_4,  0));
9257 
9258   add2_with_carry(carry2, tmp3, tmp4, carry);
9259 
9260   movl(Address(z, idx, Address::times_4,  0), tmp3);
9261   shrq(tmp3, 32);
9262 
9263   shlq(carry2, 32);
9264   orq(tmp3, carry2);
9265   movq(carry, tmp3);
9266 
9267   bind(L_post_third_loop_done);
9268 }
9269 
9270 /**
9271  * Code for BigInteger::multiplyToLen() instrinsic.
9272  *
9273  * rdi: x
9274  * rax: xlen
9275  * rsi: y
9276  * rcx: ylen
9277  * r8:  z
9278  * r11: zlen
9279  * r12: tmp1
9280  * r13: tmp2
9281  * r14: tmp3
9282  * r15: tmp4
9283  * rbx: tmp5
9284  *
9285  */
9286 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9287                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9288   ShortBranchVerifier sbv(this);
9289   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9290 
9291   push(tmp1);
9292   push(tmp2);
9293   push(tmp3);
9294   push(tmp4);
9295   push(tmp5);
9296 
9297   push(xlen);
9298   push(zlen);
9299 
9300   const Register idx = tmp1;
9301   const Register kdx = tmp2;
9302   const Register xstart = tmp3;
9303 
9304   const Register y_idx = tmp4;
9305   const Register carry = tmp5;
9306   const Register product  = xlen;
9307   const Register x_xstart = zlen;  // reuse register
9308 
9309   // First Loop.
9310   //
9311   //  final static long LONG_MASK = 0xffffffffL;
9312   //  int xstart = xlen - 1;
9313   //  int ystart = ylen - 1;
9314   //  long carry = 0;
9315   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9316   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9317   //    z[kdx] = (int)product;
9318   //    carry = product >>> 32;
9319   //  }
9320   //  z[xstart] = (int)carry;
9321   //
9322 
9323   movl(idx, ylen);      // idx = ylen;
9324   movl(kdx, zlen);      // kdx = xlen+ylen;
9325   xorq(carry, carry);   // carry = 0;
9326 
9327   Label L_done;
9328 
9329   movl(xstart, xlen);
9330   decrementl(xstart);
9331   jcc(Assembler::negative, L_done);
9332 
9333   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9334 
9335   Label L_second_loop;
9336   testl(kdx, kdx);
9337   jcc(Assembler::zero, L_second_loop);
9338 
9339   Label L_carry;
9340   subl(kdx, 1);
9341   jcc(Assembler::zero, L_carry);
9342 
9343   movl(Address(z, kdx, Address::times_4,  0), carry);
9344   shrq(carry, 32);
9345   subl(kdx, 1);
9346 
9347   bind(L_carry);
9348   movl(Address(z, kdx, Address::times_4,  0), carry);
9349 
9350   // Second and third (nested) loops.
9351   //
9352   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9353   //   carry = 0;
9354   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9355   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9356   //                    (z[k] & LONG_MASK) + carry;
9357   //     z[k] = (int)product;
9358   //     carry = product >>> 32;
9359   //   }
9360   //   z[i] = (int)carry;
9361   // }
9362   //
9363   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9364 
9365   const Register jdx = tmp1;
9366 
9367   bind(L_second_loop);
9368   xorl(carry, carry);    // carry = 0;
9369   movl(jdx, ylen);       // j = ystart+1
9370 
9371   subl(xstart, 1);       // i = xstart-1;
9372   jcc(Assembler::negative, L_done);
9373 
9374   push (z);
9375 
9376   Label L_last_x;
9377   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9378   subl(xstart, 1);       // i = xstart-1;
9379   jcc(Assembler::negative, L_last_x);
9380 
9381   if (UseBMI2Instructions) {
9382     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9383     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9384   } else {
9385     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9386     rorq(x_xstart, 32);  // convert big-endian to little-endian
9387   }
9388 
9389   Label L_third_loop_prologue;
9390   bind(L_third_loop_prologue);
9391 
9392   push (x);
9393   push (xstart);
9394   push (ylen);
9395 
9396 
9397   if (UseBMI2Instructions) {
9398     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9399   } else { // !UseBMI2Instructions
9400     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9401   }
9402 
9403   pop(ylen);
9404   pop(xlen);
9405   pop(x);
9406   pop(z);
9407 
9408   movl(tmp3, xlen);
9409   addl(tmp3, 1);
9410   movl(Address(z, tmp3, Address::times_4,  0), carry);
9411   subl(tmp3, 1);
9412   jccb(Assembler::negative, L_done);
9413 
9414   shrq(carry, 32);
9415   movl(Address(z, tmp3, Address::times_4,  0), carry);
9416   jmp(L_second_loop);
9417 
9418   // Next infrequent code is moved outside loops.
9419   bind(L_last_x);
9420   if (UseBMI2Instructions) {
9421     movl(rdx, Address(x,  0));
9422   } else {
9423     movl(x_xstart, Address(x,  0));
9424   }
9425   jmp(L_third_loop_prologue);
9426 
9427   bind(L_done);
9428 
9429   pop(zlen);
9430   pop(xlen);
9431 
9432   pop(tmp5);
9433   pop(tmp4);
9434   pop(tmp3);
9435   pop(tmp2);
9436   pop(tmp1);
9437 }
9438 
9439 //Helper functions for square_to_len()
9440 
9441 /**
9442  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9443  * Preserves x and z and modifies rest of the registers.
9444  */
9445 
9446 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9447   // Perform square and right shift by 1
9448   // Handle odd xlen case first, then for even xlen do the following
9449   // jlong carry = 0;
9450   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9451   //     huge_128 product = x[j:j+1] * x[j:j+1];
9452   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9453   //     z[i+2:i+3] = (jlong)(product >>> 1);
9454   //     carry = (jlong)product;
9455   // }
9456 
9457   xorq(tmp5, tmp5);     // carry
9458   xorq(rdxReg, rdxReg);
9459   xorl(tmp1, tmp1);     // index for x
9460   xorl(tmp4, tmp4);     // index for z
9461 
9462   Label L_first_loop, L_first_loop_exit;
9463 
9464   testl(xlen, 1);
9465   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9466 
9467   // Square and right shift by 1 the odd element using 32 bit multiply
9468   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9469   imulq(raxReg, raxReg);
9470   shrq(raxReg, 1);
9471   adcq(tmp5, 0);
9472   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9473   incrementl(tmp1);
9474   addl(tmp4, 2);
9475 
9476   // Square and  right shift by 1 the rest using 64 bit multiply
9477   bind(L_first_loop);
9478   cmpptr(tmp1, xlen);
9479   jccb(Assembler::equal, L_first_loop_exit);
9480 
9481   // Square
9482   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9483   rorq(raxReg, 32);    // convert big-endian to little-endian
9484   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9485 
9486   // Right shift by 1 and save carry
9487   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9488   rcrq(rdxReg, 1);
9489   rcrq(raxReg, 1);
9490   adcq(tmp5, 0);
9491 
9492   // Store result in z
9493   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9494   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9495 
9496   // Update indices for x and z
9497   addl(tmp1, 2);
9498   addl(tmp4, 4);
9499   jmp(L_first_loop);
9500 
9501   bind(L_first_loop_exit);
9502 }
9503 
9504 
9505 /**
9506  * Perform the following multiply add operation using BMI2 instructions
9507  * carry:sum = sum + op1*op2 + carry
9508  * op2 should be in rdx
9509  * op2 is preserved, all other registers are modified
9510  */
9511 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9512   // assert op2 is rdx
9513   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9514   addq(sum, carry);
9515   adcq(tmp2, 0);
9516   addq(sum, op1);
9517   adcq(tmp2, 0);
9518   movq(carry, tmp2);
9519 }
9520 
9521 /**
9522  * Perform the following multiply add operation:
9523  * carry:sum = sum + op1*op2 + carry
9524  * Preserves op1, op2 and modifies rest of registers
9525  */
9526 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9527   // rdx:rax = op1 * op2
9528   movq(raxReg, op2);
9529   mulq(op1);
9530 
9531   //  rdx:rax = sum + carry + rdx:rax
9532   addq(sum, carry);
9533   adcq(rdxReg, 0);
9534   addq(sum, raxReg);
9535   adcq(rdxReg, 0);
9536 
9537   // carry:sum = rdx:sum
9538   movq(carry, rdxReg);
9539 }
9540 
9541 /**
9542  * Add 64 bit long carry into z[] with carry propogation.
9543  * Preserves z and carry register values and modifies rest of registers.
9544  *
9545  */
9546 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9547   Label L_fourth_loop, L_fourth_loop_exit;
9548 
9549   movl(tmp1, 1);
9550   subl(zlen, 2);
9551   addq(Address(z, zlen, Address::times_4, 0), carry);
9552 
9553   bind(L_fourth_loop);
9554   jccb(Assembler::carryClear, L_fourth_loop_exit);
9555   subl(zlen, 2);
9556   jccb(Assembler::negative, L_fourth_loop_exit);
9557   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9558   jmp(L_fourth_loop);
9559   bind(L_fourth_loop_exit);
9560 }
9561 
9562 /**
9563  * Shift z[] left by 1 bit.
9564  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9565  *
9566  */
9567 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9568 
9569   Label L_fifth_loop, L_fifth_loop_exit;
9570 
9571   // Fifth loop
9572   // Perform primitiveLeftShift(z, zlen, 1)
9573 
9574   const Register prev_carry = tmp1;
9575   const Register new_carry = tmp4;
9576   const Register value = tmp2;
9577   const Register zidx = tmp3;
9578 
9579   // int zidx, carry;
9580   // long value;
9581   // carry = 0;
9582   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9583   //    (carry:value)  = (z[i] << 1) | carry ;
9584   //    z[i] = value;
9585   // }
9586 
9587   movl(zidx, zlen);
9588   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9589 
9590   bind(L_fifth_loop);
9591   decl(zidx);  // Use decl to preserve carry flag
9592   decl(zidx);
9593   jccb(Assembler::negative, L_fifth_loop_exit);
9594 
9595   if (UseBMI2Instructions) {
9596      movq(value, Address(z, zidx, Address::times_4, 0));
9597      rclq(value, 1);
9598      rorxq(value, value, 32);
9599      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9600   }
9601   else {
9602     // clear new_carry
9603     xorl(new_carry, new_carry);
9604 
9605     // Shift z[i] by 1, or in previous carry and save new carry
9606     movq(value, Address(z, zidx, Address::times_4, 0));
9607     shlq(value, 1);
9608     adcl(new_carry, 0);
9609 
9610     orq(value, prev_carry);
9611     rorq(value, 0x20);
9612     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9613 
9614     // Set previous carry = new carry
9615     movl(prev_carry, new_carry);
9616   }
9617   jmp(L_fifth_loop);
9618 
9619   bind(L_fifth_loop_exit);
9620 }
9621 
9622 
9623 /**
9624  * Code for BigInteger::squareToLen() intrinsic
9625  *
9626  * rdi: x
9627  * rsi: len
9628  * r8:  z
9629  * rcx: zlen
9630  * r12: tmp1
9631  * r13: tmp2
9632  * r14: tmp3
9633  * r15: tmp4
9634  * rbx: tmp5
9635  *
9636  */
9637 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) {
9638 
9639   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;
9640   push(tmp1);
9641   push(tmp2);
9642   push(tmp3);
9643   push(tmp4);
9644   push(tmp5);
9645 
9646   // First loop
9647   // Store the squares, right shifted one bit (i.e., divided by 2).
9648   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9649 
9650   // Add in off-diagonal sums.
9651   //
9652   // Second, third (nested) and fourth loops.
9653   // zlen +=2;
9654   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9655   //    carry = 0;
9656   //    long op2 = x[xidx:xidx+1];
9657   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9658   //       k -= 2;
9659   //       long op1 = x[j:j+1];
9660   //       long sum = z[k:k+1];
9661   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9662   //       z[k:k+1] = sum;
9663   //    }
9664   //    add_one_64(z, k, carry, tmp_regs);
9665   // }
9666 
9667   const Register carry = tmp5;
9668   const Register sum = tmp3;
9669   const Register op1 = tmp4;
9670   Register op2 = tmp2;
9671 
9672   push(zlen);
9673   push(len);
9674   addl(zlen,2);
9675   bind(L_second_loop);
9676   xorq(carry, carry);
9677   subl(zlen, 4);
9678   subl(len, 2);
9679   push(zlen);
9680   push(len);
9681   cmpl(len, 0);
9682   jccb(Assembler::lessEqual, L_second_loop_exit);
9683 
9684   // Multiply an array by one 64 bit long.
9685   if (UseBMI2Instructions) {
9686     op2 = rdxReg;
9687     movq(op2, Address(x, len, Address::times_4,  0));
9688     rorxq(op2, op2, 32);
9689   }
9690   else {
9691     movq(op2, Address(x, len, Address::times_4,  0));
9692     rorq(op2, 32);
9693   }
9694 
9695   bind(L_third_loop);
9696   decrementl(len);
9697   jccb(Assembler::negative, L_third_loop_exit);
9698   decrementl(len);
9699   jccb(Assembler::negative, L_last_x);
9700 
9701   movq(op1, Address(x, len, Address::times_4,  0));
9702   rorq(op1, 32);
9703 
9704   bind(L_multiply);
9705   subl(zlen, 2);
9706   movq(sum, Address(z, zlen, Address::times_4,  0));
9707 
9708   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9709   if (UseBMI2Instructions) {
9710     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9711   }
9712   else {
9713     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9714   }
9715 
9716   movq(Address(z, zlen, Address::times_4, 0), sum);
9717 
9718   jmp(L_third_loop);
9719   bind(L_third_loop_exit);
9720 
9721   // Fourth loop
9722   // Add 64 bit long carry into z with carry propogation.
9723   // Uses offsetted zlen.
9724   add_one_64(z, zlen, carry, tmp1);
9725 
9726   pop(len);
9727   pop(zlen);
9728   jmp(L_second_loop);
9729 
9730   // Next infrequent code is moved outside loops.
9731   bind(L_last_x);
9732   movl(op1, Address(x, 0));
9733   jmp(L_multiply);
9734 
9735   bind(L_second_loop_exit);
9736   pop(len);
9737   pop(zlen);
9738   pop(len);
9739   pop(zlen);
9740 
9741   // Fifth loop
9742   // Shift z left 1 bit.
9743   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9744 
9745   // z[zlen-1] |= x[len-1] & 1;
9746   movl(tmp3, Address(x, len, Address::times_4, -4));
9747   andl(tmp3, 1);
9748   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9749 
9750   pop(tmp5);
9751   pop(tmp4);
9752   pop(tmp3);
9753   pop(tmp2);
9754   pop(tmp1);
9755 }
9756 
9757 /**
9758  * Helper function for mul_add()
9759  * Multiply the in[] by int k and add to out[] starting at offset offs using
9760  * 128 bit by 32 bit multiply and return the carry in tmp5.
9761  * Only quad int aligned length of in[] is operated on in this function.
9762  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9763  * This function preserves out, in and k registers.
9764  * len and offset point to the appropriate index in "in" & "out" correspondingly
9765  * tmp5 has the carry.
9766  * other registers are temporary and are modified.
9767  *
9768  */
9769 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9770   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9771   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9772 
9773   Label L_first_loop, L_first_loop_exit;
9774 
9775   movl(tmp1, len);
9776   shrl(tmp1, 2);
9777 
9778   bind(L_first_loop);
9779   subl(tmp1, 1);
9780   jccb(Assembler::negative, L_first_loop_exit);
9781 
9782   subl(len, 4);
9783   subl(offset, 4);
9784 
9785   Register op2 = tmp2;
9786   const Register sum = tmp3;
9787   const Register op1 = tmp4;
9788   const Register carry = tmp5;
9789 
9790   if (UseBMI2Instructions) {
9791     op2 = rdxReg;
9792   }
9793 
9794   movq(op1, Address(in, len, Address::times_4,  8));
9795   rorq(op1, 32);
9796   movq(sum, Address(out, offset, Address::times_4,  8));
9797   rorq(sum, 32);
9798   if (UseBMI2Instructions) {
9799     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9800   }
9801   else {
9802     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9803   }
9804   // Store back in big endian from little endian
9805   rorq(sum, 0x20);
9806   movq(Address(out, offset, Address::times_4,  8), sum);
9807 
9808   movq(op1, Address(in, len, Address::times_4,  0));
9809   rorq(op1, 32);
9810   movq(sum, Address(out, offset, Address::times_4,  0));
9811   rorq(sum, 32);
9812   if (UseBMI2Instructions) {
9813     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9814   }
9815   else {
9816     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9817   }
9818   // Store back in big endian from little endian
9819   rorq(sum, 0x20);
9820   movq(Address(out, offset, Address::times_4,  0), sum);
9821 
9822   jmp(L_first_loop);
9823   bind(L_first_loop_exit);
9824 }
9825 
9826 /**
9827  * Code for BigInteger::mulAdd() intrinsic
9828  *
9829  * rdi: out
9830  * rsi: in
9831  * r11: offs (out.length - offset)
9832  * rcx: len
9833  * r8:  k
9834  * r12: tmp1
9835  * r13: tmp2
9836  * r14: tmp3
9837  * r15: tmp4
9838  * rbx: tmp5
9839  * Multiply the in[] by word k and add to out[], return the carry in rax
9840  */
9841 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9842    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9843    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9844 
9845   Label L_carry, L_last_in, L_done;
9846 
9847 // carry = 0;
9848 // for (int j=len-1; j >= 0; j--) {
9849 //    long product = (in[j] & LONG_MASK) * kLong +
9850 //                   (out[offs] & LONG_MASK) + carry;
9851 //    out[offs--] = (int)product;
9852 //    carry = product >>> 32;
9853 // }
9854 //
9855   push(tmp1);
9856   push(tmp2);
9857   push(tmp3);
9858   push(tmp4);
9859   push(tmp5);
9860 
9861   Register op2 = tmp2;
9862   const Register sum = tmp3;
9863   const Register op1 = tmp4;
9864   const Register carry =  tmp5;
9865 
9866   if (UseBMI2Instructions) {
9867     op2 = rdxReg;
9868     movl(op2, k);
9869   }
9870   else {
9871     movl(op2, k);
9872   }
9873 
9874   xorq(carry, carry);
9875 
9876   //First loop
9877 
9878   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9879   //The carry is in tmp5
9880   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9881 
9882   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9883   decrementl(len);
9884   jccb(Assembler::negative, L_carry);
9885   decrementl(len);
9886   jccb(Assembler::negative, L_last_in);
9887 
9888   movq(op1, Address(in, len, Address::times_4,  0));
9889   rorq(op1, 32);
9890 
9891   subl(offs, 2);
9892   movq(sum, Address(out, offs, Address::times_4,  0));
9893   rorq(sum, 32);
9894 
9895   if (UseBMI2Instructions) {
9896     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9897   }
9898   else {
9899     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9900   }
9901 
9902   // Store back in big endian from little endian
9903   rorq(sum, 0x20);
9904   movq(Address(out, offs, Address::times_4,  0), sum);
9905 
9906   testl(len, len);
9907   jccb(Assembler::zero, L_carry);
9908 
9909   //Multiply the last in[] entry, if any
9910   bind(L_last_in);
9911   movl(op1, Address(in, 0));
9912   movl(sum, Address(out, offs, Address::times_4,  -4));
9913 
9914   movl(raxReg, k);
9915   mull(op1); //tmp4 * eax -> edx:eax
9916   addl(sum, carry);
9917   adcl(rdxReg, 0);
9918   addl(sum, raxReg);
9919   adcl(rdxReg, 0);
9920   movl(carry, rdxReg);
9921 
9922   movl(Address(out, offs, Address::times_4,  -4), sum);
9923 
9924   bind(L_carry);
9925   //return tmp5/carry as carry in rax
9926   movl(rax, carry);
9927 
9928   bind(L_done);
9929   pop(tmp5);
9930   pop(tmp4);
9931   pop(tmp3);
9932   pop(tmp2);
9933   pop(tmp1);
9934 }
9935 #endif
9936 
9937 /**
9938  * Emits code to update CRC-32 with a byte value according to constants in table
9939  *
9940  * @param [in,out]crc   Register containing the crc.
9941  * @param [in]val       Register containing the byte to fold into the CRC.
9942  * @param [in]table     Register containing the table of crc constants.
9943  *
9944  * uint32_t crc;
9945  * val = crc_table[(val ^ crc) & 0xFF];
9946  * crc = val ^ (crc >> 8);
9947  *
9948  */
9949 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9950   xorl(val, crc);
9951   andl(val, 0xFF);
9952   shrl(crc, 8); // unsigned shift
9953   xorl(crc, Address(table, val, Address::times_4, 0));
9954 }
9955 
9956 /**
9957  * Fold 128-bit data chunk
9958  */
9959 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9960   if (UseAVX > 0) {
9961     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9962     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9963     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9964     pxor(xcrc, xtmp);
9965   } else {
9966     movdqa(xtmp, xcrc);
9967     pclmulhdq(xtmp, xK);   // [123:64]
9968     pclmulldq(xcrc, xK);   // [63:0]
9969     pxor(xcrc, xtmp);
9970     movdqu(xtmp, Address(buf, offset));
9971     pxor(xcrc, xtmp);
9972   }
9973 }
9974 
9975 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9976   if (UseAVX > 0) {
9977     vpclmulhdq(xtmp, xK, xcrc);
9978     vpclmulldq(xcrc, xK, xcrc);
9979     pxor(xcrc, xbuf);
9980     pxor(xcrc, xtmp);
9981   } else {
9982     movdqa(xtmp, xcrc);
9983     pclmulhdq(xtmp, xK);
9984     pclmulldq(xcrc, xK);
9985     pxor(xcrc, xbuf);
9986     pxor(xcrc, xtmp);
9987   }
9988 }
9989 
9990 /**
9991  * 8-bit folds to compute 32-bit CRC
9992  *
9993  * uint64_t xcrc;
9994  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9995  */
9996 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9997   movdl(tmp, xcrc);
9998   andl(tmp, 0xFF);
9999   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10000   psrldq(xcrc, 1); // unsigned shift one byte
10001   pxor(xcrc, xtmp);
10002 }
10003 
10004 /**
10005  * uint32_t crc;
10006  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10007  */
10008 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10009   movl(tmp, crc);
10010   andl(tmp, 0xFF);
10011   shrl(crc, 8);
10012   xorl(crc, Address(table, tmp, Address::times_4, 0));
10013 }
10014 
10015 /**
10016  * @param crc   register containing existing CRC (32-bit)
10017  * @param buf   register pointing to input byte buffer (byte*)
10018  * @param len   register containing number of bytes
10019  * @param table register that will contain address of CRC table
10020  * @param tmp   scratch register
10021  */
10022 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10023   assert_different_registers(crc, buf, len, table, tmp, rax);
10024 
10025   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10026   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10027 
10028   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10029   // context for the registers used, where all instructions below are using 128-bit mode
10030   // On EVEX without VL and BW, these instructions will all be AVX.
10031   if (VM_Version::supports_avx512vlbw()) {
10032     movl(tmp, 0xffff);
10033     kmovwl(k1, tmp);
10034   }
10035 
10036   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10037   notl(crc); // ~crc
10038   cmpl(len, 16);
10039   jcc(Assembler::less, L_tail);
10040 
10041   // Align buffer to 16 bytes
10042   movl(tmp, buf);
10043   andl(tmp, 0xF);
10044   jccb(Assembler::zero, L_aligned);
10045   subl(tmp,  16);
10046   addl(len, tmp);
10047 
10048   align(4);
10049   BIND(L_align_loop);
10050   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10051   update_byte_crc32(crc, rax, table);
10052   increment(buf);
10053   incrementl(tmp);
10054   jccb(Assembler::less, L_align_loop);
10055 
10056   BIND(L_aligned);
10057   movl(tmp, len); // save
10058   shrl(len, 4);
10059   jcc(Assembler::zero, L_tail_restore);
10060 
10061   // Fold crc into first bytes of vector
10062   movdqa(xmm1, Address(buf, 0));
10063   movdl(rax, xmm1);
10064   xorl(crc, rax);
10065   pinsrd(xmm1, crc, 0);
10066   addptr(buf, 16);
10067   subl(len, 4); // len > 0
10068   jcc(Assembler::less, L_fold_tail);
10069 
10070   movdqa(xmm2, Address(buf,  0));
10071   movdqa(xmm3, Address(buf, 16));
10072   movdqa(xmm4, Address(buf, 32));
10073   addptr(buf, 48);
10074   subl(len, 3);
10075   jcc(Assembler::lessEqual, L_fold_512b);
10076 
10077   // Fold total 512 bits of polynomial on each iteration,
10078   // 128 bits per each of 4 parallel streams.
10079   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10080 
10081   align(32);
10082   BIND(L_fold_512b_loop);
10083   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10084   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10085   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10086   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10087   addptr(buf, 64);
10088   subl(len, 4);
10089   jcc(Assembler::greater, L_fold_512b_loop);
10090 
10091   // Fold 512 bits to 128 bits.
10092   BIND(L_fold_512b);
10093   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10094   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10095   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10096   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10097 
10098   // Fold the rest of 128 bits data chunks
10099   BIND(L_fold_tail);
10100   addl(len, 3);
10101   jccb(Assembler::lessEqual, L_fold_128b);
10102   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10103 
10104   BIND(L_fold_tail_loop);
10105   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10106   addptr(buf, 16);
10107   decrementl(len);
10108   jccb(Assembler::greater, L_fold_tail_loop);
10109 
10110   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10111   BIND(L_fold_128b);
10112   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10113   if (UseAVX > 0) {
10114     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10115     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10116     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10117   } else {
10118     movdqa(xmm2, xmm0);
10119     pclmulqdq(xmm2, xmm1, 0x1);
10120     movdqa(xmm3, xmm0);
10121     pand(xmm3, xmm2);
10122     pclmulqdq(xmm0, xmm3, 0x1);
10123   }
10124   psrldq(xmm1, 8);
10125   psrldq(xmm2, 4);
10126   pxor(xmm0, xmm1);
10127   pxor(xmm0, xmm2);
10128 
10129   // 8 8-bit folds to compute 32-bit CRC.
10130   for (int j = 0; j < 4; j++) {
10131     fold_8bit_crc32(xmm0, table, xmm1, rax);
10132   }
10133   movdl(crc, xmm0); // mov 32 bits to general register
10134   for (int j = 0; j < 4; j++) {
10135     fold_8bit_crc32(crc, table, rax);
10136   }
10137 
10138   BIND(L_tail_restore);
10139   movl(len, tmp); // restore
10140   BIND(L_tail);
10141   andl(len, 0xf);
10142   jccb(Assembler::zero, L_exit);
10143 
10144   // Fold the rest of bytes
10145   align(4);
10146   BIND(L_tail_loop);
10147   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10148   update_byte_crc32(crc, rax, table);
10149   increment(buf);
10150   decrementl(len);
10151   jccb(Assembler::greater, L_tail_loop);
10152 
10153   BIND(L_exit);
10154   notl(crc); // ~c
10155 }
10156 
10157 #ifdef _LP64
10158 // S. Gueron / Information Processing Letters 112 (2012) 184
10159 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10160 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10161 // Output: the 64-bit carry-less product of B * CONST
10162 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10163                                      Register tmp1, Register tmp2, Register tmp3) {
10164   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10165   if (n > 0) {
10166     addq(tmp3, n * 256 * 8);
10167   }
10168   //    Q1 = TABLEExt[n][B & 0xFF];
10169   movl(tmp1, in);
10170   andl(tmp1, 0x000000FF);
10171   shll(tmp1, 3);
10172   addq(tmp1, tmp3);
10173   movq(tmp1, Address(tmp1, 0));
10174 
10175   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10176   movl(tmp2, in);
10177   shrl(tmp2, 8);
10178   andl(tmp2, 0x000000FF);
10179   shll(tmp2, 3);
10180   addq(tmp2, tmp3);
10181   movq(tmp2, Address(tmp2, 0));
10182 
10183   shlq(tmp2, 8);
10184   xorq(tmp1, tmp2);
10185 
10186   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10187   movl(tmp2, in);
10188   shrl(tmp2, 16);
10189   andl(tmp2, 0x000000FF);
10190   shll(tmp2, 3);
10191   addq(tmp2, tmp3);
10192   movq(tmp2, Address(tmp2, 0));
10193 
10194   shlq(tmp2, 16);
10195   xorq(tmp1, tmp2);
10196 
10197   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10198   shrl(in, 24);
10199   andl(in, 0x000000FF);
10200   shll(in, 3);
10201   addq(in, tmp3);
10202   movq(in, Address(in, 0));
10203 
10204   shlq(in, 24);
10205   xorq(in, tmp1);
10206   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10207 }
10208 
10209 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10210                                       Register in_out,
10211                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10212                                       XMMRegister w_xtmp2,
10213                                       Register tmp1,
10214                                       Register n_tmp2, Register n_tmp3) {
10215   if (is_pclmulqdq_supported) {
10216     movdl(w_xtmp1, in_out); // modified blindly
10217 
10218     movl(tmp1, const_or_pre_comp_const_index);
10219     movdl(w_xtmp2, tmp1);
10220     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10221 
10222     movdq(in_out, w_xtmp1);
10223   } else {
10224     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10225   }
10226 }
10227 
10228 // Recombination Alternative 2: No bit-reflections
10229 // T1 = (CRC_A * U1) << 1
10230 // T2 = (CRC_B * U2) << 1
10231 // C1 = T1 >> 32
10232 // C2 = T2 >> 32
10233 // T1 = T1 & 0xFFFFFFFF
10234 // T2 = T2 & 0xFFFFFFFF
10235 // T1 = CRC32(0, T1)
10236 // T2 = CRC32(0, T2)
10237 // C1 = C1 ^ T1
10238 // C2 = C2 ^ T2
10239 // CRC = C1 ^ C2 ^ CRC_C
10240 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,
10241                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10242                                      Register tmp1, Register tmp2,
10243                                      Register n_tmp3) {
10244   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10245   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10246   shlq(in_out, 1);
10247   movl(tmp1, in_out);
10248   shrq(in_out, 32);
10249   xorl(tmp2, tmp2);
10250   crc32(tmp2, tmp1, 4);
10251   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10252   shlq(in1, 1);
10253   movl(tmp1, in1);
10254   shrq(in1, 32);
10255   xorl(tmp2, tmp2);
10256   crc32(tmp2, tmp1, 4);
10257   xorl(in1, tmp2);
10258   xorl(in_out, in1);
10259   xorl(in_out, in2);
10260 }
10261 
10262 // Set N to predefined value
10263 // Subtract from a lenght of a buffer
10264 // execute in a loop:
10265 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10266 // for i = 1 to N do
10267 //  CRC_A = CRC32(CRC_A, A[i])
10268 //  CRC_B = CRC32(CRC_B, B[i])
10269 //  CRC_C = CRC32(CRC_C, C[i])
10270 // end for
10271 // Recombine
10272 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,
10273                                        Register in_out1, Register in_out2, Register in_out3,
10274                                        Register tmp1, Register tmp2, Register tmp3,
10275                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10276                                        Register tmp4, Register tmp5,
10277                                        Register n_tmp6) {
10278   Label L_processPartitions;
10279   Label L_processPartition;
10280   Label L_exit;
10281 
10282   bind(L_processPartitions);
10283   cmpl(in_out1, 3 * size);
10284   jcc(Assembler::less, L_exit);
10285     xorl(tmp1, tmp1);
10286     xorl(tmp2, tmp2);
10287     movq(tmp3, in_out2);
10288     addq(tmp3, size);
10289 
10290     bind(L_processPartition);
10291       crc32(in_out3, Address(in_out2, 0), 8);
10292       crc32(tmp1, Address(in_out2, size), 8);
10293       crc32(tmp2, Address(in_out2, size * 2), 8);
10294       addq(in_out2, 8);
10295       cmpq(in_out2, tmp3);
10296       jcc(Assembler::less, L_processPartition);
10297     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10298             w_xtmp1, w_xtmp2, w_xtmp3,
10299             tmp4, tmp5,
10300             n_tmp6);
10301     addq(in_out2, 2 * size);
10302     subl(in_out1, 3 * size);
10303     jmp(L_processPartitions);
10304 
10305   bind(L_exit);
10306 }
10307 #else
10308 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10309                                      Register tmp1, Register tmp2, Register tmp3,
10310                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10311   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10312   if (n > 0) {
10313     addl(tmp3, n * 256 * 8);
10314   }
10315   //    Q1 = TABLEExt[n][B & 0xFF];
10316   movl(tmp1, in_out);
10317   andl(tmp1, 0x000000FF);
10318   shll(tmp1, 3);
10319   addl(tmp1, tmp3);
10320   movq(xtmp1, Address(tmp1, 0));
10321 
10322   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10323   movl(tmp2, in_out);
10324   shrl(tmp2, 8);
10325   andl(tmp2, 0x000000FF);
10326   shll(tmp2, 3);
10327   addl(tmp2, tmp3);
10328   movq(xtmp2, Address(tmp2, 0));
10329 
10330   psllq(xtmp2, 8);
10331   pxor(xtmp1, xtmp2);
10332 
10333   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10334   movl(tmp2, in_out);
10335   shrl(tmp2, 16);
10336   andl(tmp2, 0x000000FF);
10337   shll(tmp2, 3);
10338   addl(tmp2, tmp3);
10339   movq(xtmp2, Address(tmp2, 0));
10340 
10341   psllq(xtmp2, 16);
10342   pxor(xtmp1, xtmp2);
10343 
10344   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10345   shrl(in_out, 24);
10346   andl(in_out, 0x000000FF);
10347   shll(in_out, 3);
10348   addl(in_out, tmp3);
10349   movq(xtmp2, Address(in_out, 0));
10350 
10351   psllq(xtmp2, 24);
10352   pxor(xtmp1, xtmp2); // Result in CXMM
10353   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10354 }
10355 
10356 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10357                                       Register in_out,
10358                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10359                                       XMMRegister w_xtmp2,
10360                                       Register tmp1,
10361                                       Register n_tmp2, Register n_tmp3) {
10362   if (is_pclmulqdq_supported) {
10363     movdl(w_xtmp1, in_out);
10364 
10365     movl(tmp1, const_or_pre_comp_const_index);
10366     movdl(w_xtmp2, tmp1);
10367     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10368     // Keep result in XMM since GPR is 32 bit in length
10369   } else {
10370     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10371   }
10372 }
10373 
10374 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,
10375                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10376                                      Register tmp1, Register tmp2,
10377                                      Register n_tmp3) {
10378   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10379   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10380 
10381   psllq(w_xtmp1, 1);
10382   movdl(tmp1, w_xtmp1);
10383   psrlq(w_xtmp1, 32);
10384   movdl(in_out, w_xtmp1);
10385 
10386   xorl(tmp2, tmp2);
10387   crc32(tmp2, tmp1, 4);
10388   xorl(in_out, tmp2);
10389 
10390   psllq(w_xtmp2, 1);
10391   movdl(tmp1, w_xtmp2);
10392   psrlq(w_xtmp2, 32);
10393   movdl(in1, w_xtmp2);
10394 
10395   xorl(tmp2, tmp2);
10396   crc32(tmp2, tmp1, 4);
10397   xorl(in1, tmp2);
10398   xorl(in_out, in1);
10399   xorl(in_out, in2);
10400 }
10401 
10402 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,
10403                                        Register in_out1, Register in_out2, Register in_out3,
10404                                        Register tmp1, Register tmp2, Register tmp3,
10405                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10406                                        Register tmp4, Register tmp5,
10407                                        Register n_tmp6) {
10408   Label L_processPartitions;
10409   Label L_processPartition;
10410   Label L_exit;
10411 
10412   bind(L_processPartitions);
10413   cmpl(in_out1, 3 * size);
10414   jcc(Assembler::less, L_exit);
10415     xorl(tmp1, tmp1);
10416     xorl(tmp2, tmp2);
10417     movl(tmp3, in_out2);
10418     addl(tmp3, size);
10419 
10420     bind(L_processPartition);
10421       crc32(in_out3, Address(in_out2, 0), 4);
10422       crc32(tmp1, Address(in_out2, size), 4);
10423       crc32(tmp2, Address(in_out2, size*2), 4);
10424       crc32(in_out3, Address(in_out2, 0+4), 4);
10425       crc32(tmp1, Address(in_out2, size+4), 4);
10426       crc32(tmp2, Address(in_out2, size*2+4), 4);
10427       addl(in_out2, 8);
10428       cmpl(in_out2, tmp3);
10429       jcc(Assembler::less, L_processPartition);
10430 
10431         push(tmp3);
10432         push(in_out1);
10433         push(in_out2);
10434         tmp4 = tmp3;
10435         tmp5 = in_out1;
10436         n_tmp6 = in_out2;
10437 
10438       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10439             w_xtmp1, w_xtmp2, w_xtmp3,
10440             tmp4, tmp5,
10441             n_tmp6);
10442 
10443         pop(in_out2);
10444         pop(in_out1);
10445         pop(tmp3);
10446 
10447     addl(in_out2, 2 * size);
10448     subl(in_out1, 3 * size);
10449     jmp(L_processPartitions);
10450 
10451   bind(L_exit);
10452 }
10453 #endif //LP64
10454 
10455 #ifdef _LP64
10456 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10457 // Input: A buffer I of L bytes.
10458 // Output: the CRC32C value of the buffer.
10459 // Notations:
10460 // Write L = 24N + r, with N = floor (L/24).
10461 // r = L mod 24 (0 <= r < 24).
10462 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10463 // N quadwords, and R consists of r bytes.
10464 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10465 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10466 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10467 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10468 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10469                                           Register tmp1, Register tmp2, Register tmp3,
10470                                           Register tmp4, Register tmp5, Register tmp6,
10471                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10472                                           bool is_pclmulqdq_supported) {
10473   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10474   Label L_wordByWord;
10475   Label L_byteByByteProlog;
10476   Label L_byteByByte;
10477   Label L_exit;
10478 
10479   if (is_pclmulqdq_supported ) {
10480     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10481     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10482 
10483     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10484     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10485 
10486     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10487     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10488     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10489   } else {
10490     const_or_pre_comp_const_index[0] = 1;
10491     const_or_pre_comp_const_index[1] = 0;
10492 
10493     const_or_pre_comp_const_index[2] = 3;
10494     const_or_pre_comp_const_index[3] = 2;
10495 
10496     const_or_pre_comp_const_index[4] = 5;
10497     const_or_pre_comp_const_index[5] = 4;
10498    }
10499   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10500                     in2, in1, in_out,
10501                     tmp1, tmp2, tmp3,
10502                     w_xtmp1, w_xtmp2, w_xtmp3,
10503                     tmp4, tmp5,
10504                     tmp6);
10505   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10506                     in2, in1, in_out,
10507                     tmp1, tmp2, tmp3,
10508                     w_xtmp1, w_xtmp2, w_xtmp3,
10509                     tmp4, tmp5,
10510                     tmp6);
10511   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10512                     in2, in1, in_out,
10513                     tmp1, tmp2, tmp3,
10514                     w_xtmp1, w_xtmp2, w_xtmp3,
10515                     tmp4, tmp5,
10516                     tmp6);
10517   movl(tmp1, in2);
10518   andl(tmp1, 0x00000007);
10519   negl(tmp1);
10520   addl(tmp1, in2);
10521   addq(tmp1, in1);
10522 
10523   BIND(L_wordByWord);
10524   cmpq(in1, tmp1);
10525   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10526     crc32(in_out, Address(in1, 0), 4);
10527     addq(in1, 4);
10528     jmp(L_wordByWord);
10529 
10530   BIND(L_byteByByteProlog);
10531   andl(in2, 0x00000007);
10532   movl(tmp2, 1);
10533 
10534   BIND(L_byteByByte);
10535   cmpl(tmp2, in2);
10536   jccb(Assembler::greater, L_exit);
10537     crc32(in_out, Address(in1, 0), 1);
10538     incq(in1);
10539     incl(tmp2);
10540     jmp(L_byteByByte);
10541 
10542   BIND(L_exit);
10543 }
10544 #else
10545 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10546                                           Register tmp1, Register  tmp2, Register tmp3,
10547                                           Register tmp4, Register  tmp5, Register tmp6,
10548                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10549                                           bool is_pclmulqdq_supported) {
10550   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10551   Label L_wordByWord;
10552   Label L_byteByByteProlog;
10553   Label L_byteByByte;
10554   Label L_exit;
10555 
10556   if (is_pclmulqdq_supported) {
10557     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10558     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10559 
10560     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10561     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10562 
10563     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10564     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10565   } else {
10566     const_or_pre_comp_const_index[0] = 1;
10567     const_or_pre_comp_const_index[1] = 0;
10568 
10569     const_or_pre_comp_const_index[2] = 3;
10570     const_or_pre_comp_const_index[3] = 2;
10571 
10572     const_or_pre_comp_const_index[4] = 5;
10573     const_or_pre_comp_const_index[5] = 4;
10574   }
10575   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10576                     in2, in1, in_out,
10577                     tmp1, tmp2, tmp3,
10578                     w_xtmp1, w_xtmp2, w_xtmp3,
10579                     tmp4, tmp5,
10580                     tmp6);
10581   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10582                     in2, in1, in_out,
10583                     tmp1, tmp2, tmp3,
10584                     w_xtmp1, w_xtmp2, w_xtmp3,
10585                     tmp4, tmp5,
10586                     tmp6);
10587   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10588                     in2, in1, in_out,
10589                     tmp1, tmp2, tmp3,
10590                     w_xtmp1, w_xtmp2, w_xtmp3,
10591                     tmp4, tmp5,
10592                     tmp6);
10593   movl(tmp1, in2);
10594   andl(tmp1, 0x00000007);
10595   negl(tmp1);
10596   addl(tmp1, in2);
10597   addl(tmp1, in1);
10598 
10599   BIND(L_wordByWord);
10600   cmpl(in1, tmp1);
10601   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10602     crc32(in_out, Address(in1,0), 4);
10603     addl(in1, 4);
10604     jmp(L_wordByWord);
10605 
10606   BIND(L_byteByByteProlog);
10607   andl(in2, 0x00000007);
10608   movl(tmp2, 1);
10609 
10610   BIND(L_byteByByte);
10611   cmpl(tmp2, in2);
10612   jccb(Assembler::greater, L_exit);
10613     movb(tmp1, Address(in1, 0));
10614     crc32(in_out, tmp1, 1);
10615     incl(in1);
10616     incl(tmp2);
10617     jmp(L_byteByByte);
10618 
10619   BIND(L_exit);
10620 }
10621 #endif // LP64
10622 #undef BIND
10623 #undef BLOCK_COMMENT
10624 
10625 
10626 // Compress char[] array to byte[].
10627 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10628                                          XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10629                                          XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10630                                          Register tmp5, Register result) {
10631   Label copy_chars_loop, return_length, return_zero, done;
10632 
10633   // rsi: src
10634   // rdi: dst
10635   // rdx: len
10636   // rcx: tmp5
10637   // rax: result
10638 
10639   // rsi holds start addr of source char[] to be compressed
10640   // rdi holds start addr of destination byte[]
10641   // rdx holds length
10642 
10643   assert(len != result, "");
10644 
10645   // save length for return
10646   push(len);
10647 
10648   if (UseSSE42Intrinsics) {
10649     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10650     Label copy_32_loop, copy_16, copy_tail;
10651 
10652     movl(result, len);
10653     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10654 
10655     // vectored compression
10656     andl(len, 0xfffffff0);    // vector count (in chars)
10657     andl(result, 0x0000000f);    // tail count (in chars)
10658     testl(len, len);
10659     jccb(Assembler::zero, copy_16);
10660 
10661     // compress 16 chars per iter
10662     movdl(tmp1Reg, tmp5);
10663     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10664     pxor(tmp4Reg, tmp4Reg);
10665 
10666     lea(src, Address(src, len, Address::times_2));
10667     lea(dst, Address(dst, len, Address::times_1));
10668     negptr(len);
10669 
10670     bind(copy_32_loop);
10671     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10672     por(tmp4Reg, tmp2Reg);
10673     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10674     por(tmp4Reg, tmp3Reg);
10675     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10676     jcc(Assembler::notZero, return_zero);
10677     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10678     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10679     addptr(len, 16);
10680     jcc(Assembler::notZero, copy_32_loop);
10681 
10682     // compress next vector of 8 chars (if any)
10683     bind(copy_16);
10684     movl(len, result);
10685     andl(len, 0xfffffff8);    // vector count (in chars)
10686     andl(result, 0x00000007);    // tail count (in chars)
10687     testl(len, len);
10688     jccb(Assembler::zero, copy_tail);
10689 
10690     movdl(tmp1Reg, tmp5);
10691     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10692     pxor(tmp3Reg, tmp3Reg);
10693 
10694     movdqu(tmp2Reg, Address(src, 0));
10695     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10696     jccb(Assembler::notZero, return_zero);
10697     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10698     movq(Address(dst, 0), tmp2Reg);
10699     addptr(src, 16);
10700     addptr(dst, 8);
10701 
10702     bind(copy_tail);
10703     movl(len, result);
10704   }
10705   // compress 1 char per iter
10706   testl(len, len);
10707   jccb(Assembler::zero, return_length);
10708   lea(src, Address(src, len, Address::times_2));
10709   lea(dst, Address(dst, len, Address::times_1));
10710   negptr(len);
10711 
10712   bind(copy_chars_loop);
10713   load_unsigned_short(result, Address(src, len, Address::times_2));
10714   testl(result, 0xff00);      // check if Unicode char
10715   jccb(Assembler::notZero, return_zero);
10716   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10717   increment(len);
10718   jcc(Assembler::notZero, copy_chars_loop);
10719 
10720   // if compression succeeded, return length
10721   bind(return_length);
10722   pop(result);
10723   jmpb(done);
10724 
10725   // if compression failed, return 0
10726   bind(return_zero);
10727   xorl(result, result);
10728   addptr(rsp, wordSize);
10729 
10730   bind(done);
10731 }
10732 
10733 // Inflate byte[] array to char[].
10734 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10735                                         XMMRegister tmp1, Register tmp2) {
10736   Label copy_chars_loop, done;
10737 
10738   // rsi: src
10739   // rdi: dst
10740   // rdx: len
10741   // rcx: tmp2
10742 
10743   // rsi holds start addr of source byte[] to be inflated
10744   // rdi holds start addr of destination char[]
10745   // rdx holds length
10746   assert_different_registers(src, dst, len, tmp2);
10747 
10748   if (UseSSE42Intrinsics) {
10749     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10750     Label copy_8_loop, copy_bytes, copy_tail;
10751 
10752     movl(tmp2, len);
10753     andl(tmp2, 0x00000007);   // tail count (in chars)
10754     andl(len, 0xfffffff8);    // vector count (in chars)
10755     jccb(Assembler::zero, copy_tail);
10756 
10757     // vectored inflation
10758     lea(src, Address(src, len, Address::times_1));
10759     lea(dst, Address(dst, len, Address::times_2));
10760     negptr(len);
10761 
10762     // inflate 8 chars per iter
10763     bind(copy_8_loop);
10764     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10765     movdqu(Address(dst, len, Address::times_2), tmp1);
10766     addptr(len, 8);
10767     jcc(Assembler::notZero, copy_8_loop);
10768 
10769     bind(copy_tail);
10770     movl(len, tmp2);
10771 
10772     cmpl(len, 4);
10773     jccb(Assembler::less, copy_bytes);
10774 
10775     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10776     pmovzxbw(tmp1, tmp1);
10777     movq(Address(dst, 0), tmp1);
10778     subptr(len, 4);
10779     addptr(src, 4);
10780     addptr(dst, 8);
10781 
10782     bind(copy_bytes);
10783   }
10784   testl(len, len);
10785   jccb(Assembler::zero, done);
10786   lea(src, Address(src, len, Address::times_1));
10787   lea(dst, Address(dst, len, Address::times_2));
10788   negptr(len);
10789 
10790   // inflate 1 char per iter
10791   bind(copy_chars_loop);
10792   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10793   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10794   increment(len);
10795   jcc(Assembler::notZero, copy_chars_loop);
10796 
10797   bind(done);
10798 }
10799 
10800 
10801 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10802   switch (cond) {
10803     // Note some conditions are synonyms for others
10804     case Assembler::zero:         return Assembler::notZero;
10805     case Assembler::notZero:      return Assembler::zero;
10806     case Assembler::less:         return Assembler::greaterEqual;
10807     case Assembler::lessEqual:    return Assembler::greater;
10808     case Assembler::greater:      return Assembler::lessEqual;
10809     case Assembler::greaterEqual: return Assembler::less;
10810     case Assembler::below:        return Assembler::aboveEqual;
10811     case Assembler::belowEqual:   return Assembler::above;
10812     case Assembler::above:        return Assembler::belowEqual;
10813     case Assembler::aboveEqual:   return Assembler::below;
10814     case Assembler::overflow:     return Assembler::noOverflow;
10815     case Assembler::noOverflow:   return Assembler::overflow;
10816     case Assembler::negative:     return Assembler::positive;
10817     case Assembler::positive:     return Assembler::negative;
10818     case Assembler::parity:       return Assembler::noParity;
10819     case Assembler::noParity:     return Assembler::parity;
10820   }
10821   ShouldNotReachHere(); return Assembler::overflow;
10822 }
10823 
10824 SkipIfEqual::SkipIfEqual(
10825     MacroAssembler* masm, const bool* flag_addr, bool value) {
10826   _masm = masm;
10827   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10828   _masm->jcc(Assembler::equal, _label);
10829 }
10830 
10831 SkipIfEqual::~SkipIfEqual() {
10832   _masm->bind(_label);
10833 }