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