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::sqrtsd(XMMRegister dst, AddressLiteral src) {
3962   if (reachable(src)) {
3963     Assembler::sqrtsd(dst, as_Address(src));
3964   } else {
3965     lea(rscratch1, src);
3966     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3967   }
3968 }
3969 
3970 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3971   if (reachable(src)) {
3972     Assembler::sqrtss(dst, as_Address(src));
3973   } else {
3974     lea(rscratch1, src);
3975     Assembler::sqrtss(dst, Address(rscratch1, 0));
3976   }
3977 }
3978 
3979 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3980   if (reachable(src)) {
3981     Assembler::subsd(dst, as_Address(src));
3982   } else {
3983     lea(rscratch1, src);
3984     Assembler::subsd(dst, Address(rscratch1, 0));
3985   }
3986 }
3987 
3988 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3989   if (reachable(src)) {
3990     Assembler::subss(dst, as_Address(src));
3991   } else {
3992     lea(rscratch1, src);
3993     Assembler::subss(dst, Address(rscratch1, 0));
3994   }
3995 }
3996 
3997 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
3998   if (reachable(src)) {
3999     Assembler::ucomisd(dst, as_Address(src));
4000   } else {
4001     lea(rscratch1, src);
4002     Assembler::ucomisd(dst, Address(rscratch1, 0));
4003   }
4004 }
4005 
4006 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4007   if (reachable(src)) {
4008     Assembler::ucomiss(dst, as_Address(src));
4009   } else {
4010     lea(rscratch1, src);
4011     Assembler::ucomiss(dst, Address(rscratch1, 0));
4012   }
4013 }
4014 
4015 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4016   // Used in sign-bit flipping with aligned address.
4017   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4018   if (reachable(src)) {
4019     Assembler::xorpd(dst, as_Address(src));
4020   } else {
4021     lea(rscratch1, src);
4022     Assembler::xorpd(dst, Address(rscratch1, 0));
4023   }
4024 }
4025 
4026 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4027   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4028     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4029   }
4030   else {
4031     Assembler::xorpd(dst, src);
4032   }
4033 }
4034 
4035 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4036   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4037     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4038   } else {
4039     Assembler::xorps(dst, src);
4040   }
4041 }
4042 
4043 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4044   // Used in sign-bit flipping with aligned address.
4045   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4046   if (reachable(src)) {
4047     Assembler::xorps(dst, as_Address(src));
4048   } else {
4049     lea(rscratch1, src);
4050     Assembler::xorps(dst, Address(rscratch1, 0));
4051   }
4052 }
4053 
4054 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4055   // Used in sign-bit flipping with aligned address.
4056   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4057   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4058   if (reachable(src)) {
4059     Assembler::pshufb(dst, as_Address(src));
4060   } else {
4061     lea(rscratch1, src);
4062     Assembler::pshufb(dst, Address(rscratch1, 0));
4063   }
4064 }
4065 
4066 // AVX 3-operands instructions
4067 
4068 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4069   if (reachable(src)) {
4070     vaddsd(dst, nds, as_Address(src));
4071   } else {
4072     lea(rscratch1, src);
4073     vaddsd(dst, nds, Address(rscratch1, 0));
4074   }
4075 }
4076 
4077 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4078   if (reachable(src)) {
4079     vaddss(dst, nds, as_Address(src));
4080   } else {
4081     lea(rscratch1, src);
4082     vaddss(dst, nds, Address(rscratch1, 0));
4083   }
4084 }
4085 
4086 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4087   int dst_enc = dst->encoding();
4088   int nds_enc = nds->encoding();
4089   int src_enc = src->encoding();
4090   if ((dst_enc < 16) && (nds_enc < 16)) {
4091     vandps(dst, nds, negate_field, vector_len);
4092   } else if ((src_enc < 16) && (dst_enc < 16)) {
4093     movss(src, nds);
4094     vandps(dst, src, negate_field, vector_len);
4095   } else if (src_enc < 16) {
4096     movss(src, nds);
4097     vandps(src, src, negate_field, vector_len);
4098     movss(dst, src);
4099   } else if (dst_enc < 16) {
4100     movdqu(src, xmm0);
4101     movss(xmm0, nds);
4102     vandps(dst, xmm0, negate_field, vector_len);
4103     movdqu(xmm0, src);
4104   } else if (nds_enc < 16) {
4105     movdqu(src, xmm0);
4106     vandps(xmm0, nds, negate_field, vector_len);
4107     movss(dst, xmm0);
4108     movdqu(xmm0, src);
4109   } else {
4110     movdqu(src, xmm0);
4111     movss(xmm0, nds);
4112     vandps(xmm0, xmm0, negate_field, vector_len);
4113     movss(dst, xmm0);
4114     movdqu(xmm0, src);
4115   }
4116 }
4117 
4118 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4119   int dst_enc = dst->encoding();
4120   int nds_enc = nds->encoding();
4121   int src_enc = src->encoding();
4122   if ((dst_enc < 16) && (nds_enc < 16)) {
4123     vandpd(dst, nds, negate_field, vector_len);
4124   } else if ((src_enc < 16) && (dst_enc < 16)) {
4125     movsd(src, nds);
4126     vandpd(dst, src, negate_field, vector_len);
4127   } else if (src_enc < 16) {
4128     movsd(src, nds);
4129     vandpd(src, src, negate_field, vector_len);
4130     movsd(dst, src);
4131   } else if (dst_enc < 16) {
4132     movdqu(src, xmm0);
4133     movsd(xmm0, nds);
4134     vandpd(dst, xmm0, negate_field, vector_len);
4135     movdqu(xmm0, src);
4136   } else if (nds_enc < 16) {
4137     movdqu(src, xmm0);
4138     vandpd(xmm0, nds, negate_field, vector_len);
4139     movsd(dst, xmm0);
4140     movdqu(xmm0, src);
4141   } else {
4142     movdqu(src, xmm0);
4143     movsd(xmm0, nds);
4144     vandpd(xmm0, xmm0, negate_field, vector_len);
4145     movsd(dst, xmm0);
4146     movdqu(xmm0, src);
4147   }
4148 }
4149 
4150 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4151   int dst_enc = dst->encoding();
4152   int nds_enc = nds->encoding();
4153   int src_enc = src->encoding();
4154   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4155     Assembler::vpaddb(dst, nds, src, vector_len);
4156   } else if ((dst_enc < 16) && (src_enc < 16)) {
4157     Assembler::vpaddb(dst, dst, src, vector_len);
4158   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4159     // use nds as scratch for src
4160     evmovdqul(nds, src, Assembler::AVX_512bit);
4161     Assembler::vpaddb(dst, dst, nds, vector_len);
4162   } else if ((src_enc < 16) && (nds_enc < 16)) {
4163     // use nds as scratch for dst
4164     evmovdqul(nds, dst, Assembler::AVX_512bit);
4165     Assembler::vpaddb(nds, nds, src, vector_len);
4166     evmovdqul(dst, nds, Assembler::AVX_512bit);
4167   } else if (dst_enc < 16) {
4168     // use nds as scatch for xmm0 to hold src
4169     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4170     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4171     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4172     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4173   } else {
4174     // worse case scenario, all regs are in the upper bank
4175     subptr(rsp, 64);
4176     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4177     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4178     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4179     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4180     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4181     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4182     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4183     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4184     addptr(rsp, 64);
4185   }
4186 }
4187 
4188 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4189   int dst_enc = dst->encoding();
4190   int nds_enc = nds->encoding();
4191   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4192     Assembler::vpaddb(dst, nds, src, vector_len);
4193   } else if (dst_enc < 16) {
4194     Assembler::vpaddb(dst, dst, src, vector_len);
4195   } else if (nds_enc < 16) {
4196     // implies dst_enc in upper bank with src as scratch
4197     evmovdqul(nds, dst, Assembler::AVX_512bit);
4198     Assembler::vpaddb(nds, nds, src, vector_len);
4199     evmovdqul(dst, nds, Assembler::AVX_512bit);
4200   } else {
4201     // worse case scenario, all regs in upper bank
4202     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4203     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4204     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4205     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4206   }
4207 }
4208 
4209 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4210   int dst_enc = dst->encoding();
4211   int nds_enc = nds->encoding();
4212   int src_enc = src->encoding();
4213   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4214     Assembler::vpaddw(dst, nds, src, vector_len);
4215   } else if ((dst_enc < 16) && (src_enc < 16)) {
4216     Assembler::vpaddw(dst, dst, src, vector_len);
4217   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4218     // use nds as scratch for src
4219     evmovdqul(nds, src, Assembler::AVX_512bit);
4220     Assembler::vpaddw(dst, dst, nds, vector_len);
4221   } else if ((src_enc < 16) && (nds_enc < 16)) {
4222     // use nds as scratch for dst
4223     evmovdqul(nds, dst, Assembler::AVX_512bit);
4224     Assembler::vpaddw(nds, nds, src, vector_len);
4225     evmovdqul(dst, nds, Assembler::AVX_512bit);
4226   } else if (dst_enc < 16) {
4227     // use nds as scatch for xmm0 to hold src
4228     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4229     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4230     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4231     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4232   } else {
4233     // worse case scenario, all regs are in the upper bank
4234     subptr(rsp, 64);
4235     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4236     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4237     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4238     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4239     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4240     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4241     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4242     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4243     addptr(rsp, 64);
4244   }
4245 }
4246 
4247 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4248   int dst_enc = dst->encoding();
4249   int nds_enc = nds->encoding();
4250   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4251     Assembler::vpaddw(dst, nds, src, vector_len);
4252   } else if (dst_enc < 16) {
4253     Assembler::vpaddw(dst, dst, src, vector_len);
4254   } else if (nds_enc < 16) {
4255     // implies dst_enc in upper bank with src as scratch
4256     evmovdqul(nds, dst, Assembler::AVX_512bit);
4257     Assembler::vpaddw(nds, nds, src, vector_len);
4258     evmovdqul(dst, nds, Assembler::AVX_512bit);
4259   } else {
4260     // worse case scenario, all regs in upper bank
4261     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4262     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4263     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4264     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4265   }
4266 }
4267 
4268 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4269   int dst_enc = dst->encoding();
4270   int nds_enc = nds->encoding();
4271   int src_enc = src->encoding();
4272   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4273     Assembler::vpsubb(dst, nds, src, vector_len);
4274   } else if ((dst_enc < 16) && (src_enc < 16)) {
4275     Assembler::vpsubb(dst, dst, src, vector_len);
4276   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4277     // use nds as scratch for src
4278     evmovdqul(nds, src, Assembler::AVX_512bit);
4279     Assembler::vpsubb(dst, dst, nds, vector_len);
4280   } else if ((src_enc < 16) && (nds_enc < 16)) {
4281     // use nds as scratch for dst
4282     evmovdqul(nds, dst, Assembler::AVX_512bit);
4283     Assembler::vpsubb(nds, nds, src, vector_len);
4284     evmovdqul(dst, nds, Assembler::AVX_512bit);
4285   } else if (dst_enc < 16) {
4286     // use nds as scatch for xmm0 to hold src
4287     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4288     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4289     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4290     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4291   } else {
4292     // worse case scenario, all regs are in the upper bank
4293     subptr(rsp, 64);
4294     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4295     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4296     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4297     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4298     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4299     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4300     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4301     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4302     addptr(rsp, 64);
4303   }
4304 }
4305 
4306 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4307   int dst_enc = dst->encoding();
4308   int nds_enc = nds->encoding();
4309   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4310     Assembler::vpsubb(dst, nds, src, vector_len);
4311   } else if (dst_enc < 16) {
4312     Assembler::vpsubb(dst, dst, src, vector_len);
4313   } else if (nds_enc < 16) {
4314     // implies dst_enc in upper bank with src as scratch
4315     evmovdqul(nds, dst, Assembler::AVX_512bit);
4316     Assembler::vpsubb(nds, nds, src, vector_len);
4317     evmovdqul(dst, nds, Assembler::AVX_512bit);
4318   } else {
4319     // worse case scenario, all regs in upper bank
4320     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4321     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4322     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4323     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4324   }
4325 }
4326 
4327 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4328   int dst_enc = dst->encoding();
4329   int nds_enc = nds->encoding();
4330   int src_enc = src->encoding();
4331   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4332     Assembler::vpsubw(dst, nds, src, vector_len);
4333   } else if ((dst_enc < 16) && (src_enc < 16)) {
4334     Assembler::vpsubw(dst, dst, src, vector_len);
4335   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4336     // use nds as scratch for src
4337     evmovdqul(nds, src, Assembler::AVX_512bit);
4338     Assembler::vpsubw(dst, dst, nds, vector_len);
4339   } else if ((src_enc < 16) && (nds_enc < 16)) {
4340     // use nds as scratch for dst
4341     evmovdqul(nds, dst, Assembler::AVX_512bit);
4342     Assembler::vpsubw(nds, nds, src, vector_len);
4343     evmovdqul(dst, nds, Assembler::AVX_512bit);
4344   } else if (dst_enc < 16) {
4345     // use nds as scatch for xmm0 to hold src
4346     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4347     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4348     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4349     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4350   } else {
4351     // worse case scenario, all regs are in the upper bank
4352     subptr(rsp, 64);
4353     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4354     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4355     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4356     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4357     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4358     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4359     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4360     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4361     addptr(rsp, 64);
4362   }
4363 }
4364 
4365 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4366   int dst_enc = dst->encoding();
4367   int nds_enc = nds->encoding();
4368   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4369     Assembler::vpsubw(dst, nds, src, vector_len);
4370   } else if (dst_enc < 16) {
4371     Assembler::vpsubw(dst, dst, src, vector_len);
4372   } else if (nds_enc < 16) {
4373     // implies dst_enc in upper bank with src as scratch
4374     evmovdqul(nds, dst, Assembler::AVX_512bit);
4375     Assembler::vpsubw(nds, nds, src, vector_len);
4376     evmovdqul(dst, nds, Assembler::AVX_512bit);
4377   } else {
4378     // worse case scenario, all regs in upper bank
4379     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4380     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4381     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4382     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4383   }
4384 }
4385 
4386 
4387 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4388   int dst_enc = dst->encoding();
4389   int nds_enc = nds->encoding();
4390   int src_enc = src->encoding();
4391   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4392     Assembler::vpmullw(dst, nds, src, vector_len);
4393   } else if ((dst_enc < 16) && (src_enc < 16)) {
4394     Assembler::vpmullw(dst, dst, src, vector_len);
4395   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4396     // use nds as scratch for src
4397     evmovdqul(nds, src, Assembler::AVX_512bit);
4398     Assembler::vpmullw(dst, dst, nds, vector_len);
4399   } else if ((src_enc < 16) && (nds_enc < 16)) {
4400     // use nds as scratch for dst
4401     evmovdqul(nds, dst, Assembler::AVX_512bit);
4402     Assembler::vpmullw(nds, nds, src, vector_len);
4403     evmovdqul(dst, nds, Assembler::AVX_512bit);
4404   } else if (dst_enc < 16) {
4405     // use nds as scatch for xmm0 to hold src
4406     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4407     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4408     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4409     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4410   } else {
4411     // worse case scenario, all regs are in the upper bank
4412     subptr(rsp, 64);
4413     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4414     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4415     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4416     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4417     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4418     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4419     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4420     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4421     addptr(rsp, 64);
4422   }
4423 }
4424 
4425 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4426   int dst_enc = dst->encoding();
4427   int nds_enc = nds->encoding();
4428   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4429     Assembler::vpmullw(dst, nds, src, vector_len);
4430   } else if (dst_enc < 16) {
4431     Assembler::vpmullw(dst, dst, src, vector_len);
4432   } else if (nds_enc < 16) {
4433     // implies dst_enc in upper bank with src as scratch
4434     evmovdqul(nds, dst, Assembler::AVX_512bit);
4435     Assembler::vpmullw(nds, nds, src, vector_len);
4436     evmovdqul(dst, nds, Assembler::AVX_512bit);
4437   } else {
4438     // worse case scenario, all regs in upper bank
4439     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4440     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4441     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4442     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4443   }
4444 }
4445 
4446 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4447   int dst_enc = dst->encoding();
4448   int nds_enc = nds->encoding();
4449   int shift_enc = shift->encoding();
4450   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4451     Assembler::vpsraw(dst, nds, shift, vector_len);
4452   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4453     Assembler::vpsraw(dst, dst, shift, vector_len);
4454   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4455     // use nds_enc as scratch with shift
4456     evmovdqul(nds, shift, Assembler::AVX_512bit);
4457     Assembler::vpsraw(dst, dst, nds, vector_len);
4458   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4459     // use nds as scratch with dst
4460     evmovdqul(nds, dst, Assembler::AVX_512bit);
4461     Assembler::vpsraw(nds, nds, shift, vector_len);
4462     evmovdqul(dst, nds, Assembler::AVX_512bit);
4463   } else if (dst_enc < 16) {
4464     // use nds to save a copy of xmm0 and hold shift
4465     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4466     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4467     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4468     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4469   } else if (nds_enc < 16) {
4470     // use nds as dest as temps
4471     evmovdqul(nds, dst, Assembler::AVX_512bit);
4472     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4473     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4474     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4475     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4476     evmovdqul(dst, nds, Assembler::AVX_512bit);
4477   } else {
4478     // worse case scenario, all regs are in the upper bank
4479     subptr(rsp, 64);
4480     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4481     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4482     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4483     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4484     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4485     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4486     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4487     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4488     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4489     addptr(rsp, 64);
4490   }
4491 }
4492 
4493 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4494   int dst_enc = dst->encoding();
4495   int nds_enc = nds->encoding();
4496   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4497     Assembler::vpsraw(dst, nds, shift, vector_len);
4498   } else if (dst_enc < 16) {
4499     Assembler::vpsraw(dst, dst, shift, vector_len);
4500   } else if (nds_enc < 16) {
4501     // use nds as scratch
4502     evmovdqul(nds, dst, Assembler::AVX_512bit);
4503     Assembler::vpsraw(nds, nds, shift, vector_len);
4504     evmovdqul(dst, nds, Assembler::AVX_512bit);
4505   } else {
4506     // use nds as scratch for xmm0
4507     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4508     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4509     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4510     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4511   }
4512 }
4513 
4514 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4515   int dst_enc = dst->encoding();
4516   int nds_enc = nds->encoding();
4517   int shift_enc = shift->encoding();
4518   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4519     Assembler::vpsrlw(dst, nds, shift, vector_len);
4520   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4521     Assembler::vpsrlw(dst, dst, shift, vector_len);
4522   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4523     // use nds_enc as scratch with shift
4524     evmovdqul(nds, shift, Assembler::AVX_512bit);
4525     Assembler::vpsrlw(dst, dst, nds, vector_len);
4526   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4527     // use nds as scratch with dst
4528     evmovdqul(nds, dst, Assembler::AVX_512bit);
4529     Assembler::vpsrlw(nds, nds, shift, vector_len);
4530     evmovdqul(dst, nds, Assembler::AVX_512bit);
4531   } else if (dst_enc < 16) {
4532     // use nds to save a copy of xmm0 and hold shift
4533     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4534     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4535     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4536     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4537   } else if (nds_enc < 16) {
4538     // use nds as dest as temps
4539     evmovdqul(nds, dst, Assembler::AVX_512bit);
4540     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4541     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4542     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4543     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4544     evmovdqul(dst, nds, Assembler::AVX_512bit);
4545   } else {
4546     // worse case scenario, all regs are in the upper bank
4547     subptr(rsp, 64);
4548     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4549     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4550     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4551     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4552     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4553     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4554     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4555     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4556     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4557     addptr(rsp, 64);
4558   }
4559 }
4560 
4561 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4562   int dst_enc = dst->encoding();
4563   int nds_enc = nds->encoding();
4564   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4565     Assembler::vpsrlw(dst, nds, shift, vector_len);
4566   } else if (dst_enc < 16) {
4567     Assembler::vpsrlw(dst, dst, shift, vector_len);
4568   } else if (nds_enc < 16) {
4569     // use nds as scratch
4570     evmovdqul(nds, dst, Assembler::AVX_512bit);
4571     Assembler::vpsrlw(nds, nds, shift, vector_len);
4572     evmovdqul(dst, nds, Assembler::AVX_512bit);
4573   } else {
4574     // use nds as scratch for xmm0
4575     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4576     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4577     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4578     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4579   }
4580 }
4581 
4582 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4583   int dst_enc = dst->encoding();
4584   int nds_enc = nds->encoding();
4585   int shift_enc = shift->encoding();
4586   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4587     Assembler::vpsllw(dst, nds, shift, vector_len);
4588   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4589     Assembler::vpsllw(dst, dst, shift, vector_len);
4590   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4591     // use nds_enc as scratch with shift
4592     evmovdqul(nds, shift, Assembler::AVX_512bit);
4593     Assembler::vpsllw(dst, dst, nds, vector_len);
4594   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4595     // use nds as scratch with dst
4596     evmovdqul(nds, dst, Assembler::AVX_512bit);
4597     Assembler::vpsllw(nds, nds, shift, vector_len);
4598     evmovdqul(dst, nds, Assembler::AVX_512bit);
4599   } else if (dst_enc < 16) {
4600     // use nds to save a copy of xmm0 and hold shift
4601     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4603     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4604     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4605   } else if (nds_enc < 16) {
4606     // use nds as dest as temps
4607     evmovdqul(nds, dst, Assembler::AVX_512bit);
4608     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4609     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4610     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4611     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4612     evmovdqul(dst, nds, Assembler::AVX_512bit);
4613   } else {
4614     // worse case scenario, all regs are in the upper bank
4615     subptr(rsp, 64);
4616     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4617     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4618     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4619     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4620     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4621     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4622     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4623     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4624     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4625     addptr(rsp, 64);
4626   }
4627 }
4628 
4629 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4630   int dst_enc = dst->encoding();
4631   int nds_enc = nds->encoding();
4632   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4633     Assembler::vpsllw(dst, nds, shift, vector_len);
4634   } else if (dst_enc < 16) {
4635     Assembler::vpsllw(dst, dst, shift, vector_len);
4636   } else if (nds_enc < 16) {
4637     // use nds as scratch
4638     evmovdqul(nds, dst, Assembler::AVX_512bit);
4639     Assembler::vpsllw(nds, nds, shift, vector_len);
4640     evmovdqul(dst, nds, Assembler::AVX_512bit);
4641   } else {
4642     // use nds as scratch for xmm0
4643     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4644     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4645     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4646     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4647   }
4648 }
4649 
4650 // This instruction exists within macros, ergo we cannot control its input
4651 // when emitted through those patterns.
4652 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4653   if (VM_Version::supports_avx512nobw()) {
4654     int dst_enc = dst->encoding();
4655     int src_enc = src->encoding();
4656     if (dst_enc == src_enc) {
4657       if (dst_enc < 16) {
4658         Assembler::punpcklbw(dst, src);
4659       } else {
4660         subptr(rsp, 64);
4661         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4662         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4663         Assembler::punpcklbw(xmm0, xmm0);
4664         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4665         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4666         addptr(rsp, 64);
4667       }
4668     } else {
4669       if ((src_enc < 16) && (dst_enc < 16)) {
4670         Assembler::punpcklbw(dst, src);
4671       } else if (src_enc < 16) {
4672         subptr(rsp, 64);
4673         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4674         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4675         Assembler::punpcklbw(xmm0, src);
4676         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4677         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4678         addptr(rsp, 64);
4679       } else if (dst_enc < 16) {
4680         subptr(rsp, 64);
4681         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4682         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4683         Assembler::punpcklbw(dst, xmm0);
4684         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4685         addptr(rsp, 64);
4686       } else {
4687         subptr(rsp, 64);
4688         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4689         subptr(rsp, 64);
4690         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4691         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4692         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4693         Assembler::punpcklbw(xmm0, xmm1);
4694         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4695         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4696         addptr(rsp, 64);
4697         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4698         addptr(rsp, 64);
4699       }
4700     }
4701   } else {
4702     Assembler::punpcklbw(dst, src);
4703   }
4704 }
4705 
4706 // This instruction exists within macros, ergo we cannot control its input
4707 // when emitted through those patterns.
4708 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4709   if (VM_Version::supports_avx512nobw()) {
4710     int dst_enc = dst->encoding();
4711     int src_enc = src->encoding();
4712     if (dst_enc == src_enc) {
4713       if (dst_enc < 16) {
4714         Assembler::pshuflw(dst, src, mode);
4715       } else {
4716         subptr(rsp, 64);
4717         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4718         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4719         Assembler::pshuflw(xmm0, xmm0, mode);
4720         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4721         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4722         addptr(rsp, 64);
4723       }
4724     } else {
4725       if ((src_enc < 16) && (dst_enc < 16)) {
4726         Assembler::pshuflw(dst, src, mode);
4727       } else if (src_enc < 16) {
4728         subptr(rsp, 64);
4729         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4730         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4731         Assembler::pshuflw(xmm0, src, mode);
4732         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4733         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4734         addptr(rsp, 64);
4735       } else if (dst_enc < 16) {
4736         subptr(rsp, 64);
4737         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4738         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4739         Assembler::pshuflw(dst, xmm0, mode);
4740         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4741         addptr(rsp, 64);
4742       } else {
4743         subptr(rsp, 64);
4744         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4745         subptr(rsp, 64);
4746         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4747         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4748         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4749         Assembler::pshuflw(xmm0, xmm1, mode);
4750         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4751         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4752         addptr(rsp, 64);
4753         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4754         addptr(rsp, 64);
4755       }
4756     }
4757   } else {
4758     Assembler::pshuflw(dst, src, mode);
4759   }
4760 }
4761 
4762 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4763   if (reachable(src)) {
4764     vandpd(dst, nds, as_Address(src), vector_len);
4765   } else {
4766     lea(rscratch1, src);
4767     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4768   }
4769 }
4770 
4771 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4772   if (reachable(src)) {
4773     vandps(dst, nds, as_Address(src), vector_len);
4774   } else {
4775     lea(rscratch1, src);
4776     vandps(dst, nds, Address(rscratch1, 0), vector_len);
4777   }
4778 }
4779 
4780 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4781   if (reachable(src)) {
4782     vdivsd(dst, nds, as_Address(src));
4783   } else {
4784     lea(rscratch1, src);
4785     vdivsd(dst, nds, Address(rscratch1, 0));
4786   }
4787 }
4788 
4789 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4790   if (reachable(src)) {
4791     vdivss(dst, nds, as_Address(src));
4792   } else {
4793     lea(rscratch1, src);
4794     vdivss(dst, nds, Address(rscratch1, 0));
4795   }
4796 }
4797 
4798 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4799   if (reachable(src)) {
4800     vmulsd(dst, nds, as_Address(src));
4801   } else {
4802     lea(rscratch1, src);
4803     vmulsd(dst, nds, Address(rscratch1, 0));
4804   }
4805 }
4806 
4807 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4808   if (reachable(src)) {
4809     vmulss(dst, nds, as_Address(src));
4810   } else {
4811     lea(rscratch1, src);
4812     vmulss(dst, nds, Address(rscratch1, 0));
4813   }
4814 }
4815 
4816 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4817   if (reachable(src)) {
4818     vsubsd(dst, nds, as_Address(src));
4819   } else {
4820     lea(rscratch1, src);
4821     vsubsd(dst, nds, Address(rscratch1, 0));
4822   }
4823 }
4824 
4825 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4826   if (reachable(src)) {
4827     vsubss(dst, nds, as_Address(src));
4828   } else {
4829     lea(rscratch1, src);
4830     vsubss(dst, nds, Address(rscratch1, 0));
4831   }
4832 }
4833 
4834 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4835   int nds_enc = nds->encoding();
4836   int dst_enc = dst->encoding();
4837   bool dst_upper_bank = (dst_enc > 15);
4838   bool nds_upper_bank = (nds_enc > 15);
4839   if (VM_Version::supports_avx512novl() &&
4840       (nds_upper_bank || dst_upper_bank)) {
4841     if (dst_upper_bank) {
4842       subptr(rsp, 64);
4843       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4844       movflt(xmm0, nds);
4845       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
4846       movflt(dst, xmm0);
4847       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4848       addptr(rsp, 64);
4849     } else {
4850       movflt(dst, nds);
4851       vxorps(dst, dst, src, Assembler::AVX_128bit);
4852     }
4853   } else {
4854     vxorps(dst, nds, src, Assembler::AVX_128bit);
4855   }
4856 }
4857 
4858 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4859   int nds_enc = nds->encoding();
4860   int dst_enc = dst->encoding();
4861   bool dst_upper_bank = (dst_enc > 15);
4862   bool nds_upper_bank = (nds_enc > 15);
4863   if (VM_Version::supports_avx512novl() &&
4864       (nds_upper_bank || dst_upper_bank)) {
4865     if (dst_upper_bank) {
4866       subptr(rsp, 64);
4867       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4868       movdbl(xmm0, nds);
4869       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
4870       movdbl(dst, xmm0);
4871       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4872       addptr(rsp, 64);
4873     } else {
4874       movdbl(dst, nds);
4875       vxorpd(dst, dst, src, Assembler::AVX_128bit);
4876     }
4877   } else {
4878     vxorpd(dst, nds, src, Assembler::AVX_128bit);
4879   }
4880 }
4881 
4882 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4883   if (reachable(src)) {
4884     vxorpd(dst, nds, as_Address(src), vector_len);
4885   } else {
4886     lea(rscratch1, src);
4887     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
4888   }
4889 }
4890 
4891 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4892   if (reachable(src)) {
4893     vxorps(dst, nds, as_Address(src), vector_len);
4894   } else {
4895     lea(rscratch1, src);
4896     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
4897   }
4898 }
4899 
4900 
4901 //////////////////////////////////////////////////////////////////////////////////
4902 #if INCLUDE_ALL_GCS
4903 
4904 void MacroAssembler::g1_write_barrier_pre(Register obj,
4905                                           Register pre_val,
4906                                           Register thread,
4907                                           Register tmp,
4908                                           bool tosca_live,
4909                                           bool expand_call) {
4910 
4911   // If expand_call is true then we expand the call_VM_leaf macro
4912   // directly to skip generating the check by
4913   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
4914 
4915 #ifdef _LP64
4916   assert(thread == r15_thread, "must be");
4917 #endif // _LP64
4918 
4919   Label done;
4920   Label runtime;
4921 
4922   assert(pre_val != noreg, "check this code");
4923 
4924   if (obj != noreg) {
4925     assert_different_registers(obj, pre_val, tmp);
4926     assert(pre_val != rax, "check this code");
4927   }
4928 
4929   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4930                                        PtrQueue::byte_offset_of_active()));
4931   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4932                                        PtrQueue::byte_offset_of_index()));
4933   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4934                                        PtrQueue::byte_offset_of_buf()));
4935 
4936 
4937   // Is marking active?
4938   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
4939     cmpl(in_progress, 0);
4940   } else {
4941     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
4942     cmpb(in_progress, 0);
4943   }
4944   jcc(Assembler::equal, done);
4945 
4946   // Do we need to load the previous value?
4947   if (obj != noreg) {
4948     load_heap_oop(pre_val, Address(obj, 0));
4949   }
4950 
4951   // Is the previous value null?
4952   cmpptr(pre_val, (int32_t) NULL_WORD);
4953   jcc(Assembler::equal, done);
4954 
4955   // Can we store original value in the thread's buffer?
4956   // Is index == 0?
4957   // (The index field is typed as size_t.)
4958 
4959   movptr(tmp, index);                   // tmp := *index_adr
4960   cmpptr(tmp, 0);                       // tmp == 0?
4961   jcc(Assembler::equal, runtime);       // If yes, goto runtime
4962 
4963   subptr(tmp, wordSize);                // tmp := tmp - wordSize
4964   movptr(index, tmp);                   // *index_adr := tmp
4965   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
4966 
4967   // Record the previous value
4968   movptr(Address(tmp, 0), pre_val);
4969   jmp(done);
4970 
4971   bind(runtime);
4972   // save the live input values
4973   if(tosca_live) push(rax);
4974 
4975   if (obj != noreg && obj != rax)
4976     push(obj);
4977 
4978   if (pre_val != rax)
4979     push(pre_val);
4980 
4981   // Calling the runtime using the regular call_VM_leaf mechanism generates
4982   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
4983   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
4984   //
4985   // If we care generating the pre-barrier without a frame (e.g. in the
4986   // intrinsified Reference.get() routine) then ebp might be pointing to
4987   // the caller frame and so this check will most likely fail at runtime.
4988   //
4989   // Expanding the call directly bypasses the generation of the check.
4990   // So when we do not have have a full interpreter frame on the stack
4991   // expand_call should be passed true.
4992 
4993   NOT_LP64( push(thread); )
4994 
4995   if (expand_call) {
4996     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
4997     pass_arg1(this, thread);
4998     pass_arg0(this, pre_val);
4999     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5000   } else {
5001     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5002   }
5003 
5004   NOT_LP64( pop(thread); )
5005 
5006   // save the live input values
5007   if (pre_val != rax)
5008     pop(pre_val);
5009 
5010   if (obj != noreg && obj != rax)
5011     pop(obj);
5012 
5013   if(tosca_live) pop(rax);
5014 
5015   bind(done);
5016 }
5017 
5018 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5019                                            Register new_val,
5020                                            Register thread,
5021                                            Register tmp,
5022                                            Register tmp2) {
5023 #ifdef _LP64
5024   assert(thread == r15_thread, "must be");
5025 #endif // _LP64
5026 
5027   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5028                                        PtrQueue::byte_offset_of_index()));
5029   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5030                                        PtrQueue::byte_offset_of_buf()));
5031 
5032   CardTableModRefBS* ct =
5033     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5034   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5035 
5036   Label done;
5037   Label runtime;
5038 
5039   // Does store cross heap regions?
5040 
5041   movptr(tmp, store_addr);
5042   xorptr(tmp, new_val);
5043   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5044   jcc(Assembler::equal, done);
5045 
5046   // crosses regions, storing NULL?
5047 
5048   cmpptr(new_val, (int32_t) NULL_WORD);
5049   jcc(Assembler::equal, done);
5050 
5051   // storing region crossing non-NULL, is card already dirty?
5052 
5053   const Register card_addr = tmp;
5054   const Register cardtable = tmp2;
5055 
5056   movptr(card_addr, store_addr);
5057   shrptr(card_addr, CardTableModRefBS::card_shift);
5058   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5059   // a valid address and therefore is not properly handled by the relocation code.
5060   movptr(cardtable, (intptr_t)ct->byte_map_base);
5061   addptr(card_addr, cardtable);
5062 
5063   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5064   jcc(Assembler::equal, done);
5065 
5066   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5067   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5068   jcc(Assembler::equal, done);
5069 
5070 
5071   // storing a region crossing, non-NULL oop, card is clean.
5072   // dirty card and log.
5073 
5074   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5075 
5076   cmpl(queue_index, 0);
5077   jcc(Assembler::equal, runtime);
5078   subl(queue_index, wordSize);
5079   movptr(tmp2, buffer);
5080 #ifdef _LP64
5081   movslq(rscratch1, queue_index);
5082   addq(tmp2, rscratch1);
5083   movq(Address(tmp2, 0), card_addr);
5084 #else
5085   addl(tmp2, queue_index);
5086   movl(Address(tmp2, 0), card_addr);
5087 #endif
5088   jmp(done);
5089 
5090   bind(runtime);
5091   // save the live input values
5092   push(store_addr);
5093   push(new_val);
5094 #ifdef _LP64
5095   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5096 #else
5097   push(thread);
5098   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5099   pop(thread);
5100 #endif
5101   pop(new_val);
5102   pop(store_addr);
5103 
5104   bind(done);
5105 }
5106 
5107 #endif // INCLUDE_ALL_GCS
5108 //////////////////////////////////////////////////////////////////////////////////
5109 
5110 
5111 void MacroAssembler::store_check(Register obj, Address dst) {
5112   store_check(obj);
5113 }
5114 
5115 void MacroAssembler::store_check(Register obj) {
5116   // Does a store check for the oop in register obj. The content of
5117   // register obj is destroyed afterwards.
5118   BarrierSet* bs = Universe::heap()->barrier_set();
5119   assert(bs->kind() == BarrierSet::CardTableForRS ||
5120          bs->kind() == BarrierSet::CardTableExtension,
5121          "Wrong barrier set kind");
5122 
5123   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5124   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5125 
5126   shrptr(obj, CardTableModRefBS::card_shift);
5127 
5128   Address card_addr;
5129 
5130   // The calculation for byte_map_base is as follows:
5131   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5132   // So this essentially converts an address to a displacement and it will
5133   // never need to be relocated. On 64bit however the value may be too
5134   // large for a 32bit displacement.
5135   intptr_t disp = (intptr_t) ct->byte_map_base;
5136   if (is_simm32(disp)) {
5137     card_addr = Address(noreg, obj, Address::times_1, disp);
5138   } else {
5139     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5140     // displacement and done in a single instruction given favorable mapping and a
5141     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5142     // entry and that entry is not properly handled by the relocation code.
5143     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5144     Address index(noreg, obj, Address::times_1);
5145     card_addr = as_Address(ArrayAddress(cardtable, index));
5146   }
5147 
5148   int dirty = CardTableModRefBS::dirty_card_val();
5149   if (UseCondCardMark) {
5150     Label L_already_dirty;
5151     if (UseConcMarkSweepGC) {
5152       membar(Assembler::StoreLoad);
5153     }
5154     cmpb(card_addr, dirty);
5155     jcc(Assembler::equal, L_already_dirty);
5156     movb(card_addr, dirty);
5157     bind(L_already_dirty);
5158   } else {
5159     movb(card_addr, dirty);
5160   }
5161 }
5162 
5163 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5164   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5165 }
5166 
5167 // Force generation of a 4 byte immediate value even if it fits into 8bit
5168 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5169   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5170 }
5171 
5172 void MacroAssembler::subptr(Register dst, Register src) {
5173   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5174 }
5175 
5176 // C++ bool manipulation
5177 void MacroAssembler::testbool(Register dst) {
5178   if(sizeof(bool) == 1)
5179     testb(dst, 0xff);
5180   else if(sizeof(bool) == 2) {
5181     // testw implementation needed for two byte bools
5182     ShouldNotReachHere();
5183   } else if(sizeof(bool) == 4)
5184     testl(dst, dst);
5185   else
5186     // unsupported
5187     ShouldNotReachHere();
5188 }
5189 
5190 void MacroAssembler::testptr(Register dst, Register src) {
5191   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5192 }
5193 
5194 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5195 void MacroAssembler::tlab_allocate(Register obj,
5196                                    Register var_size_in_bytes,
5197                                    int con_size_in_bytes,
5198                                    Register t1,
5199                                    Register t2,
5200                                    Label& slow_case) {
5201   assert_different_registers(obj, t1, t2);
5202   assert_different_registers(obj, var_size_in_bytes, t1);
5203   Register end = t2;
5204   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5205 
5206   verify_tlab();
5207 
5208   NOT_LP64(get_thread(thread));
5209 
5210   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5211   if (var_size_in_bytes == noreg) {
5212     lea(end, Address(obj, con_size_in_bytes));
5213   } else {
5214     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5215   }
5216   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5217   jcc(Assembler::above, slow_case);
5218 
5219   // update the tlab top pointer
5220   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5221 
5222   // recover var_size_in_bytes if necessary
5223   if (var_size_in_bytes == end) {
5224     subptr(var_size_in_bytes, obj);
5225   }
5226   verify_tlab();
5227 }
5228 
5229 // Preserves rbx, and rdx.
5230 Register MacroAssembler::tlab_refill(Label& retry,
5231                                      Label& try_eden,
5232                                      Label& slow_case) {
5233   Register top = rax;
5234   Register t1  = rcx;
5235   Register t2  = rsi;
5236   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5237   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5238   Label do_refill, discard_tlab;
5239 
5240   if (!Universe::heap()->supports_inline_contig_alloc()) {
5241     // No allocation in the shared eden.
5242     jmp(slow_case);
5243   }
5244 
5245   NOT_LP64(get_thread(thread_reg));
5246 
5247   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5248   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5249 
5250   // calculate amount of free space
5251   subptr(t1, top);
5252   shrptr(t1, LogHeapWordSize);
5253 
5254   // Retain tlab and allocate object in shared space if
5255   // the amount free in the tlab is too large to discard.
5256   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5257   jcc(Assembler::lessEqual, discard_tlab);
5258 
5259   // Retain
5260   // %%% yuck as movptr...
5261   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5262   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5263   if (TLABStats) {
5264     // increment number of slow_allocations
5265     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5266   }
5267   jmp(try_eden);
5268 
5269   bind(discard_tlab);
5270   if (TLABStats) {
5271     // increment number of refills
5272     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5273     // accumulate wastage -- t1 is amount free in tlab
5274     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5275   }
5276 
5277   // if tlab is currently allocated (top or end != null) then
5278   // fill [top, end + alignment_reserve) with array object
5279   testptr(top, top);
5280   jcc(Assembler::zero, do_refill);
5281 
5282   // set up the mark word
5283   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5284   // set the length to the remaining space
5285   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5286   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5287   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5288   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5289   // set klass to intArrayKlass
5290   // dubious reloc why not an oop reloc?
5291   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5292   // store klass last.  concurrent gcs assumes klass length is valid if
5293   // klass field is not null.
5294   store_klass(top, t1);
5295 
5296   movptr(t1, top);
5297   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5298   incr_allocated_bytes(thread_reg, t1, 0);
5299 
5300   // refill the tlab with an eden allocation
5301   bind(do_refill);
5302   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5303   shlptr(t1, LogHeapWordSize);
5304   // allocate new tlab, address returned in top
5305   eden_allocate(top, t1, 0, t2, slow_case);
5306 
5307   // Check that t1 was preserved in eden_allocate.
5308 #ifdef ASSERT
5309   if (UseTLAB) {
5310     Label ok;
5311     Register tsize = rsi;
5312     assert_different_registers(tsize, thread_reg, t1);
5313     push(tsize);
5314     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5315     shlptr(tsize, LogHeapWordSize);
5316     cmpptr(t1, tsize);
5317     jcc(Assembler::equal, ok);
5318     STOP("assert(t1 != tlab size)");
5319     should_not_reach_here();
5320 
5321     bind(ok);
5322     pop(tsize);
5323   }
5324 #endif
5325   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5326   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5327   addptr(top, t1);
5328   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5329   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5330   verify_tlab();
5331   jmp(retry);
5332 
5333   return thread_reg; // for use by caller
5334 }
5335 
5336 void MacroAssembler::incr_allocated_bytes(Register thread,
5337                                           Register var_size_in_bytes,
5338                                           int con_size_in_bytes,
5339                                           Register t1) {
5340   if (!thread->is_valid()) {
5341 #ifdef _LP64
5342     thread = r15_thread;
5343 #else
5344     assert(t1->is_valid(), "need temp reg");
5345     thread = t1;
5346     get_thread(thread);
5347 #endif
5348   }
5349 
5350 #ifdef _LP64
5351   if (var_size_in_bytes->is_valid()) {
5352     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5353   } else {
5354     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5355   }
5356 #else
5357   if (var_size_in_bytes->is_valid()) {
5358     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5359   } else {
5360     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5361   }
5362   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5363 #endif
5364 }
5365 
5366 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5367   pusha();
5368 
5369   // if we are coming from c1, xmm registers may be live
5370   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5371   if (UseAVX > 2) {
5372     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5373   }
5374 
5375   if (UseSSE == 1)  {
5376     subptr(rsp, sizeof(jdouble)*8);
5377     for (int n = 0; n < 8; n++) {
5378       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5379     }
5380   } else if (UseSSE >= 2)  {
5381     if (UseAVX > 2) {
5382       push(rbx);
5383       movl(rbx, 0xffff);
5384       kmovwl(k1, rbx);
5385       pop(rbx);
5386     }
5387 #ifdef COMPILER2
5388     if (MaxVectorSize > 16) {
5389       if(UseAVX > 2) {
5390         // Save upper half of ZMM registers
5391         subptr(rsp, 32*num_xmm_regs);
5392         for (int n = 0; n < num_xmm_regs; n++) {
5393           vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
5394         }
5395       }
5396       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5397       // Save upper half of YMM registers
5398       subptr(rsp, 16*num_xmm_regs);
5399       for (int n = 0; n < num_xmm_regs; n++) {
5400         vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
5401       }
5402     }
5403 #endif
5404     // Save whole 128bit (16 bytes) XMM registers
5405     subptr(rsp, 16*num_xmm_regs);
5406 #ifdef _LP64
5407     if (VM_Version::supports_evex()) {
5408       for (int n = 0; n < num_xmm_regs; n++) {
5409         vextractf32x4h(Address(rsp, n*16), as_XMMRegister(n), 0);
5410       }
5411     } else {
5412       for (int n = 0; n < num_xmm_regs; n++) {
5413         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5414       }
5415     }
5416 #else
5417     for (int n = 0; n < num_xmm_regs; n++) {
5418       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5419     }
5420 #endif
5421   }
5422 
5423   // Preserve registers across runtime call
5424   int incoming_argument_and_return_value_offset = -1;
5425   if (num_fpu_regs_in_use > 1) {
5426     // Must preserve all other FPU regs (could alternatively convert
5427     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5428     // FPU state, but can not trust C compiler)
5429     NEEDS_CLEANUP;
5430     // NOTE that in this case we also push the incoming argument(s) to
5431     // the stack and restore it later; we also use this stack slot to
5432     // hold the return value from dsin, dcos etc.
5433     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5434       subptr(rsp, sizeof(jdouble));
5435       fstp_d(Address(rsp, 0));
5436     }
5437     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5438     for (int i = nb_args-1; i >= 0; i--) {
5439       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5440     }
5441   }
5442 
5443   subptr(rsp, nb_args*sizeof(jdouble));
5444   for (int i = 0; i < nb_args; i++) {
5445     fstp_d(Address(rsp, i*sizeof(jdouble)));
5446   }
5447 
5448 #ifdef _LP64
5449   if (nb_args > 0) {
5450     movdbl(xmm0, Address(rsp, 0));
5451   }
5452   if (nb_args > 1) {
5453     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5454   }
5455   assert(nb_args <= 2, "unsupported number of args");
5456 #endif // _LP64
5457 
5458   // NOTE: we must not use call_VM_leaf here because that requires a
5459   // complete interpreter frame in debug mode -- same bug as 4387334
5460   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5461   // do proper 64bit abi
5462 
5463   NEEDS_CLEANUP;
5464   // Need to add stack banging before this runtime call if it needs to
5465   // be taken; however, there is no generic stack banging routine at
5466   // the MacroAssembler level
5467 
5468   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5469 
5470 #ifdef _LP64
5471   movsd(Address(rsp, 0), xmm0);
5472   fld_d(Address(rsp, 0));
5473 #endif // _LP64
5474   addptr(rsp, sizeof(jdouble)*nb_args);
5475   if (num_fpu_regs_in_use > 1) {
5476     // Must save return value to stack and then restore entire FPU
5477     // stack except incoming arguments
5478     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5479     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5480       fld_d(Address(rsp, 0));
5481       addptr(rsp, sizeof(jdouble));
5482     }
5483     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5484     addptr(rsp, sizeof(jdouble)*nb_args);
5485   }
5486 
5487   if (UseSSE == 1)  {
5488     for (int n = 0; n < 8; n++) {
5489       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5490     }
5491     addptr(rsp, sizeof(jdouble)*8);
5492   } else if (UseSSE >= 2)  {
5493     // Restore whole 128bit (16 bytes) XMM registers
5494 #ifdef _LP64
5495   if (VM_Version::supports_evex()) {
5496     for (int n = 0; n < num_xmm_regs; n++) {
5497       vinsertf32x4h(as_XMMRegister(n), Address(rsp, n*16), 0);
5498     }
5499   } else {
5500     for (int n = 0; n < num_xmm_regs; n++) {
5501       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5502     }
5503   }
5504 #else
5505   for (int n = 0; n < num_xmm_regs; n++) {
5506     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5507   }
5508 #endif
5509     addptr(rsp, 16*num_xmm_regs);
5510 
5511 #ifdef COMPILER2
5512     if (MaxVectorSize > 16) {
5513       // Restore upper half of YMM registers.
5514       for (int n = 0; n < num_xmm_regs; n++) {
5515         vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
5516       }
5517       addptr(rsp, 16*num_xmm_regs);
5518       if(UseAVX > 2) {
5519         for (int n = 0; n < num_xmm_regs; n++) {
5520           vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
5521         }
5522         addptr(rsp, 32*num_xmm_regs);
5523       }
5524     }
5525 #endif
5526   }
5527   popa();
5528 }
5529 
5530 static const double     pi_4 =  0.7853981633974483;
5531 
5532 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5533   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5534   // was attempted in this code; unfortunately it appears that the
5535   // switch to 80-bit precision and back causes this to be
5536   // unprofitable compared with simply performing a runtime call if
5537   // the argument is out of the (-pi/4, pi/4) range.
5538 
5539   Register tmp = noreg;
5540   if (!VM_Version::supports_cmov()) {
5541     // fcmp needs a temporary so preserve rbx,
5542     tmp = rbx;
5543     push(tmp);
5544   }
5545 
5546   Label slow_case, done;
5547 
5548   ExternalAddress pi4_adr = (address)&pi_4;
5549   if (reachable(pi4_adr)) {
5550     // x ?<= pi/4
5551     fld_d(pi4_adr);
5552     fld_s(1);                // Stack:  X  PI/4  X
5553     fabs();                  // Stack: |X| PI/4  X
5554     fcmp(tmp);
5555     jcc(Assembler::above, slow_case);
5556 
5557     // fastest case: -pi/4 <= x <= pi/4
5558     switch(trig) {
5559     case 's':
5560       fsin();
5561       break;
5562     case 'c':
5563       fcos();
5564       break;
5565     case 't':
5566       ftan();
5567       break;
5568     default:
5569       assert(false, "bad intrinsic");
5570       break;
5571     }
5572     jmp(done);
5573   }
5574 
5575   // slow case: runtime call
5576   bind(slow_case);
5577 
5578   switch(trig) {
5579   case 's':
5580     {
5581       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
5582     }
5583     break;
5584   case 'c':
5585     {
5586       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
5587     }
5588     break;
5589   case 't':
5590     {
5591       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
5592     }
5593     break;
5594   default:
5595     assert(false, "bad intrinsic");
5596     break;
5597   }
5598 
5599   // Come here with result in F-TOS
5600   bind(done);
5601 
5602   if (tmp != noreg) {
5603     pop(tmp);
5604   }
5605 }
5606 
5607 
5608 // Look up the method for a megamorphic invokeinterface call.
5609 // The target method is determined by <intf_klass, itable_index>.
5610 // The receiver klass is in recv_klass.
5611 // On success, the result will be in method_result, and execution falls through.
5612 // On failure, execution transfers to the given label.
5613 void MacroAssembler::lookup_interface_method(Register recv_klass,
5614                                              Register intf_klass,
5615                                              RegisterOrConstant itable_index,
5616                                              Register method_result,
5617                                              Register scan_temp,
5618                                              Label& L_no_such_interface) {
5619   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5620   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5621          "caller must use same register for non-constant itable index as for method");
5622 
5623   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5624   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
5625   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5626   int scan_step   = itableOffsetEntry::size() * wordSize;
5627   int vte_size    = vtableEntry::size() * wordSize;
5628   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5629   assert(vte_size == wordSize, "else adjust times_vte_scale");
5630 
5631   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
5632 
5633   // %%% Could store the aligned, prescaled offset in the klassoop.
5634   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5635   if (HeapWordsPerLong > 1) {
5636     // Round up to align_object_offset boundary
5637     // see code for InstanceKlass::start_of_itable!
5638     round_to(scan_temp, BytesPerLong);
5639   }
5640 
5641   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5642   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5643   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5644 
5645   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5646   //   if (scan->interface() == intf) {
5647   //     result = (klass + scan->offset() + itable_index);
5648   //   }
5649   // }
5650   Label search, found_method;
5651 
5652   for (int peel = 1; peel >= 0; peel--) {
5653     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5654     cmpptr(intf_klass, method_result);
5655 
5656     if (peel) {
5657       jccb(Assembler::equal, found_method);
5658     } else {
5659       jccb(Assembler::notEqual, search);
5660       // (invert the test to fall through to found_method...)
5661     }
5662 
5663     if (!peel)  break;
5664 
5665     bind(search);
5666 
5667     // Check that the previous entry is non-null.  A null entry means that
5668     // the receiver class doesn't implement the interface, and wasn't the
5669     // same as when the caller was compiled.
5670     testptr(method_result, method_result);
5671     jcc(Assembler::zero, L_no_such_interface);
5672     addptr(scan_temp, scan_step);
5673   }
5674 
5675   bind(found_method);
5676 
5677   // Got a hit.
5678   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5679   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5680 }
5681 
5682 
5683 // virtual method calling
5684 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5685                                            RegisterOrConstant vtable_index,
5686                                            Register method_result) {
5687   const int base = InstanceKlass::vtable_start_offset() * wordSize;
5688   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5689   Address vtable_entry_addr(recv_klass,
5690                             vtable_index, Address::times_ptr,
5691                             base + vtableEntry::method_offset_in_bytes());
5692   movptr(method_result, vtable_entry_addr);
5693 }
5694 
5695 
5696 void MacroAssembler::check_klass_subtype(Register sub_klass,
5697                            Register super_klass,
5698                            Register temp_reg,
5699                            Label& L_success) {
5700   Label L_failure;
5701   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5702   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5703   bind(L_failure);
5704 }
5705 
5706 
5707 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5708                                                    Register super_klass,
5709                                                    Register temp_reg,
5710                                                    Label* L_success,
5711                                                    Label* L_failure,
5712                                                    Label* L_slow_path,
5713                                         RegisterOrConstant super_check_offset) {
5714   assert_different_registers(sub_klass, super_klass, temp_reg);
5715   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5716   if (super_check_offset.is_register()) {
5717     assert_different_registers(sub_klass, super_klass,
5718                                super_check_offset.as_register());
5719   } else if (must_load_sco) {
5720     assert(temp_reg != noreg, "supply either a temp or a register offset");
5721   }
5722 
5723   Label L_fallthrough;
5724   int label_nulls = 0;
5725   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5726   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5727   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5728   assert(label_nulls <= 1, "at most one NULL in the batch");
5729 
5730   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5731   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5732   Address super_check_offset_addr(super_klass, sco_offset);
5733 
5734   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5735   // range of a jccb.  If this routine grows larger, reconsider at
5736   // least some of these.
5737 #define local_jcc(assembler_cond, label)                                \
5738   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5739   else                             jcc( assembler_cond, label) /*omit semi*/
5740 
5741   // Hacked jmp, which may only be used just before L_fallthrough.
5742 #define final_jmp(label)                                                \
5743   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5744   else                            jmp(label)                /*omit semi*/
5745 
5746   // If the pointers are equal, we are done (e.g., String[] elements).
5747   // This self-check enables sharing of secondary supertype arrays among
5748   // non-primary types such as array-of-interface.  Otherwise, each such
5749   // type would need its own customized SSA.
5750   // We move this check to the front of the fast path because many
5751   // type checks are in fact trivially successful in this manner,
5752   // so we get a nicely predicted branch right at the start of the check.
5753   cmpptr(sub_klass, super_klass);
5754   local_jcc(Assembler::equal, *L_success);
5755 
5756   // Check the supertype display:
5757   if (must_load_sco) {
5758     // Positive movl does right thing on LP64.
5759     movl(temp_reg, super_check_offset_addr);
5760     super_check_offset = RegisterOrConstant(temp_reg);
5761   }
5762   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5763   cmpptr(super_klass, super_check_addr); // load displayed supertype
5764 
5765   // This check has worked decisively for primary supers.
5766   // Secondary supers are sought in the super_cache ('super_cache_addr').
5767   // (Secondary supers are interfaces and very deeply nested subtypes.)
5768   // This works in the same check above because of a tricky aliasing
5769   // between the super_cache and the primary super display elements.
5770   // (The 'super_check_addr' can address either, as the case requires.)
5771   // Note that the cache is updated below if it does not help us find
5772   // what we need immediately.
5773   // So if it was a primary super, we can just fail immediately.
5774   // Otherwise, it's the slow path for us (no success at this point).
5775 
5776   if (super_check_offset.is_register()) {
5777     local_jcc(Assembler::equal, *L_success);
5778     cmpl(super_check_offset.as_register(), sc_offset);
5779     if (L_failure == &L_fallthrough) {
5780       local_jcc(Assembler::equal, *L_slow_path);
5781     } else {
5782       local_jcc(Assembler::notEqual, *L_failure);
5783       final_jmp(*L_slow_path);
5784     }
5785   } else if (super_check_offset.as_constant() == sc_offset) {
5786     // Need a slow path; fast failure is impossible.
5787     if (L_slow_path == &L_fallthrough) {
5788       local_jcc(Assembler::equal, *L_success);
5789     } else {
5790       local_jcc(Assembler::notEqual, *L_slow_path);
5791       final_jmp(*L_success);
5792     }
5793   } else {
5794     // No slow path; it's a fast decision.
5795     if (L_failure == &L_fallthrough) {
5796       local_jcc(Assembler::equal, *L_success);
5797     } else {
5798       local_jcc(Assembler::notEqual, *L_failure);
5799       final_jmp(*L_success);
5800     }
5801   }
5802 
5803   bind(L_fallthrough);
5804 
5805 #undef local_jcc
5806 #undef final_jmp
5807 }
5808 
5809 
5810 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5811                                                    Register super_klass,
5812                                                    Register temp_reg,
5813                                                    Register temp2_reg,
5814                                                    Label* L_success,
5815                                                    Label* L_failure,
5816                                                    bool set_cond_codes) {
5817   assert_different_registers(sub_klass, super_klass, temp_reg);
5818   if (temp2_reg != noreg)
5819     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5820 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5821 
5822   Label L_fallthrough;
5823   int label_nulls = 0;
5824   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5825   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5826   assert(label_nulls <= 1, "at most one NULL in the batch");
5827 
5828   // a couple of useful fields in sub_klass:
5829   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5830   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5831   Address secondary_supers_addr(sub_klass, ss_offset);
5832   Address super_cache_addr(     sub_klass, sc_offset);
5833 
5834   // Do a linear scan of the secondary super-klass chain.
5835   // This code is rarely used, so simplicity is a virtue here.
5836   // The repne_scan instruction uses fixed registers, which we must spill.
5837   // Don't worry too much about pre-existing connections with the input regs.
5838 
5839   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5840   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5841 
5842   // Get super_klass value into rax (even if it was in rdi or rcx).
5843   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5844   if (super_klass != rax || UseCompressedOops) {
5845     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5846     mov(rax, super_klass);
5847   }
5848   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5849   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5850 
5851 #ifndef PRODUCT
5852   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5853   ExternalAddress pst_counter_addr((address) pst_counter);
5854   NOT_LP64(  incrementl(pst_counter_addr) );
5855   LP64_ONLY( lea(rcx, pst_counter_addr) );
5856   LP64_ONLY( incrementl(Address(rcx, 0)) );
5857 #endif //PRODUCT
5858 
5859   // We will consult the secondary-super array.
5860   movptr(rdi, secondary_supers_addr);
5861   // Load the array length.  (Positive movl does right thing on LP64.)
5862   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5863   // Skip to start of data.
5864   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5865 
5866   // Scan RCX words at [RDI] for an occurrence of RAX.
5867   // Set NZ/Z based on last compare.
5868   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5869   // not change flags (only scas instruction which is repeated sets flags).
5870   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5871 
5872     testptr(rax,rax); // Set Z = 0
5873     repne_scan();
5874 
5875   // Unspill the temp. registers:
5876   if (pushed_rdi)  pop(rdi);
5877   if (pushed_rcx)  pop(rcx);
5878   if (pushed_rax)  pop(rax);
5879 
5880   if (set_cond_codes) {
5881     // Special hack for the AD files:  rdi is guaranteed non-zero.
5882     assert(!pushed_rdi, "rdi must be left non-NULL");
5883     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5884   }
5885 
5886   if (L_failure == &L_fallthrough)
5887         jccb(Assembler::notEqual, *L_failure);
5888   else  jcc(Assembler::notEqual, *L_failure);
5889 
5890   // Success.  Cache the super we found and proceed in triumph.
5891   movptr(super_cache_addr, super_klass);
5892 
5893   if (L_success != &L_fallthrough) {
5894     jmp(*L_success);
5895   }
5896 
5897 #undef IS_A_TEMP
5898 
5899   bind(L_fallthrough);
5900 }
5901 
5902 
5903 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5904   if (VM_Version::supports_cmov()) {
5905     cmovl(cc, dst, src);
5906   } else {
5907     Label L;
5908     jccb(negate_condition(cc), L);
5909     movl(dst, src);
5910     bind(L);
5911   }
5912 }
5913 
5914 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5915   if (VM_Version::supports_cmov()) {
5916     cmovl(cc, dst, src);
5917   } else {
5918     Label L;
5919     jccb(negate_condition(cc), L);
5920     movl(dst, src);
5921     bind(L);
5922   }
5923 }
5924 
5925 void MacroAssembler::verify_oop(Register reg, const char* s) {
5926   if (!VerifyOops) return;
5927 
5928   // Pass register number to verify_oop_subroutine
5929   const char* b = NULL;
5930   {
5931     ResourceMark rm;
5932     stringStream ss;
5933     ss.print("verify_oop: %s: %s", reg->name(), s);
5934     b = code_string(ss.as_string());
5935   }
5936   BLOCK_COMMENT("verify_oop {");
5937 #ifdef _LP64
5938   push(rscratch1);                    // save r10, trashed by movptr()
5939 #endif
5940   push(rax);                          // save rax,
5941   push(reg);                          // pass register argument
5942   ExternalAddress buffer((address) b);
5943   // avoid using pushptr, as it modifies scratch registers
5944   // and our contract is not to modify anything
5945   movptr(rax, buffer.addr());
5946   push(rax);
5947   // call indirectly to solve generation ordering problem
5948   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5949   call(rax);
5950   // Caller pops the arguments (oop, message) and restores rax, r10
5951   BLOCK_COMMENT("} verify_oop");
5952 }
5953 
5954 
5955 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5956                                                       Register tmp,
5957                                                       int offset) {
5958   intptr_t value = *delayed_value_addr;
5959   if (value != 0)
5960     return RegisterOrConstant(value + offset);
5961 
5962   // load indirectly to solve generation ordering problem
5963   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5964 
5965 #ifdef ASSERT
5966   { Label L;
5967     testptr(tmp, tmp);
5968     if (WizardMode) {
5969       const char* buf = NULL;
5970       {
5971         ResourceMark rm;
5972         stringStream ss;
5973         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5974         buf = code_string(ss.as_string());
5975       }
5976       jcc(Assembler::notZero, L);
5977       STOP(buf);
5978     } else {
5979       jccb(Assembler::notZero, L);
5980       hlt();
5981     }
5982     bind(L);
5983   }
5984 #endif
5985 
5986   if (offset != 0)
5987     addptr(tmp, offset);
5988 
5989   return RegisterOrConstant(tmp);
5990 }
5991 
5992 
5993 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5994                                          int extra_slot_offset) {
5995   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5996   int stackElementSize = Interpreter::stackElementSize;
5997   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5998 #ifdef ASSERT
5999   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6000   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6001 #endif
6002   Register             scale_reg    = noreg;
6003   Address::ScaleFactor scale_factor = Address::no_scale;
6004   if (arg_slot.is_constant()) {
6005     offset += arg_slot.as_constant() * stackElementSize;
6006   } else {
6007     scale_reg    = arg_slot.as_register();
6008     scale_factor = Address::times(stackElementSize);
6009   }
6010   offset += wordSize;           // return PC is on stack
6011   return Address(rsp, scale_reg, scale_factor, offset);
6012 }
6013 
6014 
6015 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6016   if (!VerifyOops) return;
6017 
6018   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6019   // Pass register number to verify_oop_subroutine
6020   const char* b = NULL;
6021   {
6022     ResourceMark rm;
6023     stringStream ss;
6024     ss.print("verify_oop_addr: %s", s);
6025     b = code_string(ss.as_string());
6026   }
6027 #ifdef _LP64
6028   push(rscratch1);                    // save r10, trashed by movptr()
6029 #endif
6030   push(rax);                          // save rax,
6031   // addr may contain rsp so we will have to adjust it based on the push
6032   // we just did (and on 64 bit we do two pushes)
6033   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6034   // stores rax into addr which is backwards of what was intended.
6035   if (addr.uses(rsp)) {
6036     lea(rax, addr);
6037     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6038   } else {
6039     pushptr(addr);
6040   }
6041 
6042   ExternalAddress buffer((address) b);
6043   // pass msg argument
6044   // avoid using pushptr, as it modifies scratch registers
6045   // and our contract is not to modify anything
6046   movptr(rax, buffer.addr());
6047   push(rax);
6048 
6049   // call indirectly to solve generation ordering problem
6050   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6051   call(rax);
6052   // Caller pops the arguments (addr, message) and restores rax, r10.
6053 }
6054 
6055 void MacroAssembler::verify_tlab() {
6056 #ifdef ASSERT
6057   if (UseTLAB && VerifyOops) {
6058     Label next, ok;
6059     Register t1 = rsi;
6060     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6061 
6062     push(t1);
6063     NOT_LP64(push(thread_reg));
6064     NOT_LP64(get_thread(thread_reg));
6065 
6066     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6067     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6068     jcc(Assembler::aboveEqual, next);
6069     STOP("assert(top >= start)");
6070     should_not_reach_here();
6071 
6072     bind(next);
6073     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6074     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6075     jcc(Assembler::aboveEqual, ok);
6076     STOP("assert(top <= end)");
6077     should_not_reach_here();
6078 
6079     bind(ok);
6080     NOT_LP64(pop(thread_reg));
6081     pop(t1);
6082   }
6083 #endif
6084 }
6085 
6086 class ControlWord {
6087  public:
6088   int32_t _value;
6089 
6090   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6091   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6092   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6093   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6094   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6095   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6096   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6097   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6098 
6099   void print() const {
6100     // rounding control
6101     const char* rc;
6102     switch (rounding_control()) {
6103       case 0: rc = "round near"; break;
6104       case 1: rc = "round down"; break;
6105       case 2: rc = "round up  "; break;
6106       case 3: rc = "chop      "; break;
6107     };
6108     // precision control
6109     const char* pc;
6110     switch (precision_control()) {
6111       case 0: pc = "24 bits "; break;
6112       case 1: pc = "reserved"; break;
6113       case 2: pc = "53 bits "; break;
6114       case 3: pc = "64 bits "; break;
6115     };
6116     // flags
6117     char f[9];
6118     f[0] = ' ';
6119     f[1] = ' ';
6120     f[2] = (precision   ()) ? 'P' : 'p';
6121     f[3] = (underflow   ()) ? 'U' : 'u';
6122     f[4] = (overflow    ()) ? 'O' : 'o';
6123     f[5] = (zero_divide ()) ? 'Z' : 'z';
6124     f[6] = (denormalized()) ? 'D' : 'd';
6125     f[7] = (invalid     ()) ? 'I' : 'i';
6126     f[8] = '\x0';
6127     // output
6128     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6129   }
6130 
6131 };
6132 
6133 class StatusWord {
6134  public:
6135   int32_t _value;
6136 
6137   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6138   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6139   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6140   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6141   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6142   int  top() const                     { return  (_value >> 11) & 7      ; }
6143   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6144   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6145   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6146   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6147   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6148   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6149   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6150   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6151 
6152   void print() const {
6153     // condition codes
6154     char c[5];
6155     c[0] = (C3()) ? '3' : '-';
6156     c[1] = (C2()) ? '2' : '-';
6157     c[2] = (C1()) ? '1' : '-';
6158     c[3] = (C0()) ? '0' : '-';
6159     c[4] = '\x0';
6160     // flags
6161     char f[9];
6162     f[0] = (error_status()) ? 'E' : '-';
6163     f[1] = (stack_fault ()) ? 'S' : '-';
6164     f[2] = (precision   ()) ? 'P' : '-';
6165     f[3] = (underflow   ()) ? 'U' : '-';
6166     f[4] = (overflow    ()) ? 'O' : '-';
6167     f[5] = (zero_divide ()) ? 'Z' : '-';
6168     f[6] = (denormalized()) ? 'D' : '-';
6169     f[7] = (invalid     ()) ? 'I' : '-';
6170     f[8] = '\x0';
6171     // output
6172     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6173   }
6174 
6175 };
6176 
6177 class TagWord {
6178  public:
6179   int32_t _value;
6180 
6181   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6182 
6183   void print() const {
6184     printf("%04x", _value & 0xFFFF);
6185   }
6186 
6187 };
6188 
6189 class FPU_Register {
6190  public:
6191   int32_t _m0;
6192   int32_t _m1;
6193   int16_t _ex;
6194 
6195   bool is_indefinite() const           {
6196     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6197   }
6198 
6199   void print() const {
6200     char  sign = (_ex < 0) ? '-' : '+';
6201     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6202     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6203   };
6204 
6205 };
6206 
6207 class FPU_State {
6208  public:
6209   enum {
6210     register_size       = 10,
6211     number_of_registers =  8,
6212     register_mask       =  7
6213   };
6214 
6215   ControlWord  _control_word;
6216   StatusWord   _status_word;
6217   TagWord      _tag_word;
6218   int32_t      _error_offset;
6219   int32_t      _error_selector;
6220   int32_t      _data_offset;
6221   int32_t      _data_selector;
6222   int8_t       _register[register_size * number_of_registers];
6223 
6224   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6225   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6226 
6227   const char* tag_as_string(int tag) const {
6228     switch (tag) {
6229       case 0: return "valid";
6230       case 1: return "zero";
6231       case 2: return "special";
6232       case 3: return "empty";
6233     }
6234     ShouldNotReachHere();
6235     return NULL;
6236   }
6237 
6238   void print() const {
6239     // print computation registers
6240     { int t = _status_word.top();
6241       for (int i = 0; i < number_of_registers; i++) {
6242         int j = (i - t) & register_mask;
6243         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6244         st(j)->print();
6245         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6246       }
6247     }
6248     printf("\n");
6249     // print control registers
6250     printf("ctrl = "); _control_word.print(); printf("\n");
6251     printf("stat = "); _status_word .print(); printf("\n");
6252     printf("tags = "); _tag_word    .print(); printf("\n");
6253   }
6254 
6255 };
6256 
6257 class Flag_Register {
6258  public:
6259   int32_t _value;
6260 
6261   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6262   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6263   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6264   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6265   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6266   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6267   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6268 
6269   void print() const {
6270     // flags
6271     char f[8];
6272     f[0] = (overflow       ()) ? 'O' : '-';
6273     f[1] = (direction      ()) ? 'D' : '-';
6274     f[2] = (sign           ()) ? 'S' : '-';
6275     f[3] = (zero           ()) ? 'Z' : '-';
6276     f[4] = (auxiliary_carry()) ? 'A' : '-';
6277     f[5] = (parity         ()) ? 'P' : '-';
6278     f[6] = (carry          ()) ? 'C' : '-';
6279     f[7] = '\x0';
6280     // output
6281     printf("%08x  flags = %s", _value, f);
6282   }
6283 
6284 };
6285 
6286 class IU_Register {
6287  public:
6288   int32_t _value;
6289 
6290   void print() const {
6291     printf("%08x  %11d", _value, _value);
6292   }
6293 
6294 };
6295 
6296 class IU_State {
6297  public:
6298   Flag_Register _eflags;
6299   IU_Register   _rdi;
6300   IU_Register   _rsi;
6301   IU_Register   _rbp;
6302   IU_Register   _rsp;
6303   IU_Register   _rbx;
6304   IU_Register   _rdx;
6305   IU_Register   _rcx;
6306   IU_Register   _rax;
6307 
6308   void print() const {
6309     // computation registers
6310     printf("rax,  = "); _rax.print(); printf("\n");
6311     printf("rbx,  = "); _rbx.print(); printf("\n");
6312     printf("rcx  = "); _rcx.print(); printf("\n");
6313     printf("rdx  = "); _rdx.print(); printf("\n");
6314     printf("rdi  = "); _rdi.print(); printf("\n");
6315     printf("rsi  = "); _rsi.print(); printf("\n");
6316     printf("rbp,  = "); _rbp.print(); printf("\n");
6317     printf("rsp  = "); _rsp.print(); printf("\n");
6318     printf("\n");
6319     // control registers
6320     printf("flgs = "); _eflags.print(); printf("\n");
6321   }
6322 };
6323 
6324 
6325 class CPU_State {
6326  public:
6327   FPU_State _fpu_state;
6328   IU_State  _iu_state;
6329 
6330   void print() const {
6331     printf("--------------------------------------------------\n");
6332     _iu_state .print();
6333     printf("\n");
6334     _fpu_state.print();
6335     printf("--------------------------------------------------\n");
6336   }
6337 
6338 };
6339 
6340 
6341 static void _print_CPU_state(CPU_State* state) {
6342   state->print();
6343 };
6344 
6345 
6346 void MacroAssembler::print_CPU_state() {
6347   push_CPU_state();
6348   push(rsp);                // pass CPU state
6349   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6350   addptr(rsp, wordSize);       // discard argument
6351   pop_CPU_state();
6352 }
6353 
6354 
6355 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6356   static int counter = 0;
6357   FPU_State* fs = &state->_fpu_state;
6358   counter++;
6359   // For leaf calls, only verify that the top few elements remain empty.
6360   // We only need 1 empty at the top for C2 code.
6361   if( stack_depth < 0 ) {
6362     if( fs->tag_for_st(7) != 3 ) {
6363       printf("FPR7 not empty\n");
6364       state->print();
6365       assert(false, "error");
6366       return false;
6367     }
6368     return true;                // All other stack states do not matter
6369   }
6370 
6371   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6372          "bad FPU control word");
6373 
6374   // compute stack depth
6375   int i = 0;
6376   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6377   int d = i;
6378   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6379   // verify findings
6380   if (i != FPU_State::number_of_registers) {
6381     // stack not contiguous
6382     printf("%s: stack not contiguous at ST%d\n", s, i);
6383     state->print();
6384     assert(false, "error");
6385     return false;
6386   }
6387   // check if computed stack depth corresponds to expected stack depth
6388   if (stack_depth < 0) {
6389     // expected stack depth is -stack_depth or less
6390     if (d > -stack_depth) {
6391       // too many elements on the stack
6392       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6393       state->print();
6394       assert(false, "error");
6395       return false;
6396     }
6397   } else {
6398     // expected stack depth is stack_depth
6399     if (d != stack_depth) {
6400       // wrong stack depth
6401       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6402       state->print();
6403       assert(false, "error");
6404       return false;
6405     }
6406   }
6407   // everything is cool
6408   return true;
6409 }
6410 
6411 
6412 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6413   if (!VerifyFPU) return;
6414   push_CPU_state();
6415   push(rsp);                // pass CPU state
6416   ExternalAddress msg((address) s);
6417   // pass message string s
6418   pushptr(msg.addr());
6419   push(stack_depth);        // pass stack depth
6420   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6421   addptr(rsp, 3 * wordSize);   // discard arguments
6422   // check for error
6423   { Label L;
6424     testl(rax, rax);
6425     jcc(Assembler::notZero, L);
6426     int3();                  // break if error condition
6427     bind(L);
6428   }
6429   pop_CPU_state();
6430 }
6431 
6432 void MacroAssembler::restore_cpu_control_state_after_jni() {
6433   // Either restore the MXCSR register after returning from the JNI Call
6434   // or verify that it wasn't changed (with -Xcheck:jni flag).
6435   if (VM_Version::supports_sse()) {
6436     if (RestoreMXCSROnJNICalls) {
6437       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6438     } else if (CheckJNICalls) {
6439       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6440     }
6441   }
6442   if (VM_Version::supports_avx()) {
6443     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6444     vzeroupper();
6445   }
6446 
6447 #ifndef _LP64
6448   // Either restore the x87 floating pointer control word after returning
6449   // from the JNI call or verify that it wasn't changed.
6450   if (CheckJNICalls) {
6451     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6452   }
6453 #endif // _LP64
6454 }
6455 
6456 
6457 void MacroAssembler::load_klass(Register dst, Register src) {
6458 #ifdef _LP64
6459   if (UseCompressedClassPointers) {
6460     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6461     decode_klass_not_null(dst);
6462   } else
6463 #endif
6464     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6465 }
6466 
6467 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6468   load_klass(dst, src);
6469   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6470 }
6471 
6472 void MacroAssembler::store_klass(Register dst, Register src) {
6473 #ifdef _LP64
6474   if (UseCompressedClassPointers) {
6475     encode_klass_not_null(src);
6476     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6477   } else
6478 #endif
6479     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6480 }
6481 
6482 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6483 #ifdef _LP64
6484   // FIXME: Must change all places where we try to load the klass.
6485   if (UseCompressedOops) {
6486     movl(dst, src);
6487     decode_heap_oop(dst);
6488   } else
6489 #endif
6490     movptr(dst, src);
6491 }
6492 
6493 // Doesn't do verfication, generates fixed size code
6494 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6495 #ifdef _LP64
6496   if (UseCompressedOops) {
6497     movl(dst, src);
6498     decode_heap_oop_not_null(dst);
6499   } else
6500 #endif
6501     movptr(dst, src);
6502 }
6503 
6504 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6505 #ifdef _LP64
6506   if (UseCompressedOops) {
6507     assert(!dst.uses(src), "not enough registers");
6508     encode_heap_oop(src);
6509     movl(dst, src);
6510   } else
6511 #endif
6512     movptr(dst, src);
6513 }
6514 
6515 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6516   assert_different_registers(src1, tmp);
6517 #ifdef _LP64
6518   if (UseCompressedOops) {
6519     bool did_push = false;
6520     if (tmp == noreg) {
6521       tmp = rax;
6522       push(tmp);
6523       did_push = true;
6524       assert(!src2.uses(rsp), "can't push");
6525     }
6526     load_heap_oop(tmp, src2);
6527     cmpptr(src1, tmp);
6528     if (did_push)  pop(tmp);
6529   } else
6530 #endif
6531     cmpptr(src1, src2);
6532 }
6533 
6534 // Used for storing NULLs.
6535 void MacroAssembler::store_heap_oop_null(Address dst) {
6536 #ifdef _LP64
6537   if (UseCompressedOops) {
6538     movl(dst, (int32_t)NULL_WORD);
6539   } else {
6540     movslq(dst, (int32_t)NULL_WORD);
6541   }
6542 #else
6543   movl(dst, (int32_t)NULL_WORD);
6544 #endif
6545 }
6546 
6547 #ifdef _LP64
6548 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6549   if (UseCompressedClassPointers) {
6550     // Store to klass gap in destination
6551     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6552   }
6553 }
6554 
6555 #ifdef ASSERT
6556 void MacroAssembler::verify_heapbase(const char* msg) {
6557   assert (UseCompressedOops, "should be compressed");
6558   assert (Universe::heap() != NULL, "java heap should be initialized");
6559   if (CheckCompressedOops) {
6560     Label ok;
6561     push(rscratch1); // cmpptr trashes rscratch1
6562     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6563     jcc(Assembler::equal, ok);
6564     STOP(msg);
6565     bind(ok);
6566     pop(rscratch1);
6567   }
6568 }
6569 #endif
6570 
6571 // Algorithm must match oop.inline.hpp encode_heap_oop.
6572 void MacroAssembler::encode_heap_oop(Register r) {
6573 #ifdef ASSERT
6574   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6575 #endif
6576   verify_oop(r, "broken oop in encode_heap_oop");
6577   if (Universe::narrow_oop_base() == NULL) {
6578     if (Universe::narrow_oop_shift() != 0) {
6579       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6580       shrq(r, LogMinObjAlignmentInBytes);
6581     }
6582     return;
6583   }
6584   testq(r, r);
6585   cmovq(Assembler::equal, r, r12_heapbase);
6586   subq(r, r12_heapbase);
6587   shrq(r, LogMinObjAlignmentInBytes);
6588 }
6589 
6590 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6591 #ifdef ASSERT
6592   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6593   if (CheckCompressedOops) {
6594     Label ok;
6595     testq(r, r);
6596     jcc(Assembler::notEqual, ok);
6597     STOP("null oop passed to encode_heap_oop_not_null");
6598     bind(ok);
6599   }
6600 #endif
6601   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6602   if (Universe::narrow_oop_base() != NULL) {
6603     subq(r, r12_heapbase);
6604   }
6605   if (Universe::narrow_oop_shift() != 0) {
6606     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6607     shrq(r, LogMinObjAlignmentInBytes);
6608   }
6609 }
6610 
6611 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6612 #ifdef ASSERT
6613   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6614   if (CheckCompressedOops) {
6615     Label ok;
6616     testq(src, src);
6617     jcc(Assembler::notEqual, ok);
6618     STOP("null oop passed to encode_heap_oop_not_null2");
6619     bind(ok);
6620   }
6621 #endif
6622   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6623   if (dst != src) {
6624     movq(dst, src);
6625   }
6626   if (Universe::narrow_oop_base() != NULL) {
6627     subq(dst, r12_heapbase);
6628   }
6629   if (Universe::narrow_oop_shift() != 0) {
6630     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6631     shrq(dst, LogMinObjAlignmentInBytes);
6632   }
6633 }
6634 
6635 void  MacroAssembler::decode_heap_oop(Register r) {
6636 #ifdef ASSERT
6637   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6638 #endif
6639   if (Universe::narrow_oop_base() == NULL) {
6640     if (Universe::narrow_oop_shift() != 0) {
6641       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6642       shlq(r, LogMinObjAlignmentInBytes);
6643     }
6644   } else {
6645     Label done;
6646     shlq(r, LogMinObjAlignmentInBytes);
6647     jccb(Assembler::equal, done);
6648     addq(r, r12_heapbase);
6649     bind(done);
6650   }
6651   verify_oop(r, "broken oop in decode_heap_oop");
6652 }
6653 
6654 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6655   // Note: it will change flags
6656   assert (UseCompressedOops, "should only be used for compressed headers");
6657   assert (Universe::heap() != NULL, "java heap should be initialized");
6658   // Cannot assert, unverified entry point counts instructions (see .ad file)
6659   // vtableStubs also counts instructions in pd_code_size_limit.
6660   // Also do not verify_oop as this is called by verify_oop.
6661   if (Universe::narrow_oop_shift() != 0) {
6662     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6663     shlq(r, LogMinObjAlignmentInBytes);
6664     if (Universe::narrow_oop_base() != NULL) {
6665       addq(r, r12_heapbase);
6666     }
6667   } else {
6668     assert (Universe::narrow_oop_base() == NULL, "sanity");
6669   }
6670 }
6671 
6672 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6673   // Note: it will change flags
6674   assert (UseCompressedOops, "should only be used for compressed headers");
6675   assert (Universe::heap() != NULL, "java heap should be initialized");
6676   // Cannot assert, unverified entry point counts instructions (see .ad file)
6677   // vtableStubs also counts instructions in pd_code_size_limit.
6678   // Also do not verify_oop as this is called by verify_oop.
6679   if (Universe::narrow_oop_shift() != 0) {
6680     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6681     if (LogMinObjAlignmentInBytes == Address::times_8) {
6682       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6683     } else {
6684       if (dst != src) {
6685         movq(dst, src);
6686       }
6687       shlq(dst, LogMinObjAlignmentInBytes);
6688       if (Universe::narrow_oop_base() != NULL) {
6689         addq(dst, r12_heapbase);
6690       }
6691     }
6692   } else {
6693     assert (Universe::narrow_oop_base() == NULL, "sanity");
6694     if (dst != src) {
6695       movq(dst, src);
6696     }
6697   }
6698 }
6699 
6700 void MacroAssembler::encode_klass_not_null(Register r) {
6701   if (Universe::narrow_klass_base() != NULL) {
6702     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6703     assert(r != r12_heapbase, "Encoding a klass in r12");
6704     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6705     subq(r, r12_heapbase);
6706   }
6707   if (Universe::narrow_klass_shift() != 0) {
6708     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6709     shrq(r, LogKlassAlignmentInBytes);
6710   }
6711   if (Universe::narrow_klass_base() != NULL) {
6712     reinit_heapbase();
6713   }
6714 }
6715 
6716 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6717   if (dst == src) {
6718     encode_klass_not_null(src);
6719   } else {
6720     if (Universe::narrow_klass_base() != NULL) {
6721       mov64(dst, (int64_t)Universe::narrow_klass_base());
6722       negq(dst);
6723       addq(dst, src);
6724     } else {
6725       movptr(dst, src);
6726     }
6727     if (Universe::narrow_klass_shift() != 0) {
6728       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6729       shrq(dst, LogKlassAlignmentInBytes);
6730     }
6731   }
6732 }
6733 
6734 // Function instr_size_for_decode_klass_not_null() counts the instructions
6735 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6736 // when (Universe::heap() != NULL).  Hence, if the instructions they
6737 // generate change, then this method needs to be updated.
6738 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6739   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6740   if (Universe::narrow_klass_base() != NULL) {
6741     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6742     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6743   } else {
6744     // longest load decode klass function, mov64, leaq
6745     return 16;
6746   }
6747 }
6748 
6749 // !!! If the instructions that get generated here change then function
6750 // instr_size_for_decode_klass_not_null() needs to get updated.
6751 void  MacroAssembler::decode_klass_not_null(Register r) {
6752   // Note: it will change flags
6753   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6754   assert(r != r12_heapbase, "Decoding a klass in r12");
6755   // Cannot assert, unverified entry point counts instructions (see .ad file)
6756   // vtableStubs also counts instructions in pd_code_size_limit.
6757   // Also do not verify_oop as this is called by verify_oop.
6758   if (Universe::narrow_klass_shift() != 0) {
6759     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6760     shlq(r, LogKlassAlignmentInBytes);
6761   }
6762   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6763   if (Universe::narrow_klass_base() != NULL) {
6764     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6765     addq(r, r12_heapbase);
6766     reinit_heapbase();
6767   }
6768 }
6769 
6770 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6771   // Note: it will change flags
6772   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6773   if (dst == src) {
6774     decode_klass_not_null(dst);
6775   } else {
6776     // Cannot assert, unverified entry point counts instructions (see .ad file)
6777     // vtableStubs also counts instructions in pd_code_size_limit.
6778     // Also do not verify_oop as this is called by verify_oop.
6779     mov64(dst, (int64_t)Universe::narrow_klass_base());
6780     if (Universe::narrow_klass_shift() != 0) {
6781       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6782       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6783       leaq(dst, Address(dst, src, Address::times_8, 0));
6784     } else {
6785       addq(dst, src);
6786     }
6787   }
6788 }
6789 
6790 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6791   assert (UseCompressedOops, "should only be used for compressed headers");
6792   assert (Universe::heap() != NULL, "java heap should be initialized");
6793   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6794   int oop_index = oop_recorder()->find_index(obj);
6795   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6796   mov_narrow_oop(dst, oop_index, rspec);
6797 }
6798 
6799 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6800   assert (UseCompressedOops, "should only be used for compressed headers");
6801   assert (Universe::heap() != NULL, "java heap should be initialized");
6802   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6803   int oop_index = oop_recorder()->find_index(obj);
6804   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6805   mov_narrow_oop(dst, oop_index, rspec);
6806 }
6807 
6808 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6809   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6810   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6811   int klass_index = oop_recorder()->find_index(k);
6812   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6813   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6814 }
6815 
6816 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6817   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6818   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6819   int klass_index = oop_recorder()->find_index(k);
6820   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6821   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6822 }
6823 
6824 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6825   assert (UseCompressedOops, "should only be used for compressed headers");
6826   assert (Universe::heap() != NULL, "java heap should be initialized");
6827   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6828   int oop_index = oop_recorder()->find_index(obj);
6829   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6830   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6831 }
6832 
6833 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6834   assert (UseCompressedOops, "should only be used for compressed headers");
6835   assert (Universe::heap() != NULL, "java heap should be initialized");
6836   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6837   int oop_index = oop_recorder()->find_index(obj);
6838   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6839   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6840 }
6841 
6842 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6843   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6844   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6845   int klass_index = oop_recorder()->find_index(k);
6846   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6847   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6848 }
6849 
6850 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6851   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6852   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6853   int klass_index = oop_recorder()->find_index(k);
6854   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6855   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6856 }
6857 
6858 void MacroAssembler::reinit_heapbase() {
6859   if (UseCompressedOops || UseCompressedClassPointers) {
6860     if (Universe::heap() != NULL) {
6861       if (Universe::narrow_oop_base() == NULL) {
6862         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6863       } else {
6864         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6865       }
6866     } else {
6867       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6868     }
6869   }
6870 }
6871 
6872 #endif // _LP64
6873 
6874 
6875 // C2 compiled method's prolog code.
6876 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6877 
6878   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6879   // NativeJump::patch_verified_entry will be able to patch out the entry
6880   // code safely. The push to verify stack depth is ok at 5 bytes,
6881   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6882   // stack bang then we must use the 6 byte frame allocation even if
6883   // we have no frame. :-(
6884   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6885 
6886   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6887   // Remove word for return addr
6888   framesize -= wordSize;
6889   stack_bang_size -= wordSize;
6890 
6891   // Calls to C2R adapters often do not accept exceptional returns.
6892   // We require that their callers must bang for them.  But be careful, because
6893   // some VM calls (such as call site linkage) can use several kilobytes of
6894   // stack.  But the stack safety zone should account for that.
6895   // See bugs 4446381, 4468289, 4497237.
6896   if (stack_bang_size > 0) {
6897     generate_stack_overflow_check(stack_bang_size);
6898 
6899     // We always push rbp, so that on return to interpreter rbp, will be
6900     // restored correctly and we can correct the stack.
6901     push(rbp);
6902     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6903     if (PreserveFramePointer) {
6904       mov(rbp, rsp);
6905     }
6906     // Remove word for ebp
6907     framesize -= wordSize;
6908 
6909     // Create frame
6910     if (framesize) {
6911       subptr(rsp, framesize);
6912     }
6913   } else {
6914     // Create frame (force generation of a 4 byte immediate value)
6915     subptr_imm32(rsp, framesize);
6916 
6917     // Save RBP register now.
6918     framesize -= wordSize;
6919     movptr(Address(rsp, framesize), rbp);
6920     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6921     if (PreserveFramePointer) {
6922       movptr(rbp, rsp);
6923       if (framesize > 0) {
6924         addptr(rbp, framesize);
6925       }
6926     }
6927   }
6928 
6929   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6930     framesize -= wordSize;
6931     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6932   }
6933 
6934 #ifndef _LP64
6935   // If method sets FPU control word do it now
6936   if (fp_mode_24b) {
6937     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6938   }
6939   if (UseSSE >= 2 && VerifyFPU) {
6940     verify_FPU(0, "FPU stack must be clean on entry");
6941   }
6942 #endif
6943 
6944 #ifdef ASSERT
6945   if (VerifyStackAtCalls) {
6946     Label L;
6947     push(rax);
6948     mov(rax, rsp);
6949     andptr(rax, StackAlignmentInBytes-1);
6950     cmpptr(rax, StackAlignmentInBytes-wordSize);
6951     pop(rax);
6952     jcc(Assembler::equal, L);
6953     STOP("Stack is not properly aligned!");
6954     bind(L);
6955   }
6956 #endif
6957 
6958 }
6959 
6960 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
6961   // cnt - number of qwords (8-byte words).
6962   // base - start address, qword aligned.
6963   assert(base==rdi, "base register must be edi for rep stos");
6964   assert(tmp==rax,   "tmp register must be eax for rep stos");
6965   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6966 
6967   xorptr(tmp, tmp);
6968   if (UseFastStosb) {
6969     shlptr(cnt,3); // convert to number of bytes
6970     rep_stosb();
6971   } else {
6972     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
6973     rep_stos();
6974   }
6975 }
6976 
6977 #ifdef COMPILER2
6978 
6979 // IndexOf for constant substrings with size >= 8 chars
6980 // which don't need to be loaded through stack.
6981 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6982                                       Register cnt1, Register cnt2,
6983                                       int int_cnt2,  Register result,
6984                                       XMMRegister vec, Register tmp,
6985                                       int ae) {
6986   ShortBranchVerifier sbv(this);
6987   assert(UseSSE42Intrinsics, "SSE4.2 is required");
6988   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6989 
6990   // This method uses the pcmpestri instruction with bound registers
6991   //   inputs:
6992   //     xmm - substring
6993   //     rax - substring length (elements count)
6994   //     mem - scanned string
6995   //     rdx - string length (elements count)
6996   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6997   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6998   //   outputs:
6999   //     rcx - matched index in string
7000   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7001   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7002   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7003   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7004   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7005 
7006   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7007         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7008         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7009 
7010   // Note, inline_string_indexOf() generates checks:
7011   // if (substr.count > string.count) return -1;
7012   // if (substr.count == 0) return 0;
7013   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7014 
7015   // Load substring.
7016   if (ae == StrIntrinsicNode::UL) {
7017     pmovzxbw(vec, Address(str2, 0));
7018   } else {
7019     movdqu(vec, Address(str2, 0));
7020   }
7021   movl(cnt2, int_cnt2);
7022   movptr(result, str1); // string addr
7023 
7024   if (int_cnt2 > stride) {
7025     jmpb(SCAN_TO_SUBSTR);
7026 
7027     // Reload substr for rescan, this code
7028     // is executed only for large substrings (> 8 chars)
7029     bind(RELOAD_SUBSTR);
7030     if (ae == StrIntrinsicNode::UL) {
7031       pmovzxbw(vec, Address(str2, 0));
7032     } else {
7033       movdqu(vec, Address(str2, 0));
7034     }
7035     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7036 
7037     bind(RELOAD_STR);
7038     // We came here after the beginning of the substring was
7039     // matched but the rest of it was not so we need to search
7040     // again. Start from the next element after the previous match.
7041 
7042     // cnt2 is number of substring reminding elements and
7043     // cnt1 is number of string reminding elements when cmp failed.
7044     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7045     subl(cnt1, cnt2);
7046     addl(cnt1, int_cnt2);
7047     movl(cnt2, int_cnt2); // Now restore cnt2
7048 
7049     decrementl(cnt1);     // Shift to next element
7050     cmpl(cnt1, cnt2);
7051     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7052 
7053     addptr(result, (1<<scale1));
7054 
7055   } // (int_cnt2 > 8)
7056 
7057   // Scan string for start of substr in 16-byte vectors
7058   bind(SCAN_TO_SUBSTR);
7059   pcmpestri(vec, Address(result, 0), mode);
7060   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7061   subl(cnt1, stride);
7062   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7063   cmpl(cnt1, cnt2);
7064   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7065   addptr(result, 16);
7066   jmpb(SCAN_TO_SUBSTR);
7067 
7068   // Found a potential substr
7069   bind(FOUND_CANDIDATE);
7070   // Matched whole vector if first element matched (tmp(rcx) == 0).
7071   if (int_cnt2 == stride) {
7072     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7073   } else { // int_cnt2 > 8
7074     jccb(Assembler::overflow, FOUND_SUBSTR);
7075   }
7076   // After pcmpestri tmp(rcx) contains matched element index
7077   // Compute start addr of substr
7078   lea(result, Address(result, tmp, scale1));
7079 
7080   // Make sure string is still long enough
7081   subl(cnt1, tmp);
7082   cmpl(cnt1, cnt2);
7083   if (int_cnt2 == stride) {
7084     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7085   } else { // int_cnt2 > 8
7086     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7087   }
7088   // Left less then substring.
7089 
7090   bind(RET_NOT_FOUND);
7091   movl(result, -1);
7092   jmpb(EXIT);
7093 
7094   if (int_cnt2 > stride) {
7095     // This code is optimized for the case when whole substring
7096     // is matched if its head is matched.
7097     bind(MATCH_SUBSTR_HEAD);
7098     pcmpestri(vec, Address(result, 0), mode);
7099     // Reload only string if does not match
7100     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7101 
7102     Label CONT_SCAN_SUBSTR;
7103     // Compare the rest of substring (> 8 chars).
7104     bind(FOUND_SUBSTR);
7105     // First 8 chars are already matched.
7106     negptr(cnt2);
7107     addptr(cnt2, stride);
7108 
7109     bind(SCAN_SUBSTR);
7110     subl(cnt1, stride);
7111     cmpl(cnt2, -stride); // Do not read beyond substring
7112     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7113     // Back-up strings to avoid reading beyond substring:
7114     // cnt1 = cnt1 - cnt2 + 8
7115     addl(cnt1, cnt2); // cnt2 is negative
7116     addl(cnt1, stride);
7117     movl(cnt2, stride); negptr(cnt2);
7118     bind(CONT_SCAN_SUBSTR);
7119     if (int_cnt2 < (int)G) {
7120       int tail_off1 = int_cnt2<<scale1;
7121       int tail_off2 = int_cnt2<<scale2;
7122       if (ae == StrIntrinsicNode::UL) {
7123         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7124       } else {
7125         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7126       }
7127       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7128     } else {
7129       // calculate index in register to avoid integer overflow (int_cnt2*2)
7130       movl(tmp, int_cnt2);
7131       addptr(tmp, cnt2);
7132       if (ae == StrIntrinsicNode::UL) {
7133         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7134       } else {
7135         movdqu(vec, Address(str2, tmp, scale2, 0));
7136       }
7137       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7138     }
7139     // Need to reload strings pointers if not matched whole vector
7140     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7141     addptr(cnt2, stride);
7142     jcc(Assembler::negative, SCAN_SUBSTR);
7143     // Fall through if found full substring
7144 
7145   } // (int_cnt2 > 8)
7146 
7147   bind(RET_FOUND);
7148   // Found result if we matched full small substring.
7149   // Compute substr offset
7150   subptr(result, str1);
7151   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7152     shrl(result, 1); // index
7153   }
7154   bind(EXIT);
7155 
7156 } // string_indexofC8
7157 
7158 // Small strings are loaded through stack if they cross page boundary.
7159 void MacroAssembler::string_indexof(Register str1, Register str2,
7160                                     Register cnt1, Register cnt2,
7161                                     int int_cnt2,  Register result,
7162                                     XMMRegister vec, Register tmp,
7163                                     int ae) {
7164   ShortBranchVerifier sbv(this);
7165   assert(UseSSE42Intrinsics, "SSE4.2 is required");
7166   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7167 
7168   //
7169   // int_cnt2 is length of small (< 8 chars) constant substring
7170   // or (-1) for non constant substring in which case its length
7171   // is in cnt2 register.
7172   //
7173   // Note, inline_string_indexOf() generates checks:
7174   // if (substr.count > string.count) return -1;
7175   // if (substr.count == 0) return 0;
7176   //
7177   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7178   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7179   // This method uses the pcmpestri instruction with bound registers
7180   //   inputs:
7181   //     xmm - substring
7182   //     rax - substring length (elements count)
7183   //     mem - scanned string
7184   //     rdx - string length (elements count)
7185   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7186   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7187   //   outputs:
7188   //     rcx - matched index in string
7189   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7190   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7191   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7192   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7193 
7194   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7195         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7196         FOUND_CANDIDATE;
7197 
7198   { //========================================================
7199     // We don't know where these strings are located
7200     // and we can't read beyond them. Load them through stack.
7201     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7202 
7203     movptr(tmp, rsp); // save old SP
7204 
7205     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7206       if (int_cnt2 == (1>>scale2)) { // One byte
7207         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7208         load_unsigned_byte(result, Address(str2, 0));
7209         movdl(vec, result); // move 32 bits
7210       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7211         // Not enough header space in 32-bit VM: 12+3 = 15.
7212         movl(result, Address(str2, -1));
7213         shrl(result, 8);
7214         movdl(vec, result); // move 32 bits
7215       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7216         load_unsigned_short(result, Address(str2, 0));
7217         movdl(vec, result); // move 32 bits
7218       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7219         movdl(vec, Address(str2, 0)); // move 32 bits
7220       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7221         movq(vec, Address(str2, 0));  // move 64 bits
7222       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7223         // Array header size is 12 bytes in 32-bit VM
7224         // + 6 bytes for 3 chars == 18 bytes,
7225         // enough space to load vec and shift.
7226         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7227         if (ae == StrIntrinsicNode::UL) {
7228           int tail_off = int_cnt2-8;
7229           pmovzxbw(vec, Address(str2, tail_off));
7230           psrldq(vec, -2*tail_off);
7231         }
7232         else {
7233           int tail_off = int_cnt2*(1<<scale2);
7234           movdqu(vec, Address(str2, tail_off-16));
7235           psrldq(vec, 16-tail_off);
7236         }
7237       }
7238     } else { // not constant substring
7239       cmpl(cnt2, stride);
7240       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7241 
7242       // We can read beyond string if srt+16 does not cross page boundary
7243       // since heaps are aligned and mapped by pages.
7244       assert(os::vm_page_size() < (int)G, "default page should be small");
7245       movl(result, str2); // We need only low 32 bits
7246       andl(result, (os::vm_page_size()-1));
7247       cmpl(result, (os::vm_page_size()-16));
7248       jccb(Assembler::belowEqual, CHECK_STR);
7249 
7250       // Move small strings to stack to allow load 16 bytes into vec.
7251       subptr(rsp, 16);
7252       int stk_offset = wordSize-(1<<scale2);
7253       push(cnt2);
7254 
7255       bind(COPY_SUBSTR);
7256       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7257         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7258         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7259       } else if (ae == StrIntrinsicNode::UU) {
7260         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7261         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7262       }
7263       decrement(cnt2);
7264       jccb(Assembler::notZero, COPY_SUBSTR);
7265 
7266       pop(cnt2);
7267       movptr(str2, rsp);  // New substring address
7268     } // non constant
7269 
7270     bind(CHECK_STR);
7271     cmpl(cnt1, stride);
7272     jccb(Assembler::aboveEqual, BIG_STRINGS);
7273 
7274     // Check cross page boundary.
7275     movl(result, str1); // We need only low 32 bits
7276     andl(result, (os::vm_page_size()-1));
7277     cmpl(result, (os::vm_page_size()-16));
7278     jccb(Assembler::belowEqual, BIG_STRINGS);
7279 
7280     subptr(rsp, 16);
7281     int stk_offset = -(1<<scale1);
7282     if (int_cnt2 < 0) { // not constant
7283       push(cnt2);
7284       stk_offset += wordSize;
7285     }
7286     movl(cnt2, cnt1);
7287 
7288     bind(COPY_STR);
7289     if (ae == StrIntrinsicNode::LL) {
7290       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7291       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7292     } else {
7293       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7294       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7295     }
7296     decrement(cnt2);
7297     jccb(Assembler::notZero, COPY_STR);
7298 
7299     if (int_cnt2 < 0) { // not constant
7300       pop(cnt2);
7301     }
7302     movptr(str1, rsp);  // New string address
7303 
7304     bind(BIG_STRINGS);
7305     // Load substring.
7306     if (int_cnt2 < 0) { // -1
7307       if (ae == StrIntrinsicNode::UL) {
7308         pmovzxbw(vec, Address(str2, 0));
7309       } else {
7310         movdqu(vec, Address(str2, 0));
7311       }
7312       push(cnt2);       // substr count
7313       push(str2);       // substr addr
7314       push(str1);       // string addr
7315     } else {
7316       // Small (< 8 chars) constant substrings are loaded already.
7317       movl(cnt2, int_cnt2);
7318     }
7319     push(tmp);  // original SP
7320 
7321   } // Finished loading
7322 
7323   //========================================================
7324   // Start search
7325   //
7326 
7327   movptr(result, str1); // string addr
7328 
7329   if (int_cnt2  < 0) {  // Only for non constant substring
7330     jmpb(SCAN_TO_SUBSTR);
7331 
7332     // SP saved at sp+0
7333     // String saved at sp+1*wordSize
7334     // Substr saved at sp+2*wordSize
7335     // Substr count saved at sp+3*wordSize
7336 
7337     // Reload substr for rescan, this code
7338     // is executed only for large substrings (> 8 chars)
7339     bind(RELOAD_SUBSTR);
7340     movptr(str2, Address(rsp, 2*wordSize));
7341     movl(cnt2, Address(rsp, 3*wordSize));
7342     if (ae == StrIntrinsicNode::UL) {
7343       pmovzxbw(vec, Address(str2, 0));
7344     } else {
7345       movdqu(vec, Address(str2, 0));
7346     }
7347     // We came here after the beginning of the substring was
7348     // matched but the rest of it was not so we need to search
7349     // again. Start from the next element after the previous match.
7350     subptr(str1, result); // Restore counter
7351     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7352       shrl(str1, 1);
7353     }
7354     addl(cnt1, str1);
7355     decrementl(cnt1);   // Shift to next element
7356     cmpl(cnt1, cnt2);
7357     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7358 
7359     addptr(result, (1<<scale1));
7360   } // non constant
7361 
7362   // Scan string for start of substr in 16-byte vectors
7363   bind(SCAN_TO_SUBSTR);
7364   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7365   pcmpestri(vec, Address(result, 0), mode);
7366   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7367   subl(cnt1, stride);
7368   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7369   cmpl(cnt1, cnt2);
7370   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7371   addptr(result, 16);
7372 
7373   bind(ADJUST_STR);
7374   cmpl(cnt1, stride); // Do not read beyond string
7375   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7376   // Back-up string to avoid reading beyond string.
7377   lea(result, Address(result, cnt1, scale1, -16));
7378   movl(cnt1, stride);
7379   jmpb(SCAN_TO_SUBSTR);
7380 
7381   // Found a potential substr
7382   bind(FOUND_CANDIDATE);
7383   // After pcmpestri tmp(rcx) contains matched element index
7384 
7385   // Make sure string is still long enough
7386   subl(cnt1, tmp);
7387   cmpl(cnt1, cnt2);
7388   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7389   // Left less then substring.
7390 
7391   bind(RET_NOT_FOUND);
7392   movl(result, -1);
7393   jmpb(CLEANUP);
7394 
7395   bind(FOUND_SUBSTR);
7396   // Compute start addr of substr
7397   lea(result, Address(result, tmp, scale1));
7398   if (int_cnt2 > 0) { // Constant substring
7399     // Repeat search for small substring (< 8 chars)
7400     // from new point without reloading substring.
7401     // Have to check that we don't read beyond string.
7402     cmpl(tmp, stride-int_cnt2);
7403     jccb(Assembler::greater, ADJUST_STR);
7404     // Fall through if matched whole substring.
7405   } else { // non constant
7406     assert(int_cnt2 == -1, "should be != 0");
7407 
7408     addl(tmp, cnt2);
7409     // Found result if we matched whole substring.
7410     cmpl(tmp, stride);
7411     jccb(Assembler::lessEqual, RET_FOUND);
7412 
7413     // Repeat search for small substring (<= 8 chars)
7414     // from new point 'str1' without reloading substring.
7415     cmpl(cnt2, stride);
7416     // Have to check that we don't read beyond string.
7417     jccb(Assembler::lessEqual, ADJUST_STR);
7418 
7419     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7420     // Compare the rest of substring (> 8 chars).
7421     movptr(str1, result);
7422 
7423     cmpl(tmp, cnt2);
7424     // First 8 chars are already matched.
7425     jccb(Assembler::equal, CHECK_NEXT);
7426 
7427     bind(SCAN_SUBSTR);
7428     pcmpestri(vec, Address(str1, 0), mode);
7429     // Need to reload strings pointers if not matched whole vector
7430     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7431 
7432     bind(CHECK_NEXT);
7433     subl(cnt2, stride);
7434     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7435     addptr(str1, 16);
7436     if (ae == StrIntrinsicNode::UL) {
7437       addptr(str2, 8);
7438     } else {
7439       addptr(str2, 16);
7440     }
7441     subl(cnt1, stride);
7442     cmpl(cnt2, stride); // Do not read beyond substring
7443     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7444     // Back-up strings to avoid reading beyond substring.
7445 
7446     if (ae == StrIntrinsicNode::UL) {
7447       lea(str2, Address(str2, cnt2, scale2, -8));
7448       lea(str1, Address(str1, cnt2, scale1, -16));
7449     } else {
7450       lea(str2, Address(str2, cnt2, scale2, -16));
7451       lea(str1, Address(str1, cnt2, scale1, -16));
7452     }
7453     subl(cnt1, cnt2);
7454     movl(cnt2, stride);
7455     addl(cnt1, stride);
7456     bind(CONT_SCAN_SUBSTR);
7457     if (ae == StrIntrinsicNode::UL) {
7458       pmovzxbw(vec, Address(str2, 0));
7459     } else {
7460       movdqu(vec, Address(str2, 0));
7461     }
7462     jmpb(SCAN_SUBSTR);
7463 
7464     bind(RET_FOUND_LONG);
7465     movptr(str1, Address(rsp, wordSize));
7466   } // non constant
7467 
7468   bind(RET_FOUND);
7469   // Compute substr offset
7470   subptr(result, str1);
7471   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7472     shrl(result, 1); // index
7473   }
7474   bind(CLEANUP);
7475   pop(rsp); // restore SP
7476 
7477 } // string_indexof
7478 
7479 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7480                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7481   ShortBranchVerifier sbv(this);
7482   assert(UseSSE42Intrinsics, "SSE4.2 is required");
7483 
7484   int stride = 8;
7485 
7486   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7487         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7488         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7489         FOUND_SEQ_CHAR, DONE_LABEL;
7490 
7491   movptr(result, str1);
7492   if (UseAVX >= 2) {
7493     cmpl(cnt1, stride);
7494     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7495     cmpl(cnt1, 2*stride);
7496     jccb(Assembler::less, SCAN_TO_8_CHAR_INIT);
7497     movdl(vec1, ch);
7498     vpbroadcastw(vec1, vec1);
7499     vpxor(vec2, vec2);
7500     movl(tmp, cnt1);
7501     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7502     andl(cnt1,0x0000000F);  //tail count (in chars)
7503 
7504     bind(SCAN_TO_16_CHAR_LOOP);
7505     vmovdqu(vec3, Address(result, 0));
7506     vpcmpeqw(vec3, vec3, vec1, 1);
7507     vptest(vec2, vec3);
7508     jcc(Assembler::carryClear, FOUND_CHAR);
7509     addptr(result, 32);
7510     subl(tmp, 2*stride);
7511     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7512     jmp(SCAN_TO_8_CHAR);
7513     bind(SCAN_TO_8_CHAR_INIT);
7514     movdl(vec1, ch);
7515     pshuflw(vec1, vec1, 0x00);
7516     pshufd(vec1, vec1, 0);
7517     pxor(vec2, vec2);
7518   }
7519   if (UseAVX >= 2 || UseSSE42Intrinsics) {
7520     bind(SCAN_TO_8_CHAR);
7521     cmpl(cnt1, stride);
7522     if (UseAVX >= 2) {
7523       jccb(Assembler::less, SCAN_TO_CHAR);
7524     }
7525     if (!(UseAVX >= 2)) {
7526       jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7527       movdl(vec1, ch);
7528       pshuflw(vec1, vec1, 0x00);
7529       pshufd(vec1, vec1, 0);
7530       pxor(vec2, vec2);
7531     }
7532     movl(tmp, cnt1);
7533     andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7534     andl(cnt1,0x00000007);  //tail count (in chars)
7535 
7536     bind(SCAN_TO_8_CHAR_LOOP);
7537     movdqu(vec3, Address(result, 0));
7538     pcmpeqw(vec3, vec1);
7539     ptest(vec2, vec3);
7540     jcc(Assembler::carryClear, FOUND_CHAR);
7541     addptr(result, 16);
7542     subl(tmp, stride);
7543     jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7544   }
7545   bind(SCAN_TO_CHAR);
7546   testl(cnt1, cnt1);
7547   jcc(Assembler::zero, RET_NOT_FOUND);
7548 
7549   bind(SCAN_TO_CHAR_LOOP);
7550   load_unsigned_short(tmp, Address(result, 0));
7551   cmpl(ch, tmp);
7552   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7553   addptr(result, 2);
7554   subl(cnt1, 1);
7555   jccb(Assembler::zero, RET_NOT_FOUND);
7556   jmp(SCAN_TO_CHAR_LOOP);
7557 
7558   bind(RET_NOT_FOUND);
7559   movl(result, -1);
7560   jmpb(DONE_LABEL);
7561 
7562   if (UseAVX >= 2 || UseSSE42Intrinsics) {
7563     bind(FOUND_CHAR);
7564     if (UseAVX >= 2) {
7565       vpmovmskb(tmp, vec3);
7566     } else {
7567       pmovmskb(tmp, vec3);
7568     }
7569     bsfl(ch, tmp);
7570     addl(result, ch);
7571   }
7572 
7573   bind(FOUND_SEQ_CHAR);
7574   subptr(result, str1);
7575   shrl(result, 1);
7576 
7577   bind(DONE_LABEL);
7578 } // string_indexof_char
7579 
7580 // helper function for string_compare
7581 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7582                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7583                                         Address::ScaleFactor scale2, Register index, int ae) {
7584   if (ae == StrIntrinsicNode::LL) {
7585     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7586     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7587   } else if (ae == StrIntrinsicNode::UU) {
7588     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7589     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7590   } else {
7591     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7592     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7593   }
7594 }
7595 
7596 // Compare strings, used for char[] and byte[].
7597 void MacroAssembler::string_compare(Register str1, Register str2,
7598                                     Register cnt1, Register cnt2, Register result,
7599                                     XMMRegister vec1, int ae) {
7600   ShortBranchVerifier sbv(this);
7601   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7602   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7603   Address::ScaleFactor scale, scale1, scale2;
7604 
7605   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7606     shrl(cnt2, 1);
7607   }
7608   // Compute the minimum of the string lengths and the
7609   // difference of the string lengths (stack).
7610   // Do the conditional move stuff
7611   movl(result, cnt1);
7612   subl(cnt1, cnt2);
7613   push(cnt1);
7614   cmov32(Assembler::lessEqual, cnt2, result);
7615 
7616   // Is the minimum length zero?
7617   testl(cnt2, cnt2);
7618   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7619   if (ae == StrIntrinsicNode::LL) {
7620     // Load first bytes
7621     load_unsigned_byte(result, Address(str1, 0));
7622     load_unsigned_byte(cnt1, Address(str2, 0));
7623   } else if (ae == StrIntrinsicNode::UU) {
7624     // Load first characters
7625     load_unsigned_short(result, Address(str1, 0));
7626     load_unsigned_short(cnt1, Address(str2, 0));
7627   } else {
7628     load_unsigned_byte(result, Address(str1, 0));
7629     load_unsigned_short(cnt1, Address(str2, 0));
7630   }
7631   subl(result, cnt1);
7632   jcc(Assembler::notZero,  POP_LABEL);
7633 
7634   if (ae == StrIntrinsicNode::UU) {
7635     // Divide length by 2 to get number of chars
7636     shrl(cnt2, 1);
7637   }
7638   cmpl(cnt2, 1);
7639   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7640 
7641   // Check if the strings start at the same location and setup scale and stride
7642   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7643     cmpptr(str1, str2);
7644     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7645     if (ae == StrIntrinsicNode::LL) {
7646       scale = Address::times_1;
7647       stride = 16;
7648     } else {
7649       scale = Address::times_2;
7650       stride = 8;
7651     }
7652   } else {
7653     scale = Address::no_scale;  // not used
7654     scale1 = Address::times_1;
7655     scale2 = Address::times_2;
7656     stride = 8;
7657   }
7658 
7659   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7660     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7661     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7662     Label COMPARE_TAIL_LONG;
7663     int pcmpmask = 0x19;
7664     if (ae == StrIntrinsicNode::LL) {
7665       pcmpmask &= ~0x01;
7666     }
7667 
7668     // Setup to compare 16-chars (32-bytes) vectors,
7669     // start from first character again because it has aligned address.
7670     if (ae == StrIntrinsicNode::LL) {
7671       stride2 = 32;
7672     } else {
7673       stride2 = 16;
7674     }
7675     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7676       adr_stride = stride << scale;
7677     } else {
7678       adr_stride1 = 8;  //stride << scale1;
7679       adr_stride2 = 16; //stride << scale2;
7680     }
7681 
7682     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7683     // rax and rdx are used by pcmpestri as elements counters
7684     movl(result, cnt2);
7685     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7686     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7687 
7688     // fast path : compare first 2 8-char vectors.
7689     bind(COMPARE_16_CHARS);
7690     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7691       movdqu(vec1, Address(str1, 0));
7692     } else {
7693       pmovzxbw(vec1, Address(str1, 0));
7694     }
7695     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7696     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7697 
7698     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7699       movdqu(vec1, Address(str1, adr_stride));
7700       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7701     } else {
7702       pmovzxbw(vec1, Address(str1, adr_stride1));
7703       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7704     }
7705     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7706     addl(cnt1, stride);
7707 
7708     // Compare the characters at index in cnt1
7709     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7710     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7711     subl(result, cnt2);
7712     jmp(POP_LABEL);
7713 
7714     // Setup the registers to start vector comparison loop
7715     bind(COMPARE_WIDE_VECTORS);
7716     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7717       lea(str1, Address(str1, result, scale));
7718       lea(str2, Address(str2, result, scale));
7719     } else {
7720       lea(str1, Address(str1, result, scale1));
7721       lea(str2, Address(str2, result, scale2));
7722     }
7723     subl(result, stride2);
7724     subl(cnt2, stride2);
7725     jccb(Assembler::zero, COMPARE_WIDE_TAIL);
7726     negptr(result);
7727 
7728     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7729     bind(COMPARE_WIDE_VECTORS_LOOP);
7730     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7731       vmovdqu(vec1, Address(str1, result, scale));
7732       vpxor(vec1, Address(str2, result, scale));
7733     } else {
7734       vpmovzxbw(vec1, Address(str1, result, scale1));
7735       vpxor(vec1, Address(str2, result, scale2));
7736     }
7737     vptest(vec1, vec1);
7738     jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
7739     addptr(result, stride2);
7740     subl(cnt2, stride2);
7741     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7742     // clean upper bits of YMM registers
7743     vpxor(vec1, vec1);
7744 
7745     // compare wide vectors tail
7746     bind(COMPARE_WIDE_TAIL);
7747     testptr(result, result);
7748     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7749 
7750     movl(result, stride2);
7751     movl(cnt2, result);
7752     negptr(result);
7753     jmpb(COMPARE_WIDE_VECTORS_LOOP);
7754 
7755     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7756     bind(VECTOR_NOT_EQUAL);
7757     // clean upper bits of YMM registers
7758     vpxor(vec1, vec1);
7759     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7760       lea(str1, Address(str1, result, scale));
7761       lea(str2, Address(str2, result, scale));
7762     } else {
7763       lea(str1, Address(str1, result, scale1));
7764       lea(str2, Address(str2, result, scale2));
7765     }
7766     jmp(COMPARE_16_CHARS);
7767 
7768     // Compare tail chars, length between 1 to 15 chars
7769     bind(COMPARE_TAIL_LONG);
7770     movl(cnt2, result);
7771     cmpl(cnt2, stride);
7772     jccb(Assembler::less, COMPARE_SMALL_STR);
7773 
7774     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7775       movdqu(vec1, Address(str1, 0));
7776     } else {
7777       pmovzxbw(vec1, Address(str1, 0));
7778     }
7779     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7780     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7781     subptr(cnt2, stride);
7782     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7783     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7784       lea(str1, Address(str1, result, scale));
7785       lea(str2, Address(str2, result, scale));
7786     } else {
7787       lea(str1, Address(str1, result, scale1));
7788       lea(str2, Address(str2, result, scale2));
7789     }
7790     negptr(cnt2);
7791     jmpb(WHILE_HEAD_LABEL);
7792 
7793     bind(COMPARE_SMALL_STR);
7794   } else if (UseSSE42Intrinsics) {
7795     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7796     int pcmpmask = 0x19;
7797     // Setup to compare 8-char (16-byte) vectors,
7798     // start from first character again because it has aligned address.
7799     movl(result, cnt2);
7800     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7801     if (ae == StrIntrinsicNode::LL) {
7802       pcmpmask &= ~0x01;
7803     }
7804     jccb(Assembler::zero, COMPARE_TAIL);
7805     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7806       lea(str1, Address(str1, result, scale));
7807       lea(str2, Address(str2, result, scale));
7808     } else {
7809       lea(str1, Address(str1, result, scale1));
7810       lea(str2, Address(str2, result, scale2));
7811     }
7812     negptr(result);
7813 
7814     // pcmpestri
7815     //   inputs:
7816     //     vec1- substring
7817     //     rax - negative string length (elements count)
7818     //     mem - scanned string
7819     //     rdx - string length (elements count)
7820     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7821     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7822     //   outputs:
7823     //     rcx - first mismatched element index
7824     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7825 
7826     bind(COMPARE_WIDE_VECTORS);
7827     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7828       movdqu(vec1, Address(str1, result, scale));
7829       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7830     } else {
7831       pmovzxbw(vec1, Address(str1, result, scale1));
7832       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7833     }
7834     // After pcmpestri cnt1(rcx) contains mismatched element index
7835 
7836     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7837     addptr(result, stride);
7838     subptr(cnt2, stride);
7839     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7840 
7841     // compare wide vectors tail
7842     testptr(result, result);
7843     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7844 
7845     movl(cnt2, stride);
7846     movl(result, stride);
7847     negptr(result);
7848     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7849       movdqu(vec1, Address(str1, result, scale));
7850       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7851     } else {
7852       pmovzxbw(vec1, Address(str1, result, scale1));
7853       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7854     }
7855     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7856 
7857     // Mismatched characters in the vectors
7858     bind(VECTOR_NOT_EQUAL);
7859     addptr(cnt1, result);
7860     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7861     subl(result, cnt2);
7862     jmpb(POP_LABEL);
7863 
7864     bind(COMPARE_TAIL); // limit is zero
7865     movl(cnt2, result);
7866     // Fallthru to tail compare
7867   }
7868   // Shift str2 and str1 to the end of the arrays, negate min
7869   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7870     lea(str1, Address(str1, cnt2, scale));
7871     lea(str2, Address(str2, cnt2, scale));
7872   } else {
7873     lea(str1, Address(str1, cnt2, scale1));
7874     lea(str2, Address(str2, cnt2, scale2));
7875   }
7876   decrementl(cnt2);  // first character was compared already
7877   negptr(cnt2);
7878 
7879   // Compare the rest of the elements
7880   bind(WHILE_HEAD_LABEL);
7881   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7882   subl(result, cnt1);
7883   jccb(Assembler::notZero, POP_LABEL);
7884   increment(cnt2);
7885   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7886 
7887   // Strings are equal up to min length.  Return the length difference.
7888   bind(LENGTH_DIFF_LABEL);
7889   pop(result);
7890   if (ae == StrIntrinsicNode::UU) {
7891     // Divide diff by 2 to get number of chars
7892     sarl(result, 1);
7893   }
7894   jmpb(DONE_LABEL);
7895 
7896   // Discard the stored length difference
7897   bind(POP_LABEL);
7898   pop(cnt1);
7899 
7900   // That's it
7901   bind(DONE_LABEL);
7902   if(ae == StrIntrinsicNode::UL) {
7903     negl(result);
7904   }
7905 }
7906 
7907 // Search for Non-ASCII character (Negative byte value) in a byte array,
7908 // return true if it has any and false otherwise.
7909 void MacroAssembler::has_negatives(Register ary1, Register len,
7910                                    Register result, Register tmp1,
7911                                    XMMRegister vec1, XMMRegister vec2) {
7912 
7913   // rsi: byte array
7914   // rcx: len
7915   // rax: result
7916   ShortBranchVerifier sbv(this);
7917   assert_different_registers(ary1, len, result, tmp1);
7918   assert_different_registers(vec1, vec2);
7919   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7920 
7921   // len == 0
7922   testl(len, len);
7923   jcc(Assembler::zero, FALSE_LABEL);
7924 
7925   movl(result, len); // copy
7926 
7927   if (UseAVX >= 2) {
7928     // With AVX2, use 32-byte vector compare
7929     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7930 
7931     // Compare 32-byte vectors
7932     andl(result, 0x0000001f);  //   tail count (in bytes)
7933     andl(len, 0xffffffe0);   // vector count (in bytes)
7934     jccb(Assembler::zero, COMPARE_TAIL);
7935 
7936     lea(ary1, Address(ary1, len, Address::times_1));
7937     negptr(len);
7938 
7939     movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7940     movdl(vec2, tmp1);
7941     vpbroadcastd(vec2, vec2);
7942 
7943     bind(COMPARE_WIDE_VECTORS);
7944     vmovdqu(vec1, Address(ary1, len, Address::times_1));
7945     vptest(vec1, vec2);
7946     jccb(Assembler::notZero, TRUE_LABEL);
7947     addptr(len, 32);
7948     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7949 
7950     testl(result, result);
7951     jccb(Assembler::zero, FALSE_LABEL);
7952 
7953     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7954     vptest(vec1, vec2);
7955     jccb(Assembler::notZero, TRUE_LABEL);
7956     jmpb(FALSE_LABEL);
7957 
7958     bind(COMPARE_TAIL); // len is zero
7959     movl(len, result);
7960     // Fallthru to tail compare
7961   } else if (UseSSE42Intrinsics) {
7962     // With SSE4.2, use double quad vector compare
7963     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7964 
7965     // Compare 16-byte vectors
7966     andl(result, 0x0000000f);  //   tail count (in bytes)
7967     andl(len, 0xfffffff0);   // vector count (in bytes)
7968     jccb(Assembler::zero, COMPARE_TAIL);
7969 
7970     lea(ary1, Address(ary1, len, Address::times_1));
7971     negptr(len);
7972 
7973     movl(tmp1, 0x80808080);
7974     movdl(vec2, tmp1);
7975     pshufd(vec2, vec2, 0);
7976 
7977     bind(COMPARE_WIDE_VECTORS);
7978     movdqu(vec1, Address(ary1, len, Address::times_1));
7979     ptest(vec1, vec2);
7980     jccb(Assembler::notZero, TRUE_LABEL);
7981     addptr(len, 16);
7982     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7983 
7984     testl(result, result);
7985     jccb(Assembler::zero, FALSE_LABEL);
7986 
7987     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7988     ptest(vec1, vec2);
7989     jccb(Assembler::notZero, TRUE_LABEL);
7990     jmpb(FALSE_LABEL);
7991 
7992     bind(COMPARE_TAIL); // len is zero
7993     movl(len, result);
7994     // Fallthru to tail compare
7995   }
7996 
7997   // Compare 4-byte vectors
7998   andl(len, 0xfffffffc); // vector count (in bytes)
7999   jccb(Assembler::zero, COMPARE_CHAR);
8000 
8001   lea(ary1, Address(ary1, len, Address::times_1));
8002   negptr(len);
8003 
8004   bind(COMPARE_VECTORS);
8005   movl(tmp1, Address(ary1, len, Address::times_1));
8006   andl(tmp1, 0x80808080);
8007   jccb(Assembler::notZero, TRUE_LABEL);
8008   addptr(len, 4);
8009   jcc(Assembler::notZero, COMPARE_VECTORS);
8010 
8011   // Compare trailing char (final 2 bytes), if any
8012   bind(COMPARE_CHAR);
8013   testl(result, 0x2);   // tail  char
8014   jccb(Assembler::zero, COMPARE_BYTE);
8015   load_unsigned_short(tmp1, Address(ary1, 0));
8016   andl(tmp1, 0x00008080);
8017   jccb(Assembler::notZero, TRUE_LABEL);
8018   subptr(result, 2);
8019   lea(ary1, Address(ary1, 2));
8020 
8021   bind(COMPARE_BYTE);
8022   testl(result, 0x1);   // tail  byte
8023   jccb(Assembler::zero, FALSE_LABEL);
8024   load_unsigned_byte(tmp1, Address(ary1, 0));
8025   andl(tmp1, 0x00000080);
8026   jccb(Assembler::notEqual, TRUE_LABEL);
8027   jmpb(FALSE_LABEL);
8028 
8029   bind(TRUE_LABEL);
8030   movl(result, 1);   // return true
8031   jmpb(DONE);
8032 
8033   bind(FALSE_LABEL);
8034   xorl(result, result); // return false
8035 
8036   // That's it
8037   bind(DONE);
8038   if (UseAVX >= 2) {
8039     // clean upper bits of YMM registers
8040     vpxor(vec1, vec1);
8041     vpxor(vec2, vec2);
8042   }
8043 }
8044 
8045 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8046 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8047                                    Register limit, Register result, Register chr,
8048                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8049   ShortBranchVerifier sbv(this);
8050   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8051 
8052   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8053   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8054 
8055   if (is_array_equ) {
8056     // Check the input args
8057     cmpptr(ary1, ary2);
8058     jcc(Assembler::equal, TRUE_LABEL);
8059 
8060     // Need additional checks for arrays_equals.
8061     testptr(ary1, ary1);
8062     jcc(Assembler::zero, FALSE_LABEL);
8063     testptr(ary2, ary2);
8064     jcc(Assembler::zero, FALSE_LABEL);
8065 
8066     // Check the lengths
8067     movl(limit, Address(ary1, length_offset));
8068     cmpl(limit, Address(ary2, length_offset));
8069     jcc(Assembler::notEqual, FALSE_LABEL);
8070   }
8071 
8072   // count == 0
8073   testl(limit, limit);
8074   jcc(Assembler::zero, TRUE_LABEL);
8075 
8076   if (is_array_equ) {
8077     // Load array address
8078     lea(ary1, Address(ary1, base_offset));
8079     lea(ary2, Address(ary2, base_offset));
8080   }
8081 
8082   if (is_array_equ && is_char) {
8083     // arrays_equals when used for char[].
8084     shll(limit, 1);      // byte count != 0
8085   }
8086   movl(result, limit); // copy
8087 
8088   if (UseAVX >= 2) {
8089     // With AVX2, use 32-byte vector compare
8090     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8091 
8092     // Compare 32-byte vectors
8093     andl(result, 0x0000001f);  //   tail count (in bytes)
8094     andl(limit, 0xffffffe0);   // vector count (in bytes)
8095     jccb(Assembler::zero, COMPARE_TAIL);
8096 
8097     lea(ary1, Address(ary1, limit, Address::times_1));
8098     lea(ary2, Address(ary2, limit, Address::times_1));
8099     negptr(limit);
8100 
8101     bind(COMPARE_WIDE_VECTORS);
8102     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8103     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8104     vpxor(vec1, vec2);
8105 
8106     vptest(vec1, vec1);
8107     jccb(Assembler::notZero, FALSE_LABEL);
8108     addptr(limit, 32);
8109     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8110 
8111     testl(result, result);
8112     jccb(Assembler::zero, TRUE_LABEL);
8113 
8114     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8115     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8116     vpxor(vec1, vec2);
8117 
8118     vptest(vec1, vec1);
8119     jccb(Assembler::notZero, FALSE_LABEL);
8120     jmpb(TRUE_LABEL);
8121 
8122     bind(COMPARE_TAIL); // limit is zero
8123     movl(limit, result);
8124     // Fallthru to tail compare
8125   } else if (UseSSE42Intrinsics) {
8126     // With SSE4.2, use double quad vector compare
8127     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8128 
8129     // Compare 16-byte vectors
8130     andl(result, 0x0000000f);  //   tail count (in bytes)
8131     andl(limit, 0xfffffff0);   // vector count (in bytes)
8132     jccb(Assembler::zero, COMPARE_TAIL);
8133 
8134     lea(ary1, Address(ary1, limit, Address::times_1));
8135     lea(ary2, Address(ary2, limit, Address::times_1));
8136     negptr(limit);
8137 
8138     bind(COMPARE_WIDE_VECTORS);
8139     movdqu(vec1, Address(ary1, limit, Address::times_1));
8140     movdqu(vec2, Address(ary2, limit, Address::times_1));
8141     pxor(vec1, vec2);
8142 
8143     ptest(vec1, vec1);
8144     jccb(Assembler::notZero, FALSE_LABEL);
8145     addptr(limit, 16);
8146     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8147 
8148     testl(result, result);
8149     jccb(Assembler::zero, TRUE_LABEL);
8150 
8151     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8152     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8153     pxor(vec1, vec2);
8154 
8155     ptest(vec1, vec1);
8156     jccb(Assembler::notZero, FALSE_LABEL);
8157     jmpb(TRUE_LABEL);
8158 
8159     bind(COMPARE_TAIL); // limit is zero
8160     movl(limit, result);
8161     // Fallthru to tail compare
8162   }
8163 
8164   // Compare 4-byte vectors
8165   andl(limit, 0xfffffffc); // vector count (in bytes)
8166   jccb(Assembler::zero, COMPARE_CHAR);
8167 
8168   lea(ary1, Address(ary1, limit, Address::times_1));
8169   lea(ary2, Address(ary2, limit, Address::times_1));
8170   negptr(limit);
8171 
8172   bind(COMPARE_VECTORS);
8173   movl(chr, Address(ary1, limit, Address::times_1));
8174   cmpl(chr, Address(ary2, limit, Address::times_1));
8175   jccb(Assembler::notEqual, FALSE_LABEL);
8176   addptr(limit, 4);
8177   jcc(Assembler::notZero, COMPARE_VECTORS);
8178 
8179   // Compare trailing char (final 2 bytes), if any
8180   bind(COMPARE_CHAR);
8181   testl(result, 0x2);   // tail  char
8182   jccb(Assembler::zero, COMPARE_BYTE);
8183   load_unsigned_short(chr, Address(ary1, 0));
8184   load_unsigned_short(limit, Address(ary2, 0));
8185   cmpl(chr, limit);
8186   jccb(Assembler::notEqual, FALSE_LABEL);
8187 
8188   if (is_array_equ && is_char) {
8189     bind(COMPARE_BYTE);
8190   } else {
8191     lea(ary1, Address(ary1, 2));
8192     lea(ary2, Address(ary2, 2));
8193 
8194     bind(COMPARE_BYTE);
8195     testl(result, 0x1);   // tail  byte
8196     jccb(Assembler::zero, TRUE_LABEL);
8197     load_unsigned_byte(chr, Address(ary1, 0));
8198     load_unsigned_byte(limit, Address(ary2, 0));
8199     cmpl(chr, limit);
8200     jccb(Assembler::notEqual, FALSE_LABEL);
8201   }
8202   bind(TRUE_LABEL);
8203   movl(result, 1);   // return true
8204   jmpb(DONE);
8205 
8206   bind(FALSE_LABEL);
8207   xorl(result, result); // return false
8208 
8209   // That's it
8210   bind(DONE);
8211   if (UseAVX >= 2) {
8212     // clean upper bits of YMM registers
8213     vpxor(vec1, vec1);
8214     vpxor(vec2, vec2);
8215   }
8216 }
8217 
8218 #endif
8219 
8220 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8221                                    Register to, Register value, Register count,
8222                                    Register rtmp, XMMRegister xtmp) {
8223   ShortBranchVerifier sbv(this);
8224   assert_different_registers(to, value, count, rtmp);
8225   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8226   Label L_fill_2_bytes, L_fill_4_bytes;
8227 
8228   int shift = -1;
8229   switch (t) {
8230     case T_BYTE:
8231       shift = 2;
8232       break;
8233     case T_SHORT:
8234       shift = 1;
8235       break;
8236     case T_INT:
8237       shift = 0;
8238       break;
8239     default: ShouldNotReachHere();
8240   }
8241 
8242   if (t == T_BYTE) {
8243     andl(value, 0xff);
8244     movl(rtmp, value);
8245     shll(rtmp, 8);
8246     orl(value, rtmp);
8247   }
8248   if (t == T_SHORT) {
8249     andl(value, 0xffff);
8250   }
8251   if (t == T_BYTE || t == T_SHORT) {
8252     movl(rtmp, value);
8253     shll(rtmp, 16);
8254     orl(value, rtmp);
8255   }
8256 
8257   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8258   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8259   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8260     // align source address at 4 bytes address boundary
8261     if (t == T_BYTE) {
8262       // One byte misalignment happens only for byte arrays
8263       testptr(to, 1);
8264       jccb(Assembler::zero, L_skip_align1);
8265       movb(Address(to, 0), value);
8266       increment(to);
8267       decrement(count);
8268       BIND(L_skip_align1);
8269     }
8270     // Two bytes misalignment happens only for byte and short (char) arrays
8271     testptr(to, 2);
8272     jccb(Assembler::zero, L_skip_align2);
8273     movw(Address(to, 0), value);
8274     addptr(to, 2);
8275     subl(count, 1<<(shift-1));
8276     BIND(L_skip_align2);
8277   }
8278   if (UseSSE < 2) {
8279     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8280     // Fill 32-byte chunks
8281     subl(count, 8 << shift);
8282     jcc(Assembler::less, L_check_fill_8_bytes);
8283     align(16);
8284 
8285     BIND(L_fill_32_bytes_loop);
8286 
8287     for (int i = 0; i < 32; i += 4) {
8288       movl(Address(to, i), value);
8289     }
8290 
8291     addptr(to, 32);
8292     subl(count, 8 << shift);
8293     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8294     BIND(L_check_fill_8_bytes);
8295     addl(count, 8 << shift);
8296     jccb(Assembler::zero, L_exit);
8297     jmpb(L_fill_8_bytes);
8298 
8299     //
8300     // length is too short, just fill qwords
8301     //
8302     BIND(L_fill_8_bytes_loop);
8303     movl(Address(to, 0), value);
8304     movl(Address(to, 4), value);
8305     addptr(to, 8);
8306     BIND(L_fill_8_bytes);
8307     subl(count, 1 << (shift + 1));
8308     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8309     // fall through to fill 4 bytes
8310   } else {
8311     Label L_fill_32_bytes;
8312     if (!UseUnalignedLoadStores) {
8313       // align to 8 bytes, we know we are 4 byte aligned to start
8314       testptr(to, 4);
8315       jccb(Assembler::zero, L_fill_32_bytes);
8316       movl(Address(to, 0), value);
8317       addptr(to, 4);
8318       subl(count, 1<<shift);
8319     }
8320     BIND(L_fill_32_bytes);
8321     {
8322       assert( UseSSE >= 2, "supported cpu only" );
8323       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8324       if (UseAVX > 2) {
8325         movl(rtmp, 0xffff);
8326         kmovwl(k1, rtmp);
8327       }
8328       movdl(xtmp, value);
8329       if (UseAVX > 2 && UseUnalignedLoadStores) {
8330         // Fill 64-byte chunks
8331         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8332         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8333 
8334         subl(count, 16 << shift);
8335         jcc(Assembler::less, L_check_fill_32_bytes);
8336         align(16);
8337 
8338         BIND(L_fill_64_bytes_loop);
8339         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8340         addptr(to, 64);
8341         subl(count, 16 << shift);
8342         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8343 
8344         BIND(L_check_fill_32_bytes);
8345         addl(count, 8 << shift);
8346         jccb(Assembler::less, L_check_fill_8_bytes);
8347         vmovdqu(Address(to, 0), xtmp);
8348         addptr(to, 32);
8349         subl(count, 8 << shift);
8350 
8351         BIND(L_check_fill_8_bytes);
8352       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8353         // Fill 64-byte chunks
8354         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8355         vpbroadcastd(xtmp, xtmp);
8356 
8357         subl(count, 16 << shift);
8358         jcc(Assembler::less, L_check_fill_32_bytes);
8359         align(16);
8360 
8361         BIND(L_fill_64_bytes_loop);
8362         vmovdqu(Address(to, 0), xtmp);
8363         vmovdqu(Address(to, 32), xtmp);
8364         addptr(to, 64);
8365         subl(count, 16 << shift);
8366         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8367 
8368         BIND(L_check_fill_32_bytes);
8369         addl(count, 8 << shift);
8370         jccb(Assembler::less, L_check_fill_8_bytes);
8371         vmovdqu(Address(to, 0), xtmp);
8372         addptr(to, 32);
8373         subl(count, 8 << shift);
8374 
8375         BIND(L_check_fill_8_bytes);
8376         // clean upper bits of YMM registers
8377         movdl(xtmp, value);
8378         pshufd(xtmp, xtmp, 0);
8379       } else {
8380         // Fill 32-byte chunks
8381         pshufd(xtmp, xtmp, 0);
8382 
8383         subl(count, 8 << shift);
8384         jcc(Assembler::less, L_check_fill_8_bytes);
8385         align(16);
8386 
8387         BIND(L_fill_32_bytes_loop);
8388 
8389         if (UseUnalignedLoadStores) {
8390           movdqu(Address(to, 0), xtmp);
8391           movdqu(Address(to, 16), xtmp);
8392         } else {
8393           movq(Address(to, 0), xtmp);
8394           movq(Address(to, 8), xtmp);
8395           movq(Address(to, 16), xtmp);
8396           movq(Address(to, 24), xtmp);
8397         }
8398 
8399         addptr(to, 32);
8400         subl(count, 8 << shift);
8401         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8402 
8403         BIND(L_check_fill_8_bytes);
8404       }
8405       addl(count, 8 << shift);
8406       jccb(Assembler::zero, L_exit);
8407       jmpb(L_fill_8_bytes);
8408 
8409       //
8410       // length is too short, just fill qwords
8411       //
8412       BIND(L_fill_8_bytes_loop);
8413       movq(Address(to, 0), xtmp);
8414       addptr(to, 8);
8415       BIND(L_fill_8_bytes);
8416       subl(count, 1 << (shift + 1));
8417       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8418     }
8419   }
8420   // fill trailing 4 bytes
8421   BIND(L_fill_4_bytes);
8422   testl(count, 1<<shift);
8423   jccb(Assembler::zero, L_fill_2_bytes);
8424   movl(Address(to, 0), value);
8425   if (t == T_BYTE || t == T_SHORT) {
8426     addptr(to, 4);
8427     BIND(L_fill_2_bytes);
8428     // fill trailing 2 bytes
8429     testl(count, 1<<(shift-1));
8430     jccb(Assembler::zero, L_fill_byte);
8431     movw(Address(to, 0), value);
8432     if (t == T_BYTE) {
8433       addptr(to, 2);
8434       BIND(L_fill_byte);
8435       // fill trailing byte
8436       testl(count, 1);
8437       jccb(Assembler::zero, L_exit);
8438       movb(Address(to, 0), value);
8439     } else {
8440       BIND(L_fill_byte);
8441     }
8442   } else {
8443     BIND(L_fill_2_bytes);
8444   }
8445   BIND(L_exit);
8446 }
8447 
8448 // encode char[] to byte[] in ISO_8859_1
8449 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8450                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8451                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8452                                       Register tmp5, Register result) {
8453   // rsi: src
8454   // rdi: dst
8455   // rdx: len
8456   // rcx: tmp5
8457   // rax: result
8458   ShortBranchVerifier sbv(this);
8459   assert_different_registers(src, dst, len, tmp5, result);
8460   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8461 
8462   // set result
8463   xorl(result, result);
8464   // check for zero length
8465   testl(len, len);
8466   jcc(Assembler::zero, L_done);
8467   movl(result, len);
8468 
8469   // Setup pointers
8470   lea(src, Address(src, len, Address::times_2)); // char[]
8471   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8472   negptr(len);
8473 
8474   if (UseSSE42Intrinsics || UseAVX >= 2) {
8475     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8476     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8477 
8478     if (UseAVX >= 2) {
8479       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8480       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8481       movdl(tmp1Reg, tmp5);
8482       vpbroadcastd(tmp1Reg, tmp1Reg);
8483       jmpb(L_chars_32_check);
8484 
8485       bind(L_copy_32_chars);
8486       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8487       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8488       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8489       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8490       jccb(Assembler::notZero, L_copy_32_chars_exit);
8491       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8492       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8493       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8494 
8495       bind(L_chars_32_check);
8496       addptr(len, 32);
8497       jccb(Assembler::lessEqual, L_copy_32_chars);
8498 
8499       bind(L_copy_32_chars_exit);
8500       subptr(len, 16);
8501       jccb(Assembler::greater, L_copy_16_chars_exit);
8502 
8503     } else if (UseSSE42Intrinsics) {
8504       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8505       movdl(tmp1Reg, tmp5);
8506       pshufd(tmp1Reg, tmp1Reg, 0);
8507       jmpb(L_chars_16_check);
8508     }
8509 
8510     bind(L_copy_16_chars);
8511     if (UseAVX >= 2) {
8512       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8513       vptest(tmp2Reg, tmp1Reg);
8514       jccb(Assembler::notZero, L_copy_16_chars_exit);
8515       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8516       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8517     } else {
8518       if (UseAVX > 0) {
8519         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8520         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8521         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8522       } else {
8523         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8524         por(tmp2Reg, tmp3Reg);
8525         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8526         por(tmp2Reg, tmp4Reg);
8527       }
8528       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8529       jccb(Assembler::notZero, L_copy_16_chars_exit);
8530       packuswb(tmp3Reg, tmp4Reg);
8531     }
8532     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8533 
8534     bind(L_chars_16_check);
8535     addptr(len, 16);
8536     jccb(Assembler::lessEqual, L_copy_16_chars);
8537 
8538     bind(L_copy_16_chars_exit);
8539     if (UseAVX >= 2) {
8540       // clean upper bits of YMM registers
8541       vpxor(tmp2Reg, tmp2Reg);
8542       vpxor(tmp3Reg, tmp3Reg);
8543       vpxor(tmp4Reg, tmp4Reg);
8544       movdl(tmp1Reg, tmp5);
8545       pshufd(tmp1Reg, tmp1Reg, 0);
8546     }
8547     subptr(len, 8);
8548     jccb(Assembler::greater, L_copy_8_chars_exit);
8549 
8550     bind(L_copy_8_chars);
8551     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8552     ptest(tmp3Reg, tmp1Reg);
8553     jccb(Assembler::notZero, L_copy_8_chars_exit);
8554     packuswb(tmp3Reg, tmp1Reg);
8555     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8556     addptr(len, 8);
8557     jccb(Assembler::lessEqual, L_copy_8_chars);
8558 
8559     bind(L_copy_8_chars_exit);
8560     subptr(len, 8);
8561     jccb(Assembler::zero, L_done);
8562   }
8563 
8564   bind(L_copy_1_char);
8565   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8566   testl(tmp5, 0xff00);      // check if Unicode char
8567   jccb(Assembler::notZero, L_copy_1_char_exit);
8568   movb(Address(dst, len, Address::times_1, 0), tmp5);
8569   addptr(len, 1);
8570   jccb(Assembler::less, L_copy_1_char);
8571 
8572   bind(L_copy_1_char_exit);
8573   addptr(result, len); // len is negative count of not processed elements
8574   bind(L_done);
8575 }
8576 
8577 #ifdef _LP64
8578 /**
8579  * Helper for multiply_to_len().
8580  */
8581 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8582   addq(dest_lo, src1);
8583   adcq(dest_hi, 0);
8584   addq(dest_lo, src2);
8585   adcq(dest_hi, 0);
8586 }
8587 
8588 /**
8589  * Multiply 64 bit by 64 bit first loop.
8590  */
8591 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8592                                            Register y, Register y_idx, Register z,
8593                                            Register carry, Register product,
8594                                            Register idx, Register kdx) {
8595   //
8596   //  jlong carry, x[], y[], z[];
8597   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8598   //    huge_128 product = y[idx] * x[xstart] + carry;
8599   //    z[kdx] = (jlong)product;
8600   //    carry  = (jlong)(product >>> 64);
8601   //  }
8602   //  z[xstart] = carry;
8603   //
8604 
8605   Label L_first_loop, L_first_loop_exit;
8606   Label L_one_x, L_one_y, L_multiply;
8607 
8608   decrementl(xstart);
8609   jcc(Assembler::negative, L_one_x);
8610 
8611   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8612   rorq(x_xstart, 32); // convert big-endian to little-endian
8613 
8614   bind(L_first_loop);
8615   decrementl(idx);
8616   jcc(Assembler::negative, L_first_loop_exit);
8617   decrementl(idx);
8618   jcc(Assembler::negative, L_one_y);
8619   movq(y_idx, Address(y, idx, Address::times_4,  0));
8620   rorq(y_idx, 32); // convert big-endian to little-endian
8621   bind(L_multiply);
8622   movq(product, x_xstart);
8623   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8624   addq(product, carry);
8625   adcq(rdx, 0);
8626   subl(kdx, 2);
8627   movl(Address(z, kdx, Address::times_4,  4), product);
8628   shrq(product, 32);
8629   movl(Address(z, kdx, Address::times_4,  0), product);
8630   movq(carry, rdx);
8631   jmp(L_first_loop);
8632 
8633   bind(L_one_y);
8634   movl(y_idx, Address(y,  0));
8635   jmp(L_multiply);
8636 
8637   bind(L_one_x);
8638   movl(x_xstart, Address(x,  0));
8639   jmp(L_first_loop);
8640 
8641   bind(L_first_loop_exit);
8642 }
8643 
8644 /**
8645  * Multiply 64 bit by 64 bit and add 128 bit.
8646  */
8647 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8648                                             Register yz_idx, Register idx,
8649                                             Register carry, Register product, int offset) {
8650   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8651   //     z[kdx] = (jlong)product;
8652 
8653   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8654   rorq(yz_idx, 32); // convert big-endian to little-endian
8655   movq(product, x_xstart);
8656   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8657   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8658   rorq(yz_idx, 32); // convert big-endian to little-endian
8659 
8660   add2_with_carry(rdx, product, carry, yz_idx);
8661 
8662   movl(Address(z, idx, Address::times_4,  offset+4), product);
8663   shrq(product, 32);
8664   movl(Address(z, idx, Address::times_4,  offset), product);
8665 
8666 }
8667 
8668 /**
8669  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8670  */
8671 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8672                                              Register yz_idx, Register idx, Register jdx,
8673                                              Register carry, Register product,
8674                                              Register carry2) {
8675   //   jlong carry, x[], y[], z[];
8676   //   int kdx = ystart+1;
8677   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8678   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8679   //     z[kdx+idx+1] = (jlong)product;
8680   //     jlong carry2  = (jlong)(product >>> 64);
8681   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8682   //     z[kdx+idx] = (jlong)product;
8683   //     carry  = (jlong)(product >>> 64);
8684   //   }
8685   //   idx += 2;
8686   //   if (idx > 0) {
8687   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8688   //     z[kdx+idx] = (jlong)product;
8689   //     carry  = (jlong)(product >>> 64);
8690   //   }
8691   //
8692 
8693   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8694 
8695   movl(jdx, idx);
8696   andl(jdx, 0xFFFFFFFC);
8697   shrl(jdx, 2);
8698 
8699   bind(L_third_loop);
8700   subl(jdx, 1);
8701   jcc(Assembler::negative, L_third_loop_exit);
8702   subl(idx, 4);
8703 
8704   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8705   movq(carry2, rdx);
8706 
8707   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8708   movq(carry, rdx);
8709   jmp(L_third_loop);
8710 
8711   bind (L_third_loop_exit);
8712 
8713   andl (idx, 0x3);
8714   jcc(Assembler::zero, L_post_third_loop_done);
8715 
8716   Label L_check_1;
8717   subl(idx, 2);
8718   jcc(Assembler::negative, L_check_1);
8719 
8720   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8721   movq(carry, rdx);
8722 
8723   bind (L_check_1);
8724   addl (idx, 0x2);
8725   andl (idx, 0x1);
8726   subl(idx, 1);
8727   jcc(Assembler::negative, L_post_third_loop_done);
8728 
8729   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8730   movq(product, x_xstart);
8731   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8732   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8733 
8734   add2_with_carry(rdx, product, yz_idx, carry);
8735 
8736   movl(Address(z, idx, Address::times_4,  0), product);
8737   shrq(product, 32);
8738 
8739   shlq(rdx, 32);
8740   orq(product, rdx);
8741   movq(carry, product);
8742 
8743   bind(L_post_third_loop_done);
8744 }
8745 
8746 /**
8747  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8748  *
8749  */
8750 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8751                                                   Register carry, Register carry2,
8752                                                   Register idx, Register jdx,
8753                                                   Register yz_idx1, Register yz_idx2,
8754                                                   Register tmp, Register tmp3, Register tmp4) {
8755   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8756 
8757   //   jlong carry, x[], y[], z[];
8758   //   int kdx = ystart+1;
8759   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8760   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8761   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8762   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8763   //     carry  = (jlong)(tmp4 >>> 64);
8764   //     z[kdx+idx+1] = (jlong)tmp3;
8765   //     z[kdx+idx] = (jlong)tmp4;
8766   //   }
8767   //   idx += 2;
8768   //   if (idx > 0) {
8769   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8770   //     z[kdx+idx] = (jlong)yz_idx1;
8771   //     carry  = (jlong)(yz_idx1 >>> 64);
8772   //   }
8773   //
8774 
8775   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8776 
8777   movl(jdx, idx);
8778   andl(jdx, 0xFFFFFFFC);
8779   shrl(jdx, 2);
8780 
8781   bind(L_third_loop);
8782   subl(jdx, 1);
8783   jcc(Assembler::negative, L_third_loop_exit);
8784   subl(idx, 4);
8785 
8786   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8787   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8788   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8789   rorxq(yz_idx2, yz_idx2, 32);
8790 
8791   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8792   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8793 
8794   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8795   rorxq(yz_idx1, yz_idx1, 32);
8796   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8797   rorxq(yz_idx2, yz_idx2, 32);
8798 
8799   if (VM_Version::supports_adx()) {
8800     adcxq(tmp3, carry);
8801     adoxq(tmp3, yz_idx1);
8802 
8803     adcxq(tmp4, tmp);
8804     adoxq(tmp4, yz_idx2);
8805 
8806     movl(carry, 0); // does not affect flags
8807     adcxq(carry2, carry);
8808     adoxq(carry2, carry);
8809   } else {
8810     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8811     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8812   }
8813   movq(carry, carry2);
8814 
8815   movl(Address(z, idx, Address::times_4, 12), tmp3);
8816   shrq(tmp3, 32);
8817   movl(Address(z, idx, Address::times_4,  8), tmp3);
8818 
8819   movl(Address(z, idx, Address::times_4,  4), tmp4);
8820   shrq(tmp4, 32);
8821   movl(Address(z, idx, Address::times_4,  0), tmp4);
8822 
8823   jmp(L_third_loop);
8824 
8825   bind (L_third_loop_exit);
8826 
8827   andl (idx, 0x3);
8828   jcc(Assembler::zero, L_post_third_loop_done);
8829 
8830   Label L_check_1;
8831   subl(idx, 2);
8832   jcc(Assembler::negative, L_check_1);
8833 
8834   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8835   rorxq(yz_idx1, yz_idx1, 32);
8836   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8837   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8838   rorxq(yz_idx2, yz_idx2, 32);
8839 
8840   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8841 
8842   movl(Address(z, idx, Address::times_4,  4), tmp3);
8843   shrq(tmp3, 32);
8844   movl(Address(z, idx, Address::times_4,  0), tmp3);
8845   movq(carry, tmp4);
8846 
8847   bind (L_check_1);
8848   addl (idx, 0x2);
8849   andl (idx, 0x1);
8850   subl(idx, 1);
8851   jcc(Assembler::negative, L_post_third_loop_done);
8852   movl(tmp4, Address(y, idx, Address::times_4,  0));
8853   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8854   movl(tmp4, Address(z, idx, Address::times_4,  0));
8855 
8856   add2_with_carry(carry2, tmp3, tmp4, carry);
8857 
8858   movl(Address(z, idx, Address::times_4,  0), tmp3);
8859   shrq(tmp3, 32);
8860 
8861   shlq(carry2, 32);
8862   orq(tmp3, carry2);
8863   movq(carry, tmp3);
8864 
8865   bind(L_post_third_loop_done);
8866 }
8867 
8868 /**
8869  * Code for BigInteger::multiplyToLen() instrinsic.
8870  *
8871  * rdi: x
8872  * rax: xlen
8873  * rsi: y
8874  * rcx: ylen
8875  * r8:  z
8876  * r11: zlen
8877  * r12: tmp1
8878  * r13: tmp2
8879  * r14: tmp3
8880  * r15: tmp4
8881  * rbx: tmp5
8882  *
8883  */
8884 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8885                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8886   ShortBranchVerifier sbv(this);
8887   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8888 
8889   push(tmp1);
8890   push(tmp2);
8891   push(tmp3);
8892   push(tmp4);
8893   push(tmp5);
8894 
8895   push(xlen);
8896   push(zlen);
8897 
8898   const Register idx = tmp1;
8899   const Register kdx = tmp2;
8900   const Register xstart = tmp3;
8901 
8902   const Register y_idx = tmp4;
8903   const Register carry = tmp5;
8904   const Register product  = xlen;
8905   const Register x_xstart = zlen;  // reuse register
8906 
8907   // First Loop.
8908   //
8909   //  final static long LONG_MASK = 0xffffffffL;
8910   //  int xstart = xlen - 1;
8911   //  int ystart = ylen - 1;
8912   //  long carry = 0;
8913   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8914   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8915   //    z[kdx] = (int)product;
8916   //    carry = product >>> 32;
8917   //  }
8918   //  z[xstart] = (int)carry;
8919   //
8920 
8921   movl(idx, ylen);      // idx = ylen;
8922   movl(kdx, zlen);      // kdx = xlen+ylen;
8923   xorq(carry, carry);   // carry = 0;
8924 
8925   Label L_done;
8926 
8927   movl(xstart, xlen);
8928   decrementl(xstart);
8929   jcc(Assembler::negative, L_done);
8930 
8931   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8932 
8933   Label L_second_loop;
8934   testl(kdx, kdx);
8935   jcc(Assembler::zero, L_second_loop);
8936 
8937   Label L_carry;
8938   subl(kdx, 1);
8939   jcc(Assembler::zero, L_carry);
8940 
8941   movl(Address(z, kdx, Address::times_4,  0), carry);
8942   shrq(carry, 32);
8943   subl(kdx, 1);
8944 
8945   bind(L_carry);
8946   movl(Address(z, kdx, Address::times_4,  0), carry);
8947 
8948   // Second and third (nested) loops.
8949   //
8950   // for (int i = xstart-1; i >= 0; i--) { // Second loop
8951   //   carry = 0;
8952   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
8953   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
8954   //                    (z[k] & LONG_MASK) + carry;
8955   //     z[k] = (int)product;
8956   //     carry = product >>> 32;
8957   //   }
8958   //   z[i] = (int)carry;
8959   // }
8960   //
8961   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
8962 
8963   const Register jdx = tmp1;
8964 
8965   bind(L_second_loop);
8966   xorl(carry, carry);    // carry = 0;
8967   movl(jdx, ylen);       // j = ystart+1
8968 
8969   subl(xstart, 1);       // i = xstart-1;
8970   jcc(Assembler::negative, L_done);
8971 
8972   push (z);
8973 
8974   Label L_last_x;
8975   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
8976   subl(xstart, 1);       // i = xstart-1;
8977   jcc(Assembler::negative, L_last_x);
8978 
8979   if (UseBMI2Instructions) {
8980     movq(rdx,  Address(x, xstart, Address::times_4,  0));
8981     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
8982   } else {
8983     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8984     rorq(x_xstart, 32);  // convert big-endian to little-endian
8985   }
8986 
8987   Label L_third_loop_prologue;
8988   bind(L_third_loop_prologue);
8989 
8990   push (x);
8991   push (xstart);
8992   push (ylen);
8993 
8994 
8995   if (UseBMI2Instructions) {
8996     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
8997   } else { // !UseBMI2Instructions
8998     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
8999   }
9000 
9001   pop(ylen);
9002   pop(xlen);
9003   pop(x);
9004   pop(z);
9005 
9006   movl(tmp3, xlen);
9007   addl(tmp3, 1);
9008   movl(Address(z, tmp3, Address::times_4,  0), carry);
9009   subl(tmp3, 1);
9010   jccb(Assembler::negative, L_done);
9011 
9012   shrq(carry, 32);
9013   movl(Address(z, tmp3, Address::times_4,  0), carry);
9014   jmp(L_second_loop);
9015 
9016   // Next infrequent code is moved outside loops.
9017   bind(L_last_x);
9018   if (UseBMI2Instructions) {
9019     movl(rdx, Address(x,  0));
9020   } else {
9021     movl(x_xstart, Address(x,  0));
9022   }
9023   jmp(L_third_loop_prologue);
9024 
9025   bind(L_done);
9026 
9027   pop(zlen);
9028   pop(xlen);
9029 
9030   pop(tmp5);
9031   pop(tmp4);
9032   pop(tmp3);
9033   pop(tmp2);
9034   pop(tmp1);
9035 }
9036 
9037 //Helper functions for square_to_len()
9038 
9039 /**
9040  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9041  * Preserves x and z and modifies rest of the registers.
9042  */
9043 
9044 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9045   // Perform square and right shift by 1
9046   // Handle odd xlen case first, then for even xlen do the following
9047   // jlong carry = 0;
9048   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9049   //     huge_128 product = x[j:j+1] * x[j:j+1];
9050   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9051   //     z[i+2:i+3] = (jlong)(product >>> 1);
9052   //     carry = (jlong)product;
9053   // }
9054 
9055   xorq(tmp5, tmp5);     // carry
9056   xorq(rdxReg, rdxReg);
9057   xorl(tmp1, tmp1);     // index for x
9058   xorl(tmp4, tmp4);     // index for z
9059 
9060   Label L_first_loop, L_first_loop_exit;
9061 
9062   testl(xlen, 1);
9063   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9064 
9065   // Square and right shift by 1 the odd element using 32 bit multiply
9066   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9067   imulq(raxReg, raxReg);
9068   shrq(raxReg, 1);
9069   adcq(tmp5, 0);
9070   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9071   incrementl(tmp1);
9072   addl(tmp4, 2);
9073 
9074   // Square and  right shift by 1 the rest using 64 bit multiply
9075   bind(L_first_loop);
9076   cmpptr(tmp1, xlen);
9077   jccb(Assembler::equal, L_first_loop_exit);
9078 
9079   // Square
9080   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9081   rorq(raxReg, 32);    // convert big-endian to little-endian
9082   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9083 
9084   // Right shift by 1 and save carry
9085   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9086   rcrq(rdxReg, 1);
9087   rcrq(raxReg, 1);
9088   adcq(tmp5, 0);
9089 
9090   // Store result in z
9091   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9092   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9093 
9094   // Update indices for x and z
9095   addl(tmp1, 2);
9096   addl(tmp4, 4);
9097   jmp(L_first_loop);
9098 
9099   bind(L_first_loop_exit);
9100 }
9101 
9102 
9103 /**
9104  * Perform the following multiply add operation using BMI2 instructions
9105  * carry:sum = sum + op1*op2 + carry
9106  * op2 should be in rdx
9107  * op2 is preserved, all other registers are modified
9108  */
9109 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9110   // assert op2 is rdx
9111   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9112   addq(sum, carry);
9113   adcq(tmp2, 0);
9114   addq(sum, op1);
9115   adcq(tmp2, 0);
9116   movq(carry, tmp2);
9117 }
9118 
9119 /**
9120  * Perform the following multiply add operation:
9121  * carry:sum = sum + op1*op2 + carry
9122  * Preserves op1, op2 and modifies rest of registers
9123  */
9124 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9125   // rdx:rax = op1 * op2
9126   movq(raxReg, op2);
9127   mulq(op1);
9128 
9129   //  rdx:rax = sum + carry + rdx:rax
9130   addq(sum, carry);
9131   adcq(rdxReg, 0);
9132   addq(sum, raxReg);
9133   adcq(rdxReg, 0);
9134 
9135   // carry:sum = rdx:sum
9136   movq(carry, rdxReg);
9137 }
9138 
9139 /**
9140  * Add 64 bit long carry into z[] with carry propogation.
9141  * Preserves z and carry register values and modifies rest of registers.
9142  *
9143  */
9144 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9145   Label L_fourth_loop, L_fourth_loop_exit;
9146 
9147   movl(tmp1, 1);
9148   subl(zlen, 2);
9149   addq(Address(z, zlen, Address::times_4, 0), carry);
9150 
9151   bind(L_fourth_loop);
9152   jccb(Assembler::carryClear, L_fourth_loop_exit);
9153   subl(zlen, 2);
9154   jccb(Assembler::negative, L_fourth_loop_exit);
9155   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9156   jmp(L_fourth_loop);
9157   bind(L_fourth_loop_exit);
9158 }
9159 
9160 /**
9161  * Shift z[] left by 1 bit.
9162  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9163  *
9164  */
9165 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9166 
9167   Label L_fifth_loop, L_fifth_loop_exit;
9168 
9169   // Fifth loop
9170   // Perform primitiveLeftShift(z, zlen, 1)
9171 
9172   const Register prev_carry = tmp1;
9173   const Register new_carry = tmp4;
9174   const Register value = tmp2;
9175   const Register zidx = tmp3;
9176 
9177   // int zidx, carry;
9178   // long value;
9179   // carry = 0;
9180   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9181   //    (carry:value)  = (z[i] << 1) | carry ;
9182   //    z[i] = value;
9183   // }
9184 
9185   movl(zidx, zlen);
9186   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9187 
9188   bind(L_fifth_loop);
9189   decl(zidx);  // Use decl to preserve carry flag
9190   decl(zidx);
9191   jccb(Assembler::negative, L_fifth_loop_exit);
9192 
9193   if (UseBMI2Instructions) {
9194      movq(value, Address(z, zidx, Address::times_4, 0));
9195      rclq(value, 1);
9196      rorxq(value, value, 32);
9197      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9198   }
9199   else {
9200     // clear new_carry
9201     xorl(new_carry, new_carry);
9202 
9203     // Shift z[i] by 1, or in previous carry and save new carry
9204     movq(value, Address(z, zidx, Address::times_4, 0));
9205     shlq(value, 1);
9206     adcl(new_carry, 0);
9207 
9208     orq(value, prev_carry);
9209     rorq(value, 0x20);
9210     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9211 
9212     // Set previous carry = new carry
9213     movl(prev_carry, new_carry);
9214   }
9215   jmp(L_fifth_loop);
9216 
9217   bind(L_fifth_loop_exit);
9218 }
9219 
9220 
9221 /**
9222  * Code for BigInteger::squareToLen() intrinsic
9223  *
9224  * rdi: x
9225  * rsi: len
9226  * r8:  z
9227  * rcx: zlen
9228  * r12: tmp1
9229  * r13: tmp2
9230  * r14: tmp3
9231  * r15: tmp4
9232  * rbx: tmp5
9233  *
9234  */
9235 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) {
9236 
9237   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;
9238   push(tmp1);
9239   push(tmp2);
9240   push(tmp3);
9241   push(tmp4);
9242   push(tmp5);
9243 
9244   // First loop
9245   // Store the squares, right shifted one bit (i.e., divided by 2).
9246   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9247 
9248   // Add in off-diagonal sums.
9249   //
9250   // Second, third (nested) and fourth loops.
9251   // zlen +=2;
9252   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9253   //    carry = 0;
9254   //    long op2 = x[xidx:xidx+1];
9255   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9256   //       k -= 2;
9257   //       long op1 = x[j:j+1];
9258   //       long sum = z[k:k+1];
9259   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9260   //       z[k:k+1] = sum;
9261   //    }
9262   //    add_one_64(z, k, carry, tmp_regs);
9263   // }
9264 
9265   const Register carry = tmp5;
9266   const Register sum = tmp3;
9267   const Register op1 = tmp4;
9268   Register op2 = tmp2;
9269 
9270   push(zlen);
9271   push(len);
9272   addl(zlen,2);
9273   bind(L_second_loop);
9274   xorq(carry, carry);
9275   subl(zlen, 4);
9276   subl(len, 2);
9277   push(zlen);
9278   push(len);
9279   cmpl(len, 0);
9280   jccb(Assembler::lessEqual, L_second_loop_exit);
9281 
9282   // Multiply an array by one 64 bit long.
9283   if (UseBMI2Instructions) {
9284     op2 = rdxReg;
9285     movq(op2, Address(x, len, Address::times_4,  0));
9286     rorxq(op2, op2, 32);
9287   }
9288   else {
9289     movq(op2, Address(x, len, Address::times_4,  0));
9290     rorq(op2, 32);
9291   }
9292 
9293   bind(L_third_loop);
9294   decrementl(len);
9295   jccb(Assembler::negative, L_third_loop_exit);
9296   decrementl(len);
9297   jccb(Assembler::negative, L_last_x);
9298 
9299   movq(op1, Address(x, len, Address::times_4,  0));
9300   rorq(op1, 32);
9301 
9302   bind(L_multiply);
9303   subl(zlen, 2);
9304   movq(sum, Address(z, zlen, Address::times_4,  0));
9305 
9306   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9307   if (UseBMI2Instructions) {
9308     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9309   }
9310   else {
9311     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9312   }
9313 
9314   movq(Address(z, zlen, Address::times_4, 0), sum);
9315 
9316   jmp(L_third_loop);
9317   bind(L_third_loop_exit);
9318 
9319   // Fourth loop
9320   // Add 64 bit long carry into z with carry propogation.
9321   // Uses offsetted zlen.
9322   add_one_64(z, zlen, carry, tmp1);
9323 
9324   pop(len);
9325   pop(zlen);
9326   jmp(L_second_loop);
9327 
9328   // Next infrequent code is moved outside loops.
9329   bind(L_last_x);
9330   movl(op1, Address(x, 0));
9331   jmp(L_multiply);
9332 
9333   bind(L_second_loop_exit);
9334   pop(len);
9335   pop(zlen);
9336   pop(len);
9337   pop(zlen);
9338 
9339   // Fifth loop
9340   // Shift z left 1 bit.
9341   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9342 
9343   // z[zlen-1] |= x[len-1] & 1;
9344   movl(tmp3, Address(x, len, Address::times_4, -4));
9345   andl(tmp3, 1);
9346   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9347 
9348   pop(tmp5);
9349   pop(tmp4);
9350   pop(tmp3);
9351   pop(tmp2);
9352   pop(tmp1);
9353 }
9354 
9355 /**
9356  * Helper function for mul_add()
9357  * Multiply the in[] by int k and add to out[] starting at offset offs using
9358  * 128 bit by 32 bit multiply and return the carry in tmp5.
9359  * Only quad int aligned length of in[] is operated on in this function.
9360  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9361  * This function preserves out, in and k registers.
9362  * len and offset point to the appropriate index in "in" & "out" correspondingly
9363  * tmp5 has the carry.
9364  * other registers are temporary and are modified.
9365  *
9366  */
9367 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9368   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9369   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9370 
9371   Label L_first_loop, L_first_loop_exit;
9372 
9373   movl(tmp1, len);
9374   shrl(tmp1, 2);
9375 
9376   bind(L_first_loop);
9377   subl(tmp1, 1);
9378   jccb(Assembler::negative, L_first_loop_exit);
9379 
9380   subl(len, 4);
9381   subl(offset, 4);
9382 
9383   Register op2 = tmp2;
9384   const Register sum = tmp3;
9385   const Register op1 = tmp4;
9386   const Register carry = tmp5;
9387 
9388   if (UseBMI2Instructions) {
9389     op2 = rdxReg;
9390   }
9391 
9392   movq(op1, Address(in, len, Address::times_4,  8));
9393   rorq(op1, 32);
9394   movq(sum, Address(out, offset, Address::times_4,  8));
9395   rorq(sum, 32);
9396   if (UseBMI2Instructions) {
9397     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9398   }
9399   else {
9400     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9401   }
9402   // Store back in big endian from little endian
9403   rorq(sum, 0x20);
9404   movq(Address(out, offset, Address::times_4,  8), sum);
9405 
9406   movq(op1, Address(in, len, Address::times_4,  0));
9407   rorq(op1, 32);
9408   movq(sum, Address(out, offset, Address::times_4,  0));
9409   rorq(sum, 32);
9410   if (UseBMI2Instructions) {
9411     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9412   }
9413   else {
9414     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9415   }
9416   // Store back in big endian from little endian
9417   rorq(sum, 0x20);
9418   movq(Address(out, offset, Address::times_4,  0), sum);
9419 
9420   jmp(L_first_loop);
9421   bind(L_first_loop_exit);
9422 }
9423 
9424 /**
9425  * Code for BigInteger::mulAdd() intrinsic
9426  *
9427  * rdi: out
9428  * rsi: in
9429  * r11: offs (out.length - offset)
9430  * rcx: len
9431  * r8:  k
9432  * r12: tmp1
9433  * r13: tmp2
9434  * r14: tmp3
9435  * r15: tmp4
9436  * rbx: tmp5
9437  * Multiply the in[] by word k and add to out[], return the carry in rax
9438  */
9439 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9440    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9441    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9442 
9443   Label L_carry, L_last_in, L_done;
9444 
9445 // carry = 0;
9446 // for (int j=len-1; j >= 0; j--) {
9447 //    long product = (in[j] & LONG_MASK) * kLong +
9448 //                   (out[offs] & LONG_MASK) + carry;
9449 //    out[offs--] = (int)product;
9450 //    carry = product >>> 32;
9451 // }
9452 //
9453   push(tmp1);
9454   push(tmp2);
9455   push(tmp3);
9456   push(tmp4);
9457   push(tmp5);
9458 
9459   Register op2 = tmp2;
9460   const Register sum = tmp3;
9461   const Register op1 = tmp4;
9462   const Register carry =  tmp5;
9463 
9464   if (UseBMI2Instructions) {
9465     op2 = rdxReg;
9466     movl(op2, k);
9467   }
9468   else {
9469     movl(op2, k);
9470   }
9471 
9472   xorq(carry, carry);
9473 
9474   //First loop
9475 
9476   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9477   //The carry is in tmp5
9478   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9479 
9480   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9481   decrementl(len);
9482   jccb(Assembler::negative, L_carry);
9483   decrementl(len);
9484   jccb(Assembler::negative, L_last_in);
9485 
9486   movq(op1, Address(in, len, Address::times_4,  0));
9487   rorq(op1, 32);
9488 
9489   subl(offs, 2);
9490   movq(sum, Address(out, offs, Address::times_4,  0));
9491   rorq(sum, 32);
9492 
9493   if (UseBMI2Instructions) {
9494     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9495   }
9496   else {
9497     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9498   }
9499 
9500   // Store back in big endian from little endian
9501   rorq(sum, 0x20);
9502   movq(Address(out, offs, Address::times_4,  0), sum);
9503 
9504   testl(len, len);
9505   jccb(Assembler::zero, L_carry);
9506 
9507   //Multiply the last in[] entry, if any
9508   bind(L_last_in);
9509   movl(op1, Address(in, 0));
9510   movl(sum, Address(out, offs, Address::times_4,  -4));
9511 
9512   movl(raxReg, k);
9513   mull(op1); //tmp4 * eax -> edx:eax
9514   addl(sum, carry);
9515   adcl(rdxReg, 0);
9516   addl(sum, raxReg);
9517   adcl(rdxReg, 0);
9518   movl(carry, rdxReg);
9519 
9520   movl(Address(out, offs, Address::times_4,  -4), sum);
9521 
9522   bind(L_carry);
9523   //return tmp5/carry as carry in rax
9524   movl(rax, carry);
9525 
9526   bind(L_done);
9527   pop(tmp5);
9528   pop(tmp4);
9529   pop(tmp3);
9530   pop(tmp2);
9531   pop(tmp1);
9532 }
9533 #endif
9534 
9535 /**
9536  * Emits code to update CRC-32 with a byte value according to constants in table
9537  *
9538  * @param [in,out]crc   Register containing the crc.
9539  * @param [in]val       Register containing the byte to fold into the CRC.
9540  * @param [in]table     Register containing the table of crc constants.
9541  *
9542  * uint32_t crc;
9543  * val = crc_table[(val ^ crc) & 0xFF];
9544  * crc = val ^ (crc >> 8);
9545  *
9546  */
9547 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9548   xorl(val, crc);
9549   andl(val, 0xFF);
9550   shrl(crc, 8); // unsigned shift
9551   xorl(crc, Address(table, val, Address::times_4, 0));
9552 }
9553 
9554 /**
9555  * Fold 128-bit data chunk
9556  */
9557 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9558   if (UseAVX > 0) {
9559     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9560     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9561     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9562     pxor(xcrc, xtmp);
9563   } else {
9564     movdqa(xtmp, xcrc);
9565     pclmulhdq(xtmp, xK);   // [123:64]
9566     pclmulldq(xcrc, xK);   // [63:0]
9567     pxor(xcrc, xtmp);
9568     movdqu(xtmp, Address(buf, offset));
9569     pxor(xcrc, xtmp);
9570   }
9571 }
9572 
9573 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9574   if (UseAVX > 0) {
9575     vpclmulhdq(xtmp, xK, xcrc);
9576     vpclmulldq(xcrc, xK, xcrc);
9577     pxor(xcrc, xbuf);
9578     pxor(xcrc, xtmp);
9579   } else {
9580     movdqa(xtmp, xcrc);
9581     pclmulhdq(xtmp, xK);
9582     pclmulldq(xcrc, xK);
9583     pxor(xcrc, xbuf);
9584     pxor(xcrc, xtmp);
9585   }
9586 }
9587 
9588 /**
9589  * 8-bit folds to compute 32-bit CRC
9590  *
9591  * uint64_t xcrc;
9592  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9593  */
9594 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9595   movdl(tmp, xcrc);
9596   andl(tmp, 0xFF);
9597   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9598   psrldq(xcrc, 1); // unsigned shift one byte
9599   pxor(xcrc, xtmp);
9600 }
9601 
9602 /**
9603  * uint32_t crc;
9604  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9605  */
9606 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9607   movl(tmp, crc);
9608   andl(tmp, 0xFF);
9609   shrl(crc, 8);
9610   xorl(crc, Address(table, tmp, Address::times_4, 0));
9611 }
9612 
9613 /**
9614  * @param crc   register containing existing CRC (32-bit)
9615  * @param buf   register pointing to input byte buffer (byte*)
9616  * @param len   register containing number of bytes
9617  * @param table register that will contain address of CRC table
9618  * @param tmp   scratch register
9619  */
9620 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9621   assert_different_registers(crc, buf, len, table, tmp, rax);
9622 
9623   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9624   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9625 
9626   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9627   // context for the registers used, where all instructions below are using 128-bit mode
9628   // On EVEX without VL and BW, these instructions will all be AVX.
9629   if (VM_Version::supports_avx512vlbw()) {
9630     movl(tmp, 0xffff);
9631     kmovwl(k1, tmp);
9632   }
9633 
9634   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9635   notl(crc); // ~crc
9636   cmpl(len, 16);
9637   jcc(Assembler::less, L_tail);
9638 
9639   // Align buffer to 16 bytes
9640   movl(tmp, buf);
9641   andl(tmp, 0xF);
9642   jccb(Assembler::zero, L_aligned);
9643   subl(tmp,  16);
9644   addl(len, tmp);
9645 
9646   align(4);
9647   BIND(L_align_loop);
9648   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9649   update_byte_crc32(crc, rax, table);
9650   increment(buf);
9651   incrementl(tmp);
9652   jccb(Assembler::less, L_align_loop);
9653 
9654   BIND(L_aligned);
9655   movl(tmp, len); // save
9656   shrl(len, 4);
9657   jcc(Assembler::zero, L_tail_restore);
9658 
9659   // Fold crc into first bytes of vector
9660   movdqa(xmm1, Address(buf, 0));
9661   movdl(rax, xmm1);
9662   xorl(crc, rax);
9663   pinsrd(xmm1, crc, 0);
9664   addptr(buf, 16);
9665   subl(len, 4); // len > 0
9666   jcc(Assembler::less, L_fold_tail);
9667 
9668   movdqa(xmm2, Address(buf,  0));
9669   movdqa(xmm3, Address(buf, 16));
9670   movdqa(xmm4, Address(buf, 32));
9671   addptr(buf, 48);
9672   subl(len, 3);
9673   jcc(Assembler::lessEqual, L_fold_512b);
9674 
9675   // Fold total 512 bits of polynomial on each iteration,
9676   // 128 bits per each of 4 parallel streams.
9677   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9678 
9679   align(32);
9680   BIND(L_fold_512b_loop);
9681   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9682   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9683   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9684   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9685   addptr(buf, 64);
9686   subl(len, 4);
9687   jcc(Assembler::greater, L_fold_512b_loop);
9688 
9689   // Fold 512 bits to 128 bits.
9690   BIND(L_fold_512b);
9691   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9692   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
9693   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
9694   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
9695 
9696   // Fold the rest of 128 bits data chunks
9697   BIND(L_fold_tail);
9698   addl(len, 3);
9699   jccb(Assembler::lessEqual, L_fold_128b);
9700   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9701 
9702   BIND(L_fold_tail_loop);
9703   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9704   addptr(buf, 16);
9705   decrementl(len);
9706   jccb(Assembler::greater, L_fold_tail_loop);
9707 
9708   // Fold 128 bits in xmm1 down into 32 bits in crc register.
9709   BIND(L_fold_128b);
9710   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
9711   if (UseAVX > 0) {
9712     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
9713     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
9714     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
9715   } else {
9716     movdqa(xmm2, xmm0);
9717     pclmulqdq(xmm2, xmm1, 0x1);
9718     movdqa(xmm3, xmm0);
9719     pand(xmm3, xmm2);
9720     pclmulqdq(xmm0, xmm3, 0x1);
9721   }
9722   psrldq(xmm1, 8);
9723   psrldq(xmm2, 4);
9724   pxor(xmm0, xmm1);
9725   pxor(xmm0, xmm2);
9726 
9727   // 8 8-bit folds to compute 32-bit CRC.
9728   for (int j = 0; j < 4; j++) {
9729     fold_8bit_crc32(xmm0, table, xmm1, rax);
9730   }
9731   movdl(crc, xmm0); // mov 32 bits to general register
9732   for (int j = 0; j < 4; j++) {
9733     fold_8bit_crc32(crc, table, rax);
9734   }
9735 
9736   BIND(L_tail_restore);
9737   movl(len, tmp); // restore
9738   BIND(L_tail);
9739   andl(len, 0xf);
9740   jccb(Assembler::zero, L_exit);
9741 
9742   // Fold the rest of bytes
9743   align(4);
9744   BIND(L_tail_loop);
9745   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9746   update_byte_crc32(crc, rax, table);
9747   increment(buf);
9748   decrementl(len);
9749   jccb(Assembler::greater, L_tail_loop);
9750 
9751   BIND(L_exit);
9752   notl(crc); // ~c
9753 }
9754 
9755 #ifdef _LP64
9756 // S. Gueron / Information Processing Letters 112 (2012) 184
9757 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
9758 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
9759 // Output: the 64-bit carry-less product of B * CONST
9760 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
9761                                      Register tmp1, Register tmp2, Register tmp3) {
9762   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9763   if (n > 0) {
9764     addq(tmp3, n * 256 * 8);
9765   }
9766   //    Q1 = TABLEExt[n][B & 0xFF];
9767   movl(tmp1, in);
9768   andl(tmp1, 0x000000FF);
9769   shll(tmp1, 3);
9770   addq(tmp1, tmp3);
9771   movq(tmp1, Address(tmp1, 0));
9772 
9773   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9774   movl(tmp2, in);
9775   shrl(tmp2, 8);
9776   andl(tmp2, 0x000000FF);
9777   shll(tmp2, 3);
9778   addq(tmp2, tmp3);
9779   movq(tmp2, Address(tmp2, 0));
9780 
9781   shlq(tmp2, 8);
9782   xorq(tmp1, tmp2);
9783 
9784   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9785   movl(tmp2, in);
9786   shrl(tmp2, 16);
9787   andl(tmp2, 0x000000FF);
9788   shll(tmp2, 3);
9789   addq(tmp2, tmp3);
9790   movq(tmp2, Address(tmp2, 0));
9791 
9792   shlq(tmp2, 16);
9793   xorq(tmp1, tmp2);
9794 
9795   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9796   shrl(in, 24);
9797   andl(in, 0x000000FF);
9798   shll(in, 3);
9799   addq(in, tmp3);
9800   movq(in, Address(in, 0));
9801 
9802   shlq(in, 24);
9803   xorq(in, tmp1);
9804   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9805 }
9806 
9807 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9808                                       Register in_out,
9809                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9810                                       XMMRegister w_xtmp2,
9811                                       Register tmp1,
9812                                       Register n_tmp2, Register n_tmp3) {
9813   if (is_pclmulqdq_supported) {
9814     movdl(w_xtmp1, in_out); // modified blindly
9815 
9816     movl(tmp1, const_or_pre_comp_const_index);
9817     movdl(w_xtmp2, tmp1);
9818     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9819 
9820     movdq(in_out, w_xtmp1);
9821   } else {
9822     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
9823   }
9824 }
9825 
9826 // Recombination Alternative 2: No bit-reflections
9827 // T1 = (CRC_A * U1) << 1
9828 // T2 = (CRC_B * U2) << 1
9829 // C1 = T1 >> 32
9830 // C2 = T2 >> 32
9831 // T1 = T1 & 0xFFFFFFFF
9832 // T2 = T2 & 0xFFFFFFFF
9833 // T1 = CRC32(0, T1)
9834 // T2 = CRC32(0, T2)
9835 // C1 = C1 ^ T1
9836 // C2 = C2 ^ T2
9837 // CRC = C1 ^ C2 ^ CRC_C
9838 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,
9839                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9840                                      Register tmp1, Register tmp2,
9841                                      Register n_tmp3) {
9842   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9843   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9844   shlq(in_out, 1);
9845   movl(tmp1, in_out);
9846   shrq(in_out, 32);
9847   xorl(tmp2, tmp2);
9848   crc32(tmp2, tmp1, 4);
9849   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
9850   shlq(in1, 1);
9851   movl(tmp1, in1);
9852   shrq(in1, 32);
9853   xorl(tmp2, tmp2);
9854   crc32(tmp2, tmp1, 4);
9855   xorl(in1, tmp2);
9856   xorl(in_out, in1);
9857   xorl(in_out, in2);
9858 }
9859 
9860 // Set N to predefined value
9861 // Subtract from a lenght of a buffer
9862 // execute in a loop:
9863 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
9864 // for i = 1 to N do
9865 //  CRC_A = CRC32(CRC_A, A[i])
9866 //  CRC_B = CRC32(CRC_B, B[i])
9867 //  CRC_C = CRC32(CRC_C, C[i])
9868 // end for
9869 // Recombine
9870 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,
9871                                        Register in_out1, Register in_out2, Register in_out3,
9872                                        Register tmp1, Register tmp2, Register tmp3,
9873                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9874                                        Register tmp4, Register tmp5,
9875                                        Register n_tmp6) {
9876   Label L_processPartitions;
9877   Label L_processPartition;
9878   Label L_exit;
9879 
9880   bind(L_processPartitions);
9881   cmpl(in_out1, 3 * size);
9882   jcc(Assembler::less, L_exit);
9883     xorl(tmp1, tmp1);
9884     xorl(tmp2, tmp2);
9885     movq(tmp3, in_out2);
9886     addq(tmp3, size);
9887 
9888     bind(L_processPartition);
9889       crc32(in_out3, Address(in_out2, 0), 8);
9890       crc32(tmp1, Address(in_out2, size), 8);
9891       crc32(tmp2, Address(in_out2, size * 2), 8);
9892       addq(in_out2, 8);
9893       cmpq(in_out2, tmp3);
9894       jcc(Assembler::less, L_processPartition);
9895     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9896             w_xtmp1, w_xtmp2, w_xtmp3,
9897             tmp4, tmp5,
9898             n_tmp6);
9899     addq(in_out2, 2 * size);
9900     subl(in_out1, 3 * size);
9901     jmp(L_processPartitions);
9902 
9903   bind(L_exit);
9904 }
9905 #else
9906 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
9907                                      Register tmp1, Register tmp2, Register tmp3,
9908                                      XMMRegister xtmp1, XMMRegister xtmp2) {
9909   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9910   if (n > 0) {
9911     addl(tmp3, n * 256 * 8);
9912   }
9913   //    Q1 = TABLEExt[n][B & 0xFF];
9914   movl(tmp1, in_out);
9915   andl(tmp1, 0x000000FF);
9916   shll(tmp1, 3);
9917   addl(tmp1, tmp3);
9918   movq(xtmp1, Address(tmp1, 0));
9919 
9920   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9921   movl(tmp2, in_out);
9922   shrl(tmp2, 8);
9923   andl(tmp2, 0x000000FF);
9924   shll(tmp2, 3);
9925   addl(tmp2, tmp3);
9926   movq(xtmp2, Address(tmp2, 0));
9927 
9928   psllq(xtmp2, 8);
9929   pxor(xtmp1, xtmp2);
9930 
9931   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9932   movl(tmp2, in_out);
9933   shrl(tmp2, 16);
9934   andl(tmp2, 0x000000FF);
9935   shll(tmp2, 3);
9936   addl(tmp2, tmp3);
9937   movq(xtmp2, Address(tmp2, 0));
9938 
9939   psllq(xtmp2, 16);
9940   pxor(xtmp1, xtmp2);
9941 
9942   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9943   shrl(in_out, 24);
9944   andl(in_out, 0x000000FF);
9945   shll(in_out, 3);
9946   addl(in_out, tmp3);
9947   movq(xtmp2, Address(in_out, 0));
9948 
9949   psllq(xtmp2, 24);
9950   pxor(xtmp1, xtmp2); // Result in CXMM
9951   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9952 }
9953 
9954 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9955                                       Register in_out,
9956                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9957                                       XMMRegister w_xtmp2,
9958                                       Register tmp1,
9959                                       Register n_tmp2, Register n_tmp3) {
9960   if (is_pclmulqdq_supported) {
9961     movdl(w_xtmp1, in_out);
9962 
9963     movl(tmp1, const_or_pre_comp_const_index);
9964     movdl(w_xtmp2, tmp1);
9965     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9966     // Keep result in XMM since GPR is 32 bit in length
9967   } else {
9968     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
9969   }
9970 }
9971 
9972 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,
9973                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9974                                      Register tmp1, Register tmp2,
9975                                      Register n_tmp3) {
9976   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9977   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9978 
9979   psllq(w_xtmp1, 1);
9980   movdl(tmp1, w_xtmp1);
9981   psrlq(w_xtmp1, 32);
9982   movdl(in_out, w_xtmp1);
9983 
9984   xorl(tmp2, tmp2);
9985   crc32(tmp2, tmp1, 4);
9986   xorl(in_out, tmp2);
9987 
9988   psllq(w_xtmp2, 1);
9989   movdl(tmp1, w_xtmp2);
9990   psrlq(w_xtmp2, 32);
9991   movdl(in1, w_xtmp2);
9992 
9993   xorl(tmp2, tmp2);
9994   crc32(tmp2, tmp1, 4);
9995   xorl(in1, tmp2);
9996   xorl(in_out, in1);
9997   xorl(in_out, in2);
9998 }
9999 
10000 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,
10001                                        Register in_out1, Register in_out2, Register in_out3,
10002                                        Register tmp1, Register tmp2, Register tmp3,
10003                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10004                                        Register tmp4, Register tmp5,
10005                                        Register n_tmp6) {
10006   Label L_processPartitions;
10007   Label L_processPartition;
10008   Label L_exit;
10009 
10010   bind(L_processPartitions);
10011   cmpl(in_out1, 3 * size);
10012   jcc(Assembler::less, L_exit);
10013     xorl(tmp1, tmp1);
10014     xorl(tmp2, tmp2);
10015     movl(tmp3, in_out2);
10016     addl(tmp3, size);
10017 
10018     bind(L_processPartition);
10019       crc32(in_out3, Address(in_out2, 0), 4);
10020       crc32(tmp1, Address(in_out2, size), 4);
10021       crc32(tmp2, Address(in_out2, size*2), 4);
10022       crc32(in_out3, Address(in_out2, 0+4), 4);
10023       crc32(tmp1, Address(in_out2, size+4), 4);
10024       crc32(tmp2, Address(in_out2, size*2+4), 4);
10025       addl(in_out2, 8);
10026       cmpl(in_out2, tmp3);
10027       jcc(Assembler::less, L_processPartition);
10028 
10029         push(tmp3);
10030         push(in_out1);
10031         push(in_out2);
10032         tmp4 = tmp3;
10033         tmp5 = in_out1;
10034         n_tmp6 = in_out2;
10035 
10036       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10037             w_xtmp1, w_xtmp2, w_xtmp3,
10038             tmp4, tmp5,
10039             n_tmp6);
10040 
10041         pop(in_out2);
10042         pop(in_out1);
10043         pop(tmp3);
10044 
10045     addl(in_out2, 2 * size);
10046     subl(in_out1, 3 * size);
10047     jmp(L_processPartitions);
10048 
10049   bind(L_exit);
10050 }
10051 #endif //LP64
10052 
10053 #ifdef _LP64
10054 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10055 // Input: A buffer I of L bytes.
10056 // Output: the CRC32C value of the buffer.
10057 // Notations:
10058 // Write L = 24N + r, with N = floor (L/24).
10059 // r = L mod 24 (0 <= r < 24).
10060 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10061 // N quadwords, and R consists of r bytes.
10062 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10063 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10064 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10065 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10066 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10067                                           Register tmp1, Register tmp2, Register tmp3,
10068                                           Register tmp4, Register tmp5, Register tmp6,
10069                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10070                                           bool is_pclmulqdq_supported) {
10071   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10072   Label L_wordByWord;
10073   Label L_byteByByteProlog;
10074   Label L_byteByByte;
10075   Label L_exit;
10076 
10077   if (is_pclmulqdq_supported ) {
10078     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10079     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10080 
10081     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10082     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10083 
10084     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10085     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10086     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10087   } else {
10088     const_or_pre_comp_const_index[0] = 1;
10089     const_or_pre_comp_const_index[1] = 0;
10090 
10091     const_or_pre_comp_const_index[2] = 3;
10092     const_or_pre_comp_const_index[3] = 2;
10093 
10094     const_or_pre_comp_const_index[4] = 5;
10095     const_or_pre_comp_const_index[5] = 4;
10096    }
10097   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10098                     in2, in1, in_out,
10099                     tmp1, tmp2, tmp3,
10100                     w_xtmp1, w_xtmp2, w_xtmp3,
10101                     tmp4, tmp5,
10102                     tmp6);
10103   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10104                     in2, in1, in_out,
10105                     tmp1, tmp2, tmp3,
10106                     w_xtmp1, w_xtmp2, w_xtmp3,
10107                     tmp4, tmp5,
10108                     tmp6);
10109   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10110                     in2, in1, in_out,
10111                     tmp1, tmp2, tmp3,
10112                     w_xtmp1, w_xtmp2, w_xtmp3,
10113                     tmp4, tmp5,
10114                     tmp6);
10115   movl(tmp1, in2);
10116   andl(tmp1, 0x00000007);
10117   negl(tmp1);
10118   addl(tmp1, in2);
10119   addq(tmp1, in1);
10120 
10121   BIND(L_wordByWord);
10122   cmpq(in1, tmp1);
10123   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10124     crc32(in_out, Address(in1, 0), 4);
10125     addq(in1, 4);
10126     jmp(L_wordByWord);
10127 
10128   BIND(L_byteByByteProlog);
10129   andl(in2, 0x00000007);
10130   movl(tmp2, 1);
10131 
10132   BIND(L_byteByByte);
10133   cmpl(tmp2, in2);
10134   jccb(Assembler::greater, L_exit);
10135     crc32(in_out, Address(in1, 0), 1);
10136     incq(in1);
10137     incl(tmp2);
10138     jmp(L_byteByByte);
10139 
10140   BIND(L_exit);
10141 }
10142 #else
10143 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10144                                           Register tmp1, Register  tmp2, Register tmp3,
10145                                           Register tmp4, Register  tmp5, Register tmp6,
10146                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10147                                           bool is_pclmulqdq_supported) {
10148   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10149   Label L_wordByWord;
10150   Label L_byteByByteProlog;
10151   Label L_byteByByte;
10152   Label L_exit;
10153 
10154   if (is_pclmulqdq_supported) {
10155     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10156     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10157 
10158     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10159     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10160 
10161     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10162     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10163   } else {
10164     const_or_pre_comp_const_index[0] = 1;
10165     const_or_pre_comp_const_index[1] = 0;
10166 
10167     const_or_pre_comp_const_index[2] = 3;
10168     const_or_pre_comp_const_index[3] = 2;
10169 
10170     const_or_pre_comp_const_index[4] = 5;
10171     const_or_pre_comp_const_index[5] = 4;
10172   }
10173   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10174                     in2, in1, in_out,
10175                     tmp1, tmp2, tmp3,
10176                     w_xtmp1, w_xtmp2, w_xtmp3,
10177                     tmp4, tmp5,
10178                     tmp6);
10179   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10180                     in2, in1, in_out,
10181                     tmp1, tmp2, tmp3,
10182                     w_xtmp1, w_xtmp2, w_xtmp3,
10183                     tmp4, tmp5,
10184                     tmp6);
10185   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10186                     in2, in1, in_out,
10187                     tmp1, tmp2, tmp3,
10188                     w_xtmp1, w_xtmp2, w_xtmp3,
10189                     tmp4, tmp5,
10190                     tmp6);
10191   movl(tmp1, in2);
10192   andl(tmp1, 0x00000007);
10193   negl(tmp1);
10194   addl(tmp1, in2);
10195   addl(tmp1, in1);
10196 
10197   BIND(L_wordByWord);
10198   cmpl(in1, tmp1);
10199   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10200     crc32(in_out, Address(in1,0), 4);
10201     addl(in1, 4);
10202     jmp(L_wordByWord);
10203 
10204   BIND(L_byteByByteProlog);
10205   andl(in2, 0x00000007);
10206   movl(tmp2, 1);
10207 
10208   BIND(L_byteByByte);
10209   cmpl(tmp2, in2);
10210   jccb(Assembler::greater, L_exit);
10211     movb(tmp1, Address(in1, 0));
10212     crc32(in_out, tmp1, 1);
10213     incl(in1);
10214     incl(tmp2);
10215     jmp(L_byteByByte);
10216 
10217   BIND(L_exit);
10218 }
10219 #endif // LP64
10220 #undef BIND
10221 #undef BLOCK_COMMENT
10222 
10223 
10224 // Compress char[] array to byte[].
10225 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10226                                          XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10227                                          XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10228                                          Register tmp5, Register result) {
10229   Label copy_chars_loop, return_length, return_zero, done;
10230 
10231   // rsi: src
10232   // rdi: dst
10233   // rdx: len
10234   // rcx: tmp5
10235   // rax: result
10236 
10237   // rsi holds start addr of source char[] to be compressed
10238   // rdi holds start addr of destination byte[]
10239   // rdx holds length
10240 
10241   assert(len != result, "");
10242 
10243   // save length for return
10244   push(len);
10245 
10246   if (UseSSE42Intrinsics) {
10247     Label copy_32_loop, copy_16, copy_tail;
10248 
10249     movl(result, len);
10250     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10251 
10252     // vectored compression
10253     andl(len, 0xfffffff0);    // vector count (in chars)
10254     andl(result, 0x0000000f);    // tail count (in chars)
10255     testl(len, len);
10256     jccb(Assembler::zero, copy_16);
10257 
10258     // compress 16 chars per iter
10259     movdl(tmp1Reg, tmp5);
10260     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10261     pxor(tmp4Reg, tmp4Reg);
10262 
10263     lea(src, Address(src, len, Address::times_2));
10264     lea(dst, Address(dst, len, Address::times_1));
10265     negptr(len);
10266 
10267     bind(copy_32_loop);
10268     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10269     por(tmp4Reg, tmp2Reg);
10270     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10271     por(tmp4Reg, tmp3Reg);
10272     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10273     jcc(Assembler::notZero, return_zero);
10274     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10275     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10276     addptr(len, 16);
10277     jcc(Assembler::notZero, copy_32_loop);
10278 
10279     // compress next vector of 8 chars (if any)
10280     bind(copy_16);
10281     movl(len, result);
10282     andl(len, 0xfffffff8);    // vector count (in chars)
10283     andl(result, 0x00000007);    // tail count (in chars)
10284     testl(len, len);
10285     jccb(Assembler::zero, copy_tail);
10286 
10287     movdl(tmp1Reg, tmp5);
10288     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10289     pxor(tmp3Reg, tmp3Reg);
10290 
10291     movdqu(tmp2Reg, Address(src, 0));
10292     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10293     jccb(Assembler::notZero, return_zero);
10294     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10295     movq(Address(dst, 0), tmp2Reg);
10296     addptr(src, 16);
10297     addptr(dst, 8);
10298 
10299     bind(copy_tail);
10300     movl(len, result);
10301   }
10302   // compress 1 char per iter
10303   testl(len, len);
10304   jccb(Assembler::zero, return_length);
10305   lea(src, Address(src, len, Address::times_2));
10306   lea(dst, Address(dst, len, Address::times_1));
10307   negptr(len);
10308 
10309   bind(copy_chars_loop);
10310   load_unsigned_short(result, Address(src, len, Address::times_2));
10311   testl(result, 0xff00);      // check if Unicode char
10312   jccb(Assembler::notZero, return_zero);
10313   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10314   increment(len);
10315   jcc(Assembler::notZero, copy_chars_loop);
10316 
10317   // if compression succeeded, return length
10318   bind(return_length);
10319   pop(result);
10320   jmpb(done);
10321 
10322   // if compression failed, return 0
10323   bind(return_zero);
10324   xorl(result, result);
10325   addptr(rsp, wordSize);
10326 
10327   bind(done);
10328 }
10329 
10330 // Inflate byte[] array to char[].
10331 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10332                                         XMMRegister tmp1, Register tmp2) {
10333   Label copy_chars_loop, done;
10334 
10335   // rsi: src
10336   // rdi: dst
10337   // rdx: len
10338   // rcx: tmp2
10339 
10340   // rsi holds start addr of source byte[] to be inflated
10341   // rdi holds start addr of destination char[]
10342   // rdx holds length
10343   assert_different_registers(src, dst, len, tmp2);
10344 
10345   if (UseSSE42Intrinsics) {
10346     Label copy_8_loop, copy_bytes, copy_tail;
10347 
10348     movl(tmp2, len);
10349     andl(tmp2, 0x00000007);   // tail count (in chars)
10350     andl(len, 0xfffffff8);    // vector count (in chars)
10351     jccb(Assembler::zero, copy_tail);
10352 
10353     // vectored inflation
10354     lea(src, Address(src, len, Address::times_1));
10355     lea(dst, Address(dst, len, Address::times_2));
10356     negptr(len);
10357 
10358     // inflate 8 chars per iter
10359     bind(copy_8_loop);
10360     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10361     movdqu(Address(dst, len, Address::times_2), tmp1);
10362     addptr(len, 8);
10363     jcc(Assembler::notZero, copy_8_loop);
10364 
10365     bind(copy_tail);
10366     movl(len, tmp2);
10367 
10368     cmpl(len, 4);
10369     jccb(Assembler::less, copy_bytes);
10370 
10371     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10372     pmovzxbw(tmp1, tmp1);
10373     movq(Address(dst, 0), tmp1);
10374     subptr(len, 4);
10375     addptr(src, 4);
10376     addptr(dst, 8);
10377 
10378     bind(copy_bytes);
10379   }
10380   testl(len, len);
10381   jccb(Assembler::zero, done);
10382   lea(src, Address(src, len, Address::times_1));
10383   lea(dst, Address(dst, len, Address::times_2));
10384   negptr(len);
10385 
10386   // inflate 1 char per iter
10387   bind(copy_chars_loop);
10388   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10389   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10390   increment(len);
10391   jcc(Assembler::notZero, copy_chars_loop);
10392 
10393   bind(done);
10394 }
10395 
10396 
10397 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10398   switch (cond) {
10399     // Note some conditions are synonyms for others
10400     case Assembler::zero:         return Assembler::notZero;
10401     case Assembler::notZero:      return Assembler::zero;
10402     case Assembler::less:         return Assembler::greaterEqual;
10403     case Assembler::lessEqual:    return Assembler::greater;
10404     case Assembler::greater:      return Assembler::lessEqual;
10405     case Assembler::greaterEqual: return Assembler::less;
10406     case Assembler::below:        return Assembler::aboveEqual;
10407     case Assembler::belowEqual:   return Assembler::above;
10408     case Assembler::above:        return Assembler::belowEqual;
10409     case Assembler::aboveEqual:   return Assembler::below;
10410     case Assembler::overflow:     return Assembler::noOverflow;
10411     case Assembler::noOverflow:   return Assembler::overflow;
10412     case Assembler::negative:     return Assembler::positive;
10413     case Assembler::positive:     return Assembler::negative;
10414     case Assembler::parity:       return Assembler::noParity;
10415     case Assembler::noParity:     return Assembler::parity;
10416   }
10417   ShouldNotReachHere(); return Assembler::overflow;
10418 }
10419 
10420 SkipIfEqual::SkipIfEqual(
10421     MacroAssembler* masm, const bool* flag_addr, bool value) {
10422   _masm = masm;
10423   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10424   _masm->jcc(Assembler::equal, _label);
10425 }
10426 
10427 SkipIfEqual::~SkipIfEqual() {
10428   _masm->bind(_label);
10429 }