1 /*
   2  * Copyright (c) 1997, 2016, 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 "runtime/thread.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #endif // INCLUDE_ALL_GCS
  49 #include "crc32c.h"
  50 #ifdef COMPILER2
  51 #include "opto/intrinsicnode.hpp"
  52 #endif
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #define STOP(error) stop(error)
  57 #else
  58 #define BLOCK_COMMENT(str) block_comment(str)
  59 #define STOP(error) block_comment(error); stop(error)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 #ifdef ASSERT
  65 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  66 #endif
  67 
  68 static Assembler::Condition reverse[] = {
  69     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  70     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  71     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  72     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  73     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  74     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  75     Assembler::above          /* belowEqual    = 0x6 */ ,
  76     Assembler::belowEqual     /* above         = 0x7 */ ,
  77     Assembler::positive       /* negative      = 0x8 */ ,
  78     Assembler::negative       /* positive      = 0x9 */ ,
  79     Assembler::noParity       /* parity        = 0xa */ ,
  80     Assembler::parity         /* noParity      = 0xb */ ,
  81     Assembler::greaterEqual   /* less          = 0xc */ ,
  82     Assembler::less           /* greaterEqual  = 0xd */ ,
  83     Assembler::greater        /* lessEqual     = 0xe */ ,
  84     Assembler::lessEqual      /* greater       = 0xf, */
  85 
  86 };
  87 
  88 
  89 // Implementation of MacroAssembler
  90 
  91 // First all the versions that have distinct versions depending on 32/64 bit
  92 // Unless the difference is trivial (1 line or so).
  93 
  94 #ifndef _LP64
  95 
  96 // 32bit versions
  97 
  98 Address MacroAssembler::as_Address(AddressLiteral adr) {
  99   return Address(adr.target(), adr.rspec());
 100 }
 101 
 102 Address MacroAssembler::as_Address(ArrayAddress adr) {
 103   return Address::make_array(adr);
 104 }
 105 
 106 void MacroAssembler::call_VM_leaf_base(address entry_point,
 107                                        int number_of_arguments) {
 108   call(RuntimeAddress(entry_point));
 109   increment(rsp, number_of_arguments * wordSize);
 110 }
 111 
 112 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 113   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 114 }
 115 
 116 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 117   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 121   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 125   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 126 }
 127 
 128 void MacroAssembler::extend_sign(Register hi, Register lo) {
 129   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 130   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 131     cdql();
 132   } else {
 133     movl(hi, lo);
 134     sarl(hi, 31);
 135   }
 136 }
 137 
 138 void MacroAssembler::jC2(Register tmp, Label& L) {
 139   // set parity bit if FPU flag C2 is set (via rax)
 140   save_rax(tmp);
 141   fwait(); fnstsw_ax();
 142   sahf();
 143   restore_rax(tmp);
 144   // branch
 145   jcc(Assembler::parity, L);
 146 }
 147 
 148 void MacroAssembler::jnC2(Register tmp, Label& L) {
 149   // set parity bit if FPU flag C2 is set (via rax)
 150   save_rax(tmp);
 151   fwait(); fnstsw_ax();
 152   sahf();
 153   restore_rax(tmp);
 154   // branch
 155   jcc(Assembler::noParity, L);
 156 }
 157 
 158 // 32bit can do a case table jump in one instruction but we no longer allow the base
 159 // to be installed in the Address class
 160 void MacroAssembler::jump(ArrayAddress entry) {
 161   jmp(as_Address(entry));
 162 }
 163 
 164 // Note: y_lo will be destroyed
 165 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 166   // Long compare for Java (semantics as described in JVM spec.)
 167   Label high, low, done;
 168 
 169   cmpl(x_hi, y_hi);
 170   jcc(Assembler::less, low);
 171   jcc(Assembler::greater, high);
 172   // x_hi is the return register
 173   xorl(x_hi, x_hi);
 174   cmpl(x_lo, y_lo);
 175   jcc(Assembler::below, low);
 176   jcc(Assembler::equal, done);
 177 
 178   bind(high);
 179   xorl(x_hi, x_hi);
 180   increment(x_hi);
 181   jmp(done);
 182 
 183   bind(low);
 184   xorl(x_hi, x_hi);
 185   decrementl(x_hi);
 186 
 187   bind(done);
 188 }
 189 
 190 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 191     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 192 }
 193 
 194 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 195   // leal(dst, as_Address(adr));
 196   // see note in movl as to why we must use a move
 197   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 198 }
 199 
 200 void MacroAssembler::leave() {
 201   mov(rsp, rbp);
 202   pop(rbp);
 203 }
 204 
 205 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 206   // Multiplication of two Java long values stored on the stack
 207   // as illustrated below. Result is in rdx:rax.
 208   //
 209   // rsp ---> [  ??  ] \               \
 210   //            ....    | y_rsp_offset  |
 211   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 212   //          [ y_hi ]                  | (in bytes)
 213   //            ....                    |
 214   //          [ x_lo ]                 /
 215   //          [ x_hi ]
 216   //            ....
 217   //
 218   // Basic idea: lo(result) = lo(x_lo * y_lo)
 219   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 220   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 221   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 222   Label quick;
 223   // load x_hi, y_hi and check if quick
 224   // multiplication is possible
 225   movl(rbx, x_hi);
 226   movl(rcx, y_hi);
 227   movl(rax, rbx);
 228   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 229   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 230   // do full multiplication
 231   // 1st step
 232   mull(y_lo);                                    // x_hi * y_lo
 233   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 234   // 2nd step
 235   movl(rax, x_lo);
 236   mull(rcx);                                     // x_lo * y_hi
 237   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 238   // 3rd step
 239   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 240   movl(rax, x_lo);
 241   mull(y_lo);                                    // x_lo * y_lo
 242   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 243 }
 244 
 245 void MacroAssembler::lneg(Register hi, Register lo) {
 246   negl(lo);
 247   adcl(hi, 0);
 248   negl(hi);
 249 }
 250 
 251 void MacroAssembler::lshl(Register hi, Register lo) {
 252   // Java shift left long support (semantics as described in JVM spec., p.305)
 253   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 254   // shift value is in rcx !
 255   assert(hi != rcx, "must not use rcx");
 256   assert(lo != rcx, "must not use rcx");
 257   const Register s = rcx;                        // shift count
 258   const int      n = BitsPerWord;
 259   Label L;
 260   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 261   cmpl(s, n);                                    // if (s < n)
 262   jcc(Assembler::less, L);                       // else (s >= n)
 263   movl(hi, lo);                                  // x := x << n
 264   xorl(lo, lo);
 265   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 266   bind(L);                                       // s (mod n) < n
 267   shldl(hi, lo);                                 // x := x << s
 268   shll(lo);
 269 }
 270 
 271 
 272 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 273   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 274   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 275   assert(hi != rcx, "must not use rcx");
 276   assert(lo != rcx, "must not use rcx");
 277   const Register s = rcx;                        // shift count
 278   const int      n = BitsPerWord;
 279   Label L;
 280   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 281   cmpl(s, n);                                    // if (s < n)
 282   jcc(Assembler::less, L);                       // else (s >= n)
 283   movl(lo, hi);                                  // x := x >> n
 284   if (sign_extension) sarl(hi, 31);
 285   else                xorl(hi, hi);
 286   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 287   bind(L);                                       // s (mod n) < n
 288   shrdl(lo, hi);                                 // x := x >> s
 289   if (sign_extension) sarl(hi);
 290   else                shrl(hi);
 291 }
 292 
 293 void MacroAssembler::movoop(Register dst, jobject obj) {
 294   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 295 }
 296 
 297 void MacroAssembler::movoop(Address dst, jobject obj) {
 298   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 302   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 306   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 307 }
 308 
 309 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 310   // scratch register is not used,
 311   // it is defined to match parameters of 64-bit version of this method.
 312   if (src.is_lval()) {
 313     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 314   } else {
 315     movl(dst, as_Address(src));
 316   }
 317 }
 318 
 319 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 320   movl(as_Address(dst), src);
 321 }
 322 
 323 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 324   movl(dst, as_Address(src));
 325 }
 326 
 327 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 328 void MacroAssembler::movptr(Address dst, intptr_t src) {
 329   movl(dst, src);
 330 }
 331 
 332 
 333 void MacroAssembler::pop_callee_saved_registers() {
 334   pop(rcx);
 335   pop(rdx);
 336   pop(rdi);
 337   pop(rsi);
 338 }
 339 
 340 void MacroAssembler::pop_fTOS() {
 341   fld_d(Address(rsp, 0));
 342   addl(rsp, 2 * wordSize);
 343 }
 344 
 345 void MacroAssembler::push_callee_saved_registers() {
 346   push(rsi);
 347   push(rdi);
 348   push(rdx);
 349   push(rcx);
 350 }
 351 
 352 void MacroAssembler::push_fTOS() {
 353   subl(rsp, 2 * wordSize);
 354   fstp_d(Address(rsp, 0));
 355 }
 356 
 357 
 358 void MacroAssembler::pushoop(jobject obj) {
 359   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 360 }
 361 
 362 void MacroAssembler::pushklass(Metadata* obj) {
 363   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 364 }
 365 
 366 void MacroAssembler::pushptr(AddressLiteral src) {
 367   if (src.is_lval()) {
 368     push_literal32((int32_t)src.target(), src.rspec());
 369   } else {
 370     pushl(as_Address(src));
 371   }
 372 }
 373 
 374 void MacroAssembler::set_word_if_not_zero(Register dst) {
 375   xorl(dst, dst);
 376   set_byte_if_not_zero(dst);
 377 }
 378 
 379 static void pass_arg0(MacroAssembler* masm, Register arg) {
 380   masm->push(arg);
 381 }
 382 
 383 static void pass_arg1(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg2(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 static void pass_arg3(MacroAssembler* masm, Register arg) {
 392   masm->push(arg);
 393 }
 394 
 395 #ifndef PRODUCT
 396 extern "C" void findpc(intptr_t x);
 397 #endif
 398 
 399 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 400   // In order to get locks to work, we need to fake a in_VM state
 401   JavaThread* thread = JavaThread::current();
 402   JavaThreadState saved_state = thread->thread_state();
 403   thread->set_thread_state(_thread_in_vm);
 404   if (ShowMessageBoxOnError) {
 405     JavaThread* thread = JavaThread::current();
 406     JavaThreadState saved_state = thread->thread_state();
 407     thread->set_thread_state(_thread_in_vm);
 408     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 409       ttyLocker ttyl;
 410       BytecodeCounter::print();
 411     }
 412     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 413     // This is the value of eip which points to where verify_oop will return.
 414     if (os::message_box(msg, "Execution stopped, print registers?")) {
 415       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 416       BREAKPOINT;
 417     }
 418   } else {
 419     ttyLocker ttyl;
 420     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 421   }
 422   // Don't assert holding the ttyLock
 423     assert(false, "DEBUG MESSAGE: %s", msg);
 424   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 425 }
 426 
 427 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 428   ttyLocker ttyl;
 429   FlagSetting fs(Debugging, true);
 430   tty->print_cr("eip = 0x%08x", eip);
 431 #ifndef PRODUCT
 432   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 433     tty->cr();
 434     findpc(eip);
 435     tty->cr();
 436   }
 437 #endif
 438 #define PRINT_REG(rax) \
 439   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 440   PRINT_REG(rax);
 441   PRINT_REG(rbx);
 442   PRINT_REG(rcx);
 443   PRINT_REG(rdx);
 444   PRINT_REG(rdi);
 445   PRINT_REG(rsi);
 446   PRINT_REG(rbp);
 447   PRINT_REG(rsp);
 448 #undef PRINT_REG
 449   // Print some words near top of staack.
 450   int* dump_sp = (int*) rsp;
 451   for (int col1 = 0; col1 < 8; col1++) {
 452     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 453     os::print_location(tty, *dump_sp++);
 454   }
 455   for (int row = 0; row < 16; row++) {
 456     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 457     for (int col = 0; col < 8; col++) {
 458       tty->print(" 0x%08x", *dump_sp++);
 459     }
 460     tty->cr();
 461   }
 462   // Print some instructions around pc:
 463   Disassembler::decode((address)eip-64, (address)eip);
 464   tty->print_cr("--------");
 465   Disassembler::decode((address)eip, (address)eip+32);
 466 }
 467 
 468 void MacroAssembler::stop(const char* msg) {
 469   ExternalAddress message((address)msg);
 470   // push address of message
 471   pushptr(message.addr());
 472   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 473   pusha();                                            // push registers
 474   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 475   hlt();
 476 }
 477 
 478 void MacroAssembler::warn(const char* msg) {
 479   push_CPU_state();
 480 
 481   ExternalAddress message((address) msg);
 482   // push address of message
 483   pushptr(message.addr());
 484 
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 486   addl(rsp, wordSize);       // discard argument
 487   pop_CPU_state();
 488 }
 489 
 490 void MacroAssembler::print_state() {
 491   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 492   pusha();                                            // push registers
 493 
 494   push_CPU_state();
 495   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 496   pop_CPU_state();
 497 
 498   popa();
 499   addl(rsp, wordSize);
 500 }
 501 
 502 #else // _LP64
 503 
 504 // 64 bit versions
 505 
 506 Address MacroAssembler::as_Address(AddressLiteral adr) {
 507   // amd64 always does this as a pc-rel
 508   // we can be absolute or disp based on the instruction type
 509   // jmp/call are displacements others are absolute
 510   assert(!adr.is_lval(), "must be rval");
 511   assert(reachable(adr), "must be");
 512   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 513 
 514 }
 515 
 516 Address MacroAssembler::as_Address(ArrayAddress adr) {
 517   AddressLiteral base = adr.base();
 518   lea(rscratch1, base);
 519   Address index = adr.index();
 520   assert(index._disp == 0, "must not have disp"); // maybe it can?
 521   Address array(rscratch1, index._index, index._scale, index._disp);
 522   return array;
 523 }
 524 
 525 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 526   Label L, E;
 527 
 528 #ifdef _WIN64
 529   // Windows always allocates space for it's register args
 530   assert(num_args <= 4, "only register arguments supported");
 531   subq(rsp,  frame::arg_reg_save_area_bytes);
 532 #endif
 533 
 534   // Align stack if necessary
 535   testl(rsp, 15);
 536   jcc(Assembler::zero, L);
 537 
 538   subq(rsp, 8);
 539   {
 540     call(RuntimeAddress(entry_point));
 541   }
 542   addq(rsp, 8);
 543   jmp(E);
 544 
 545   bind(L);
 546   {
 547     call(RuntimeAddress(entry_point));
 548   }
 549 
 550   bind(E);
 551 
 552 #ifdef _WIN64
 553   // restore stack pointer
 554   addq(rsp, frame::arg_reg_save_area_bytes);
 555 #endif
 556 
 557 }
 558 
 559 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 560   assert(!src2.is_lval(), "should use cmpptr");
 561 
 562   if (reachable(src2)) {
 563     cmpq(src1, as_Address(src2));
 564   } else {
 565     lea(rscratch1, src2);
 566     Assembler::cmpq(src1, Address(rscratch1, 0));
 567   }
 568 }
 569 
 570 int MacroAssembler::corrected_idivq(Register reg) {
 571   // Full implementation of Java ldiv and lrem; checks for special
 572   // case as described in JVM spec., p.243 & p.271.  The function
 573   // returns the (pc) offset of the idivl instruction - may be needed
 574   // for implicit exceptions.
 575   //
 576   //         normal case                           special case
 577   //
 578   // input : rax: dividend                         min_long
 579   //         reg: divisor   (may not be eax/edx)   -1
 580   //
 581   // output: rax: quotient  (= rax idiv reg)       min_long
 582   //         rdx: remainder (= rax irem reg)       0
 583   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 584   static const int64_t min_long = 0x8000000000000000;
 585   Label normal_case, special_case;
 586 
 587   // check for special case
 588   cmp64(rax, ExternalAddress((address) &min_long));
 589   jcc(Assembler::notEqual, normal_case);
 590   xorl(rdx, rdx); // prepare rdx for possible special case (where
 591                   // remainder = 0)
 592   cmpq(reg, -1);
 593   jcc(Assembler::equal, special_case);
 594 
 595   // handle normal case
 596   bind(normal_case);
 597   cdqq();
 598   int idivq_offset = offset();
 599   idivq(reg);
 600 
 601   // normal and special case exit
 602   bind(special_case);
 603 
 604   return idivq_offset;
 605 }
 606 
 607 void MacroAssembler::decrementq(Register reg, int value) {
 608   if (value == min_jint) { subq(reg, value); return; }
 609   if (value <  0) { incrementq(reg, -value); return; }
 610   if (value == 0) {                        ; return; }
 611   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 612   /* else */      { subq(reg, value)       ; return; }
 613 }
 614 
 615 void MacroAssembler::decrementq(Address dst, int value) {
 616   if (value == min_jint) { subq(dst, value); return; }
 617   if (value <  0) { incrementq(dst, -value); return; }
 618   if (value == 0) {                        ; return; }
 619   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 620   /* else */      { subq(dst, value)       ; return; }
 621 }
 622 
 623 void MacroAssembler::incrementq(AddressLiteral dst) {
 624   if (reachable(dst)) {
 625     incrementq(as_Address(dst));
 626   } else {
 627     lea(rscratch1, dst);
 628     incrementq(Address(rscratch1, 0));
 629   }
 630 }
 631 
 632 void MacroAssembler::incrementq(Register reg, int value) {
 633   if (value == min_jint) { addq(reg, value); return; }
 634   if (value <  0) { decrementq(reg, -value); return; }
 635   if (value == 0) {                        ; return; }
 636   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 637   /* else */      { addq(reg, value)       ; return; }
 638 }
 639 
 640 void MacroAssembler::incrementq(Address dst, int value) {
 641   if (value == min_jint) { addq(dst, value); return; }
 642   if (value <  0) { decrementq(dst, -value); return; }
 643   if (value == 0) {                        ; return; }
 644   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 645   /* else */      { addq(dst, value)       ; return; }
 646 }
 647 
 648 // 32bit can do a case table jump in one instruction but we no longer allow the base
 649 // to be installed in the Address class
 650 void MacroAssembler::jump(ArrayAddress entry) {
 651   lea(rscratch1, entry.base());
 652   Address dispatch = entry.index();
 653   assert(dispatch._base == noreg, "must be");
 654   dispatch._base = rscratch1;
 655   jmp(dispatch);
 656 }
 657 
 658 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 659   ShouldNotReachHere(); // 64bit doesn't use two regs
 660   cmpq(x_lo, y_lo);
 661 }
 662 
 663 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 664     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 665 }
 666 
 667 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 668   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 669   movptr(dst, rscratch1);
 670 }
 671 
 672 void MacroAssembler::leave() {
 673   // %%% is this really better? Why not on 32bit too?
 674   emit_int8((unsigned char)0xC9); // LEAVE
 675 }
 676 
 677 void MacroAssembler::lneg(Register hi, Register lo) {
 678   ShouldNotReachHere(); // 64bit doesn't use two regs
 679   negq(lo);
 680 }
 681 
 682 void MacroAssembler::movoop(Register dst, jobject obj) {
 683   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 684 }
 685 
 686 void MacroAssembler::movoop(Address dst, jobject obj) {
 687   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 688   movq(dst, rscratch1);
 689 }
 690 
 691 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 692   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 693 }
 694 
 695 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 696   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 697   movq(dst, rscratch1);
 698 }
 699 
 700 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 701   if (src.is_lval()) {
 702     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 703   } else {
 704     if (reachable(src)) {
 705       movq(dst, as_Address(src));
 706     } else {
 707       lea(scratch, src);
 708       movq(dst, Address(scratch, 0));
 709     }
 710   }
 711 }
 712 
 713 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 714   movq(as_Address(dst), src);
 715 }
 716 
 717 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 718   movq(dst, as_Address(src));
 719 }
 720 
 721 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 722 void MacroAssembler::movptr(Address dst, intptr_t src) {
 723   mov64(rscratch1, src);
 724   movq(dst, rscratch1);
 725 }
 726 
 727 // These are mostly for initializing NULL
 728 void MacroAssembler::movptr(Address dst, int32_t src) {
 729   movslq(dst, src);
 730 }
 731 
 732 void MacroAssembler::movptr(Register dst, int32_t src) {
 733   mov64(dst, (intptr_t)src);
 734 }
 735 
 736 void MacroAssembler::pushoop(jobject obj) {
 737   movoop(rscratch1, obj);
 738   push(rscratch1);
 739 }
 740 
 741 void MacroAssembler::pushklass(Metadata* obj) {
 742   mov_metadata(rscratch1, obj);
 743   push(rscratch1);
 744 }
 745 
 746 void MacroAssembler::pushptr(AddressLiteral src) {
 747   lea(rscratch1, src);
 748   if (src.is_lval()) {
 749     push(rscratch1);
 750   } else {
 751     pushq(Address(rscratch1, 0));
 752   }
 753 }
 754 
 755 void MacroAssembler::reset_last_Java_frame(bool clear_fp,
 756                                            bool clear_pc) {
 757   // we must set sp to zero to clear frame
 758   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 759   // must clear fp, so that compiled frames are not confused; it is
 760   // possible that we need it only for debugging
 761   if (clear_fp) {
 762     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 763   }
 764 
 765   if (clear_pc) {
 766     movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 767   }
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 773   // determine last_java_sp register
 774   if (!last_java_sp->is_valid()) {
 775     last_java_sp = rsp;
 776   }
 777 
 778   // last_java_fp is optional
 779   if (last_java_fp->is_valid()) {
 780     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 781            last_java_fp);
 782   }
 783 
 784   // last_java_pc is optional
 785   if (last_java_pc != NULL) {
 786     Address java_pc(r15_thread,
 787                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 788     lea(rscratch1, InternalAddress(last_java_pc));
 789     movptr(java_pc, rscratch1);
 790   }
 791 
 792   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 793 }
 794 
 795 static void pass_arg0(MacroAssembler* masm, Register arg) {
 796   if (c_rarg0 != arg ) {
 797     masm->mov(c_rarg0, arg);
 798   }
 799 }
 800 
 801 static void pass_arg1(MacroAssembler* masm, Register arg) {
 802   if (c_rarg1 != arg ) {
 803     masm->mov(c_rarg1, arg);
 804   }
 805 }
 806 
 807 static void pass_arg2(MacroAssembler* masm, Register arg) {
 808   if (c_rarg2 != arg ) {
 809     masm->mov(c_rarg2, arg);
 810   }
 811 }
 812 
 813 static void pass_arg3(MacroAssembler* masm, Register arg) {
 814   if (c_rarg3 != arg ) {
 815     masm->mov(c_rarg3, arg);
 816   }
 817 }
 818 
 819 void MacroAssembler::stop(const char* msg) {
 820   address rip = pc();
 821   pusha(); // get regs on stack
 822   lea(c_rarg0, ExternalAddress((address) msg));
 823   lea(c_rarg1, InternalAddress(rip));
 824   movq(c_rarg2, rsp); // pass pointer to regs array
 825   andq(rsp, -16); // align stack as required by ABI
 826   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 827   hlt();
 828 }
 829 
 830 void MacroAssembler::warn(const char* msg) {
 831   push(rbp);
 832   movq(rbp, rsp);
 833   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 834   push_CPU_state();   // keeps alignment at 16 bytes
 835   lea(c_rarg0, ExternalAddress((address) msg));
 836   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 837   pop_CPU_state();
 838   mov(rsp, rbp);
 839   pop(rbp);
 840 }
 841 
 842 void MacroAssembler::print_state() {
 843   address rip = pc();
 844   pusha();            // get regs on stack
 845   push(rbp);
 846   movq(rbp, rsp);
 847   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 848   push_CPU_state();   // keeps alignment at 16 bytes
 849 
 850   lea(c_rarg0, InternalAddress(rip));
 851   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 852   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 853 
 854   pop_CPU_state();
 855   mov(rsp, rbp);
 856   pop(rbp);
 857   popa();
 858 }
 859 
 860 #ifndef PRODUCT
 861 extern "C" void findpc(intptr_t x);
 862 #endif
 863 
 864 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 865   // In order to get locks to work, we need to fake a in_VM state
 866   if (ShowMessageBoxOnError) {
 867     JavaThread* thread = JavaThread::current();
 868     JavaThreadState saved_state = thread->thread_state();
 869     thread->set_thread_state(_thread_in_vm);
 870 #ifndef PRODUCT
 871     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 872       ttyLocker ttyl;
 873       BytecodeCounter::print();
 874     }
 875 #endif
 876     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 877     // XXX correct this offset for amd64
 878     // This is the value of eip which points to where verify_oop will return.
 879     if (os::message_box(msg, "Execution stopped, print registers?")) {
 880       print_state64(pc, regs);
 881       BREAKPOINT;
 882       assert(false, "start up GDB");
 883     }
 884     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 885   } else {
 886     ttyLocker ttyl;
 887     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 888                     msg);
 889     assert(false, "DEBUG MESSAGE: %s", msg);
 890   }
 891 }
 892 
 893 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 894   ttyLocker ttyl;
 895   FlagSetting fs(Debugging, true);
 896   tty->print_cr("rip = 0x%016lx", pc);
 897 #ifndef PRODUCT
 898   tty->cr();
 899   findpc(pc);
 900   tty->cr();
 901 #endif
 902 #define PRINT_REG(rax, value) \
 903   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 904   PRINT_REG(rax, regs[15]);
 905   PRINT_REG(rbx, regs[12]);
 906   PRINT_REG(rcx, regs[14]);
 907   PRINT_REG(rdx, regs[13]);
 908   PRINT_REG(rdi, regs[8]);
 909   PRINT_REG(rsi, regs[9]);
 910   PRINT_REG(rbp, regs[10]);
 911   PRINT_REG(rsp, regs[11]);
 912   PRINT_REG(r8 , regs[7]);
 913   PRINT_REG(r9 , regs[6]);
 914   PRINT_REG(r10, regs[5]);
 915   PRINT_REG(r11, regs[4]);
 916   PRINT_REG(r12, regs[3]);
 917   PRINT_REG(r13, regs[2]);
 918   PRINT_REG(r14, regs[1]);
 919   PRINT_REG(r15, regs[0]);
 920 #undef PRINT_REG
 921   // Print some words near top of staack.
 922   int64_t* rsp = (int64_t*) regs[11];
 923   int64_t* dump_sp = rsp;
 924   for (int col1 = 0; col1 < 8; col1++) {
 925     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 926     os::print_location(tty, *dump_sp++);
 927   }
 928   for (int row = 0; row < 25; row++) {
 929     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 930     for (int col = 0; col < 4; col++) {
 931       tty->print(" 0x%016lx", *dump_sp++);
 932     }
 933     tty->cr();
 934   }
 935   // Print some instructions around pc:
 936   Disassembler::decode((address)pc-64, (address)pc);
 937   tty->print_cr("--------");
 938   Disassembler::decode((address)pc, (address)pc+32);
 939 }
 940 
 941 #endif // _LP64
 942 
 943 // Now versions that are common to 32/64 bit
 944 
 945 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 946   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 947 }
 948 
 949 void MacroAssembler::addptr(Register dst, Register src) {
 950   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 951 }
 952 
 953 void MacroAssembler::addptr(Address dst, Register src) {
 954   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 955 }
 956 
 957 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 958   if (reachable(src)) {
 959     Assembler::addsd(dst, as_Address(src));
 960   } else {
 961     lea(rscratch1, src);
 962     Assembler::addsd(dst, Address(rscratch1, 0));
 963   }
 964 }
 965 
 966 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 967   if (reachable(src)) {
 968     addss(dst, as_Address(src));
 969   } else {
 970     lea(rscratch1, src);
 971     addss(dst, Address(rscratch1, 0));
 972   }
 973 }
 974 
 975 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 976   if (reachable(src)) {
 977     Assembler::addpd(dst, as_Address(src));
 978   } else {
 979     lea(rscratch1, src);
 980     Assembler::addpd(dst, Address(rscratch1, 0));
 981   }
 982 }
 983 
 984 void MacroAssembler::align(int modulus) {
 985   align(modulus, offset());
 986 }
 987 
 988 void MacroAssembler::align(int modulus, int target) {
 989   if (target % modulus != 0) {
 990     nop(modulus - (target % modulus));
 991   }
 992 }
 993 
 994 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 995   // Used in sign-masking with aligned address.
 996   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 997   if (reachable(src)) {
 998     Assembler::andpd(dst, as_Address(src));
 999   } else {
1000     lea(rscratch1, src);
1001     Assembler::andpd(dst, Address(rscratch1, 0));
1002   }
1003 }
1004 
1005 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1006   // Used in sign-masking with aligned address.
1007   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1008   if (reachable(src)) {
1009     Assembler::andps(dst, as_Address(src));
1010   } else {
1011     lea(rscratch1, src);
1012     Assembler::andps(dst, Address(rscratch1, 0));
1013   }
1014 }
1015 
1016 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1017   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1018 }
1019 
1020 void MacroAssembler::atomic_incl(Address counter_addr) {
1021   if (os::is_MP())
1022     lock();
1023   incrementl(counter_addr);
1024 }
1025 
1026 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1027   if (reachable(counter_addr)) {
1028     atomic_incl(as_Address(counter_addr));
1029   } else {
1030     lea(scr, counter_addr);
1031     atomic_incl(Address(scr, 0));
1032   }
1033 }
1034 
1035 #ifdef _LP64
1036 void MacroAssembler::atomic_incq(Address counter_addr) {
1037   if (os::is_MP())
1038     lock();
1039   incrementq(counter_addr);
1040 }
1041 
1042 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1043   if (reachable(counter_addr)) {
1044     atomic_incq(as_Address(counter_addr));
1045   } else {
1046     lea(scr, counter_addr);
1047     atomic_incq(Address(scr, 0));
1048   }
1049 }
1050 #endif
1051 
1052 // Writes to stack successive pages until offset reached to check for
1053 // stack overflow + shadow pages.  This clobbers tmp.
1054 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1055   movptr(tmp, rsp);
1056   // Bang stack for total size given plus shadow page size.
1057   // Bang one page at a time because large size can bang beyond yellow and
1058   // red zones.
1059   Label loop;
1060   bind(loop);
1061   movl(Address(tmp, (-os::vm_page_size())), size );
1062   subptr(tmp, os::vm_page_size());
1063   subl(size, os::vm_page_size());
1064   jcc(Assembler::greater, loop);
1065 
1066   // Bang down shadow pages too.
1067   // At this point, (tmp-0) is the last address touched, so don't
1068   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1069   // was post-decremented.)  Skip this address by starting at i=1, and
1070   // touch a few more pages below.  N.B.  It is important to touch all
1071   // the way down including all pages in the shadow zone.
1072   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1073     // this could be any sized move but this is can be a debugging crumb
1074     // so the bigger the better.
1075     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1076   }
1077 }
1078 
1079 void MacroAssembler::reserved_stack_check() {
1080     // testing if reserved zone needs to be enabled
1081     Label no_reserved_zone_enabling;
1082     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1083     NOT_LP64(get_thread(rsi);)
1084 
1085     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1086     jcc(Assembler::below, no_reserved_zone_enabling);
1087 
1088     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1089     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1090     should_not_reach_here();
1091 
1092     bind(no_reserved_zone_enabling);
1093 }
1094 
1095 int MacroAssembler::biased_locking_enter(Register lock_reg,
1096                                          Register obj_reg,
1097                                          Register swap_reg,
1098                                          Register tmp_reg,
1099                                          bool swap_reg_contains_mark,
1100                                          Label& done,
1101                                          Label* slow_case,
1102                                          BiasedLockingCounters* counters) {
1103   assert(UseBiasedLocking, "why call this otherwise?");
1104   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1105   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1106   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1107   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1108   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1109   Address saved_mark_addr(lock_reg, 0);
1110 
1111   if (PrintBiasedLockingStatistics && counters == NULL) {
1112     counters = BiasedLocking::counters();
1113   }
1114   // Biased locking
1115   // See whether the lock is currently biased toward our thread and
1116   // whether the epoch is still valid
1117   // Note that the runtime guarantees sufficient alignment of JavaThread
1118   // pointers to allow age to be placed into low bits
1119   // First check to see whether biasing is even enabled for this object
1120   Label cas_label;
1121   int null_check_offset = -1;
1122   if (!swap_reg_contains_mark) {
1123     null_check_offset = offset();
1124     movptr(swap_reg, mark_addr);
1125   }
1126   movptr(tmp_reg, swap_reg);
1127   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1128   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1129   jcc(Assembler::notEqual, cas_label);
1130   // The bias pattern is present in the object's header. Need to check
1131   // whether the bias owner and the epoch are both still current.
1132 #ifndef _LP64
1133   // Note that because there is no current thread register on x86_32 we
1134   // need to store off the mark word we read out of the object to
1135   // avoid reloading it and needing to recheck invariants below. This
1136   // store is unfortunate but it makes the overall code shorter and
1137   // simpler.
1138   movptr(saved_mark_addr, swap_reg);
1139 #endif
1140   if (swap_reg_contains_mark) {
1141     null_check_offset = offset();
1142   }
1143   load_prototype_header(tmp_reg, obj_reg);
1144 #ifdef _LP64
1145   orptr(tmp_reg, r15_thread);
1146   xorptr(tmp_reg, swap_reg);
1147   Register header_reg = tmp_reg;
1148 #else
1149   xorptr(tmp_reg, swap_reg);
1150   get_thread(swap_reg);
1151   xorptr(swap_reg, tmp_reg);
1152   Register header_reg = swap_reg;
1153 #endif
1154   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1155   if (counters != NULL) {
1156     cond_inc32(Assembler::zero,
1157                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1158   }
1159   jcc(Assembler::equal, done);
1160 
1161   Label try_revoke_bias;
1162   Label try_rebias;
1163 
1164   // At this point we know that the header has the bias pattern and
1165   // that we are not the bias owner in the current epoch. We need to
1166   // figure out more details about the state of the header in order to
1167   // know what operations can be legally performed on the object's
1168   // header.
1169 
1170   // If the low three bits in the xor result aren't clear, that means
1171   // the prototype header is no longer biased and we have to revoke
1172   // the bias on this object.
1173   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1174   jccb(Assembler::notZero, try_revoke_bias);
1175 
1176   // Biasing is still enabled for this data type. See whether the
1177   // epoch of the current bias is still valid, meaning that the epoch
1178   // bits of the mark word are equal to the epoch bits of the
1179   // prototype header. (Note that the prototype header's epoch bits
1180   // only change at a safepoint.) If not, attempt to rebias the object
1181   // toward the current thread. Note that we must be absolutely sure
1182   // that the current epoch is invalid in order to do this because
1183   // otherwise the manipulations it performs on the mark word are
1184   // illegal.
1185   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1186   jccb(Assembler::notZero, try_rebias);
1187 
1188   // The epoch of the current bias is still valid but we know nothing
1189   // about the owner; it might be set or it might be clear. Try to
1190   // acquire the bias of the object using an atomic operation. If this
1191   // fails we will go in to the runtime to revoke the object's bias.
1192   // Note that we first construct the presumed unbiased header so we
1193   // don't accidentally blow away another thread's valid bias.
1194   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1195   andptr(swap_reg,
1196          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1197 #ifdef _LP64
1198   movptr(tmp_reg, swap_reg);
1199   orptr(tmp_reg, r15_thread);
1200 #else
1201   get_thread(tmp_reg);
1202   orptr(tmp_reg, swap_reg);
1203 #endif
1204   if (os::is_MP()) {
1205     lock();
1206   }
1207   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1208   // If the biasing toward our thread failed, this means that
1209   // another thread succeeded in biasing it toward itself and we
1210   // need to revoke that bias. The revocation will occur in the
1211   // interpreter runtime in the slow case.
1212   if (counters != NULL) {
1213     cond_inc32(Assembler::zero,
1214                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1215   }
1216   if (slow_case != NULL) {
1217     jcc(Assembler::notZero, *slow_case);
1218   }
1219   jmp(done);
1220 
1221   bind(try_rebias);
1222   // At this point we know the epoch has expired, meaning that the
1223   // current "bias owner", if any, is actually invalid. Under these
1224   // circumstances _only_, we are allowed to use the current header's
1225   // value as the comparison value when doing the cas to acquire the
1226   // bias in the current epoch. In other words, we allow transfer of
1227   // the bias from one thread to another directly in this situation.
1228   //
1229   // FIXME: due to a lack of registers we currently blow away the age
1230   // bits in this situation. Should attempt to preserve them.
1231   load_prototype_header(tmp_reg, obj_reg);
1232 #ifdef _LP64
1233   orptr(tmp_reg, r15_thread);
1234 #else
1235   get_thread(swap_reg);
1236   orptr(tmp_reg, swap_reg);
1237   movptr(swap_reg, saved_mark_addr);
1238 #endif
1239   if (os::is_MP()) {
1240     lock();
1241   }
1242   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1243   // If the biasing toward our thread failed, then another thread
1244   // succeeded in biasing it toward itself and we need to revoke that
1245   // bias. The revocation will occur in the runtime in the slow case.
1246   if (counters != NULL) {
1247     cond_inc32(Assembler::zero,
1248                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1249   }
1250   if (slow_case != NULL) {
1251     jcc(Assembler::notZero, *slow_case);
1252   }
1253   jmp(done);
1254 
1255   bind(try_revoke_bias);
1256   // The prototype mark in the klass doesn't have the bias bit set any
1257   // more, indicating that objects of this data type are not supposed
1258   // to be biased any more. We are going to try to reset the mark of
1259   // this object to the prototype value and fall through to the
1260   // CAS-based locking scheme. Note that if our CAS fails, it means
1261   // that another thread raced us for the privilege of revoking the
1262   // bias of this particular object, so it's okay to continue in the
1263   // normal locking code.
1264   //
1265   // FIXME: due to a lack of registers we currently blow away the age
1266   // bits in this situation. Should attempt to preserve them.
1267   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1268   load_prototype_header(tmp_reg, obj_reg);
1269   if (os::is_MP()) {
1270     lock();
1271   }
1272   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1273   // Fall through to the normal CAS-based lock, because no matter what
1274   // the result of the above CAS, some thread must have succeeded in
1275   // removing the bias bit from the object's header.
1276   if (counters != NULL) {
1277     cond_inc32(Assembler::zero,
1278                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1279   }
1280 
1281   bind(cas_label);
1282 
1283   return null_check_offset;
1284 }
1285 
1286 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1287   assert(UseBiasedLocking, "why call this otherwise?");
1288 
1289   // Check for biased locking unlock case, which is a no-op
1290   // Note: we do not have to check the thread ID for two reasons.
1291   // First, the interpreter checks for IllegalMonitorStateException at
1292   // a higher level. Second, if the bias was revoked while we held the
1293   // lock, the object could not be rebiased toward another thread, so
1294   // the bias bit would be clear.
1295   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1296   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1297   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1298   jcc(Assembler::equal, done);
1299 }
1300 
1301 #ifdef COMPILER2
1302 
1303 #if INCLUDE_RTM_OPT
1304 
1305 // Update rtm_counters based on abort status
1306 // input: abort_status
1307 //        rtm_counters (RTMLockingCounters*)
1308 // flags are killed
1309 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1310 
1311   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1312   if (PrintPreciseRTMLockingStatistics) {
1313     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1314       Label check_abort;
1315       testl(abort_status, (1<<i));
1316       jccb(Assembler::equal, check_abort);
1317       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1318       bind(check_abort);
1319     }
1320   }
1321 }
1322 
1323 // Branch if (random & (count-1) != 0), count is 2^n
1324 // tmp, scr and flags are killed
1325 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1326   assert(tmp == rax, "");
1327   assert(scr == rdx, "");
1328   rdtsc(); // modifies EDX:EAX
1329   andptr(tmp, count-1);
1330   jccb(Assembler::notZero, brLabel);
1331 }
1332 
1333 // Perform abort ratio calculation, set no_rtm bit if high ratio
1334 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1335 // tmpReg, rtm_counters_Reg and flags are killed
1336 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1337                                                  Register rtm_counters_Reg,
1338                                                  RTMLockingCounters* rtm_counters,
1339                                                  Metadata* method_data) {
1340   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1341 
1342   if (RTMLockingCalculationDelay > 0) {
1343     // Delay calculation
1344     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1345     testptr(tmpReg, tmpReg);
1346     jccb(Assembler::equal, L_done);
1347   }
1348   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1349   //   Aborted transactions = abort_count * 100
1350   //   All transactions = total_count *  RTMTotalCountIncrRate
1351   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1352 
1353   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1354   cmpptr(tmpReg, RTMAbortThreshold);
1355   jccb(Assembler::below, L_check_always_rtm2);
1356   imulptr(tmpReg, tmpReg, 100);
1357 
1358   Register scrReg = rtm_counters_Reg;
1359   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1360   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1361   imulptr(scrReg, scrReg, RTMAbortRatio);
1362   cmpptr(tmpReg, scrReg);
1363   jccb(Assembler::below, L_check_always_rtm1);
1364   if (method_data != NULL) {
1365     // set rtm_state to "no rtm" in MDO
1366     mov_metadata(tmpReg, method_data);
1367     if (os::is_MP()) {
1368       lock();
1369     }
1370     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1371   }
1372   jmpb(L_done);
1373   bind(L_check_always_rtm1);
1374   // Reload RTMLockingCounters* address
1375   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1376   bind(L_check_always_rtm2);
1377   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1378   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1379   jccb(Assembler::below, L_done);
1380   if (method_data != NULL) {
1381     // set rtm_state to "always rtm" in MDO
1382     mov_metadata(tmpReg, method_data);
1383     if (os::is_MP()) {
1384       lock();
1385     }
1386     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1387   }
1388   bind(L_done);
1389 }
1390 
1391 // Update counters and perform abort ratio calculation
1392 // input:  abort_status_Reg
1393 // rtm_counters_Reg, flags are killed
1394 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1395                                    Register rtm_counters_Reg,
1396                                    RTMLockingCounters* rtm_counters,
1397                                    Metadata* method_data,
1398                                    bool profile_rtm) {
1399 
1400   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1401   // update rtm counters based on rax value at abort
1402   // reads abort_status_Reg, updates flags
1403   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1404   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1405   if (profile_rtm) {
1406     // Save abort status because abort_status_Reg is used by following code.
1407     if (RTMRetryCount > 0) {
1408       push(abort_status_Reg);
1409     }
1410     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1411     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1412     // restore abort status
1413     if (RTMRetryCount > 0) {
1414       pop(abort_status_Reg);
1415     }
1416   }
1417 }
1418 
1419 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1420 // inputs: retry_count_Reg
1421 //       : abort_status_Reg
1422 // output: retry_count_Reg decremented by 1
1423 // flags are killed
1424 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1425   Label doneRetry;
1426   assert(abort_status_Reg == rax, "");
1427   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1428   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1429   // if reason is in 0x6 and retry count != 0 then retry
1430   andptr(abort_status_Reg, 0x6);
1431   jccb(Assembler::zero, doneRetry);
1432   testl(retry_count_Reg, retry_count_Reg);
1433   jccb(Assembler::zero, doneRetry);
1434   pause();
1435   decrementl(retry_count_Reg);
1436   jmp(retryLabel);
1437   bind(doneRetry);
1438 }
1439 
1440 // Spin and retry if lock is busy,
1441 // inputs: box_Reg (monitor address)
1442 //       : retry_count_Reg
1443 // output: retry_count_Reg decremented by 1
1444 //       : clear z flag if retry count exceeded
1445 // tmp_Reg, scr_Reg, flags are killed
1446 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1447                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1448   Label SpinLoop, SpinExit, doneRetry;
1449   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1450 
1451   testl(retry_count_Reg, retry_count_Reg);
1452   jccb(Assembler::zero, doneRetry);
1453   decrementl(retry_count_Reg);
1454   movptr(scr_Reg, RTMSpinLoopCount);
1455 
1456   bind(SpinLoop);
1457   pause();
1458   decrementl(scr_Reg);
1459   jccb(Assembler::lessEqual, SpinExit);
1460   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1461   testptr(tmp_Reg, tmp_Reg);
1462   jccb(Assembler::notZero, SpinLoop);
1463 
1464   bind(SpinExit);
1465   jmp(retryLabel);
1466   bind(doneRetry);
1467   incrementl(retry_count_Reg); // clear z flag
1468 }
1469 
1470 // Use RTM for normal stack locks
1471 // Input: objReg (object to lock)
1472 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1473                                        Register retry_on_abort_count_Reg,
1474                                        RTMLockingCounters* stack_rtm_counters,
1475                                        Metadata* method_data, bool profile_rtm,
1476                                        Label& DONE_LABEL, Label& IsInflated) {
1477   assert(UseRTMForStackLocks, "why call this otherwise?");
1478   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1479   assert(tmpReg == rax, "");
1480   assert(scrReg == rdx, "");
1481   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1482 
1483   if (RTMRetryCount > 0) {
1484     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1485     bind(L_rtm_retry);
1486   }
1487   movptr(tmpReg, Address(objReg, 0));
1488   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1489   jcc(Assembler::notZero, IsInflated);
1490 
1491   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1492     Label L_noincrement;
1493     if (RTMTotalCountIncrRate > 1) {
1494       // tmpReg, scrReg and flags are killed
1495       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1496     }
1497     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1498     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1499     bind(L_noincrement);
1500   }
1501   xbegin(L_on_abort);
1502   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1503   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1504   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1505   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1506 
1507   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1508   if (UseRTMXendForLockBusy) {
1509     xend();
1510     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1511     jmp(L_decrement_retry);
1512   }
1513   else {
1514     xabort(0);
1515   }
1516   bind(L_on_abort);
1517   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1518     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1519   }
1520   bind(L_decrement_retry);
1521   if (RTMRetryCount > 0) {
1522     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1523     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1524   }
1525 }
1526 
1527 // Use RTM for inflating locks
1528 // inputs: objReg (object to lock)
1529 //         boxReg (on-stack box address (displaced header location) - KILLED)
1530 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1531 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1532                                           Register scrReg, Register retry_on_busy_count_Reg,
1533                                           Register retry_on_abort_count_Reg,
1534                                           RTMLockingCounters* rtm_counters,
1535                                           Metadata* method_data, bool profile_rtm,
1536                                           Label& DONE_LABEL) {
1537   assert(UseRTMLocking, "why call this otherwise?");
1538   assert(tmpReg == rax, "");
1539   assert(scrReg == rdx, "");
1540   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1541   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1542 
1543   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1544   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1545   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1546 
1547   if (RTMRetryCount > 0) {
1548     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1549     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1550     bind(L_rtm_retry);
1551   }
1552   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1553     Label L_noincrement;
1554     if (RTMTotalCountIncrRate > 1) {
1555       // tmpReg, scrReg and flags are killed
1556       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1557     }
1558     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1559     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1560     bind(L_noincrement);
1561   }
1562   xbegin(L_on_abort);
1563   movptr(tmpReg, Address(objReg, 0));
1564   movptr(tmpReg, Address(tmpReg, owner_offset));
1565   testptr(tmpReg, tmpReg);
1566   jcc(Assembler::zero, DONE_LABEL);
1567   if (UseRTMXendForLockBusy) {
1568     xend();
1569     jmp(L_decrement_retry);
1570   }
1571   else {
1572     xabort(0);
1573   }
1574   bind(L_on_abort);
1575   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1576   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1577     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1578   }
1579   if (RTMRetryCount > 0) {
1580     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1581     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1582   }
1583 
1584   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1585   testptr(tmpReg, tmpReg) ;
1586   jccb(Assembler::notZero, L_decrement_retry) ;
1587 
1588   // Appears unlocked - try to swing _owner from null to non-null.
1589   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1590 #ifdef _LP64
1591   Register threadReg = r15_thread;
1592 #else
1593   get_thread(scrReg);
1594   Register threadReg = scrReg;
1595 #endif
1596   if (os::is_MP()) {
1597     lock();
1598   }
1599   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1600 
1601   if (RTMRetryCount > 0) {
1602     // success done else retry
1603     jccb(Assembler::equal, DONE_LABEL) ;
1604     bind(L_decrement_retry);
1605     // Spin and retry if lock is busy.
1606     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1607   }
1608   else {
1609     bind(L_decrement_retry);
1610   }
1611 }
1612 
1613 #endif //  INCLUDE_RTM_OPT
1614 
1615 // Fast_Lock and Fast_Unlock used by C2
1616 
1617 // Because the transitions from emitted code to the runtime
1618 // monitorenter/exit helper stubs are so slow it's critical that
1619 // we inline both the stack-locking fast-path and the inflated fast path.
1620 //
1621 // See also: cmpFastLock and cmpFastUnlock.
1622 //
1623 // What follows is a specialized inline transliteration of the code
1624 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1625 // another option would be to emit TrySlowEnter and TrySlowExit methods
1626 // at startup-time.  These methods would accept arguments as
1627 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1628 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1629 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1630 // In practice, however, the # of lock sites is bounded and is usually small.
1631 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1632 // if the processor uses simple bimodal branch predictors keyed by EIP
1633 // Since the helper routines would be called from multiple synchronization
1634 // sites.
1635 //
1636 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1637 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1638 // to those specialized methods.  That'd give us a mostly platform-independent
1639 // implementation that the JITs could optimize and inline at their pleasure.
1640 // Done correctly, the only time we'd need to cross to native could would be
1641 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1642 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1643 // (b) explicit barriers or fence operations.
1644 //
1645 // TODO:
1646 //
1647 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1648 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1649 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1650 //    the lock operators would typically be faster than reifying Self.
1651 //
1652 // *  Ideally I'd define the primitives as:
1653 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1654 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1655 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1656 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1657 //    Furthermore the register assignments are overconstrained, possibly resulting in
1658 //    sub-optimal code near the synchronization site.
1659 //
1660 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1661 //    Alternately, use a better sp-proximity test.
1662 //
1663 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1664 //    Either one is sufficient to uniquely identify a thread.
1665 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1666 //
1667 // *  Intrinsify notify() and notifyAll() for the common cases where the
1668 //    object is locked by the calling thread but the waitlist is empty.
1669 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1670 //
1671 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1672 //    But beware of excessive branch density on AMD Opterons.
1673 //
1674 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1675 //    or failure of the fast-path.  If the fast-path fails then we pass
1676 //    control to the slow-path, typically in C.  In Fast_Lock and
1677 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1678 //    will emit a conditional branch immediately after the node.
1679 //    So we have branches to branches and lots of ICC.ZF games.
1680 //    Instead, it might be better to have C2 pass a "FailureLabel"
1681 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1682 //    will drop through the node.  ICC.ZF is undefined at exit.
1683 //    In the case of failure, the node will branch directly to the
1684 //    FailureLabel
1685 
1686 
1687 // obj: object to lock
1688 // box: on-stack box address (displaced header location) - KILLED
1689 // rax,: tmp -- KILLED
1690 // scr: tmp -- KILLED
1691 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1692                                Register scrReg, Register cx1Reg, Register cx2Reg,
1693                                BiasedLockingCounters* counters,
1694                                RTMLockingCounters* rtm_counters,
1695                                RTMLockingCounters* stack_rtm_counters,
1696                                Metadata* method_data,
1697                                bool use_rtm, bool profile_rtm) {
1698   // Ensure the register assignents are disjoint
1699   assert(tmpReg == rax, "");
1700 
1701   if (use_rtm) {
1702     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1703   } else {
1704     assert(cx1Reg == noreg, "");
1705     assert(cx2Reg == noreg, "");
1706     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1707   }
1708 
1709   if (counters != NULL) {
1710     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1711   }
1712   if (EmitSync & 1) {
1713       // set box->dhw = markOopDesc::unused_mark()
1714       // Force all sync thru slow-path: slow_enter() and slow_exit()
1715       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1716       cmpptr (rsp, (int32_t)NULL_WORD);
1717   } else {
1718     // Possible cases that we'll encounter in fast_lock
1719     // ------------------------------------------------
1720     // * Inflated
1721     //    -- unlocked
1722     //    -- Locked
1723     //       = by self
1724     //       = by other
1725     // * biased
1726     //    -- by Self
1727     //    -- by other
1728     // * neutral
1729     // * stack-locked
1730     //    -- by self
1731     //       = sp-proximity test hits
1732     //       = sp-proximity test generates false-negative
1733     //    -- by other
1734     //
1735 
1736     Label IsInflated, DONE_LABEL;
1737 
1738     // it's stack-locked, biased or neutral
1739     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1740     // order to reduce the number of conditional branches in the most common cases.
1741     // Beware -- there's a subtle invariant that fetch of the markword
1742     // at [FETCH], below, will never observe a biased encoding (*101b).
1743     // If this invariant is not held we risk exclusion (safety) failure.
1744     if (UseBiasedLocking && !UseOptoBiasInlining) {
1745       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1746     }
1747 
1748 #if INCLUDE_RTM_OPT
1749     if (UseRTMForStackLocks && use_rtm) {
1750       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1751                         stack_rtm_counters, method_data, profile_rtm,
1752                         DONE_LABEL, IsInflated);
1753     }
1754 #endif // INCLUDE_RTM_OPT
1755 
1756     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1757     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1758     jccb(Assembler::notZero, IsInflated);
1759 
1760     // Attempt stack-locking ...
1761     orptr (tmpReg, markOopDesc::unlocked_value);
1762     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1763     if (os::is_MP()) {
1764       lock();
1765     }
1766     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1767     if (counters != NULL) {
1768       cond_inc32(Assembler::equal,
1769                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1770     }
1771     jcc(Assembler::equal, DONE_LABEL);           // Success
1772 
1773     // Recursive locking.
1774     // The object is stack-locked: markword contains stack pointer to BasicLock.
1775     // Locked by current thread if difference with current SP is less than one page.
1776     subptr(tmpReg, rsp);
1777     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1778     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1779     movptr(Address(boxReg, 0), tmpReg);
1780     if (counters != NULL) {
1781       cond_inc32(Assembler::equal,
1782                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1783     }
1784     jmp(DONE_LABEL);
1785 
1786     bind(IsInflated);
1787     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1788 
1789 #if INCLUDE_RTM_OPT
1790     // Use the same RTM locking code in 32- and 64-bit VM.
1791     if (use_rtm) {
1792       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1793                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1794     } else {
1795 #endif // INCLUDE_RTM_OPT
1796 
1797 #ifndef _LP64
1798     // The object is inflated.
1799 
1800     // boxReg refers to the on-stack BasicLock in the current frame.
1801     // We'd like to write:
1802     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1803     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1804     // additional latency as we have another ST in the store buffer that must drain.
1805 
1806     if (EmitSync & 8192) {
1807        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1808        get_thread (scrReg);
1809        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1810        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1811        if (os::is_MP()) {
1812          lock();
1813        }
1814        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1815     } else
1816     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1817        // register juggle because we need tmpReg for cmpxchgptr below
1818        movptr(scrReg, boxReg);
1819        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1820 
1821        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1822        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1823           // prefetchw [eax + Offset(_owner)-2]
1824           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1825        }
1826 
1827        if ((EmitSync & 64) == 0) {
1828          // Optimistic form: consider XORL tmpReg,tmpReg
1829          movptr(tmpReg, NULL_WORD);
1830        } else {
1831          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1832          // Test-And-CAS instead of CAS
1833          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1834          testptr(tmpReg, tmpReg);                   // Locked ?
1835          jccb  (Assembler::notZero, DONE_LABEL);
1836        }
1837 
1838        // Appears unlocked - try to swing _owner from null to non-null.
1839        // Ideally, I'd manifest "Self" with get_thread and then attempt
1840        // to CAS the register containing Self into m->Owner.
1841        // But we don't have enough registers, so instead we can either try to CAS
1842        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1843        // we later store "Self" into m->Owner.  Transiently storing a stack address
1844        // (rsp or the address of the box) into  m->owner is harmless.
1845        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1846        if (os::is_MP()) {
1847          lock();
1848        }
1849        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1850        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1851        // If we weren't able to swing _owner from NULL to the BasicLock
1852        // then take the slow path.
1853        jccb  (Assembler::notZero, DONE_LABEL);
1854        // update _owner from BasicLock to thread
1855        get_thread (scrReg);                    // beware: clobbers ICCs
1856        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1857        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1858 
1859        // If the CAS fails we can either retry or pass control to the slow-path.
1860        // We use the latter tactic.
1861        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1862        // If the CAS was successful ...
1863        //   Self has acquired the lock
1864        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1865        // Intentional fall-through into DONE_LABEL ...
1866     } else {
1867        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1868        movptr(boxReg, tmpReg);
1869 
1870        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1871        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1872           // prefetchw [eax + Offset(_owner)-2]
1873           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1874        }
1875 
1876        if ((EmitSync & 64) == 0) {
1877          // Optimistic form
1878          xorptr  (tmpReg, tmpReg);
1879        } else {
1880          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1881          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1882          testptr(tmpReg, tmpReg);                   // Locked ?
1883          jccb  (Assembler::notZero, DONE_LABEL);
1884        }
1885 
1886        // Appears unlocked - try to swing _owner from null to non-null.
1887        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1888        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1889        get_thread (scrReg);
1890        if (os::is_MP()) {
1891          lock();
1892        }
1893        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1894 
1895        // If the CAS fails we can either retry or pass control to the slow-path.
1896        // We use the latter tactic.
1897        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1898        // If the CAS was successful ...
1899        //   Self has acquired the lock
1900        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1901        // Intentional fall-through into DONE_LABEL ...
1902     }
1903 #else // _LP64
1904     // It's inflated
1905     movq(scrReg, tmpReg);
1906     xorq(tmpReg, tmpReg);
1907 
1908     if (os::is_MP()) {
1909       lock();
1910     }
1911     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1912     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1913     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1914     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1915     // Intentional fall-through into DONE_LABEL ...
1916     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1917 #endif // _LP64
1918 #if INCLUDE_RTM_OPT
1919     } // use_rtm()
1920 #endif
1921     // DONE_LABEL is a hot target - we'd really like to place it at the
1922     // start of cache line by padding with NOPs.
1923     // See the AMD and Intel software optimization manuals for the
1924     // most efficient "long" NOP encodings.
1925     // Unfortunately none of our alignment mechanisms suffice.
1926     bind(DONE_LABEL);
1927 
1928     // At DONE_LABEL the icc ZFlag is set as follows ...
1929     // Fast_Unlock uses the same protocol.
1930     // ZFlag == 1 -> Success
1931     // ZFlag == 0 -> Failure - force control through the slow-path
1932   }
1933 }
1934 
1935 // obj: object to unlock
1936 // box: box address (displaced header location), killed.  Must be EAX.
1937 // tmp: killed, cannot be obj nor box.
1938 //
1939 // Some commentary on balanced locking:
1940 //
1941 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1942 // Methods that don't have provably balanced locking are forced to run in the
1943 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1944 // The interpreter provides two properties:
1945 // I1:  At return-time the interpreter automatically and quietly unlocks any
1946 //      objects acquired the current activation (frame).  Recall that the
1947 //      interpreter maintains an on-stack list of locks currently held by
1948 //      a frame.
1949 // I2:  If a method attempts to unlock an object that is not held by the
1950 //      the frame the interpreter throws IMSX.
1951 //
1952 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1953 // B() doesn't have provably balanced locking so it runs in the interpreter.
1954 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1955 // is still locked by A().
1956 //
1957 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1958 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1959 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1960 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1961 // Arguably given that the spec legislates the JNI case as undefined our implementation
1962 // could reasonably *avoid* checking owner in Fast_Unlock().
1963 // In the interest of performance we elide m->Owner==Self check in unlock.
1964 // A perfectly viable alternative is to elide the owner check except when
1965 // Xcheck:jni is enabled.
1966 
1967 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1968   assert(boxReg == rax, "");
1969   assert_different_registers(objReg, boxReg, tmpReg);
1970 
1971   if (EmitSync & 4) {
1972     // Disable - inhibit all inlining.  Force control through the slow-path
1973     cmpptr (rsp, 0);
1974   } else {
1975     Label DONE_LABEL, Stacked, CheckSucc;
1976 
1977     // Critically, the biased locking test must have precedence over
1978     // and appear before the (box->dhw == 0) recursive stack-lock test.
1979     if (UseBiasedLocking && !UseOptoBiasInlining) {
1980        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1981     }
1982 
1983 #if INCLUDE_RTM_OPT
1984     if (UseRTMForStackLocks && use_rtm) {
1985       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1986       Label L_regular_unlock;
1987       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1988       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1989       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1990       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1991       xend();                                       // otherwise end...
1992       jmp(DONE_LABEL);                              // ... and we're done
1993       bind(L_regular_unlock);
1994     }
1995 #endif
1996 
1997     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1998     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1999     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
2000     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2001     jccb  (Assembler::zero, Stacked);
2002 
2003     // It's inflated.
2004 #if INCLUDE_RTM_OPT
2005     if (use_rtm) {
2006       Label L_regular_inflated_unlock;
2007       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2008       movptr(boxReg, Address(tmpReg, owner_offset));
2009       testptr(boxReg, boxReg);
2010       jccb(Assembler::notZero, L_regular_inflated_unlock);
2011       xend();
2012       jmpb(DONE_LABEL);
2013       bind(L_regular_inflated_unlock);
2014     }
2015 #endif
2016 
2017     // Despite our balanced locking property we still check that m->_owner == Self
2018     // as java routines or native JNI code called by this thread might
2019     // have released the lock.
2020     // Refer to the comments in synchronizer.cpp for how we might encode extra
2021     // state in _succ so we can avoid fetching EntryList|cxq.
2022     //
2023     // I'd like to add more cases in fast_lock() and fast_unlock() --
2024     // such as recursive enter and exit -- but we have to be wary of
2025     // I$ bloat, T$ effects and BP$ effects.
2026     //
2027     // If there's no contention try a 1-0 exit.  That is, exit without
2028     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2029     // we detect and recover from the race that the 1-0 exit admits.
2030     //
2031     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2032     // before it STs null into _owner, releasing the lock.  Updates
2033     // to data protected by the critical section must be visible before
2034     // we drop the lock (and thus before any other thread could acquire
2035     // the lock and observe the fields protected by the lock).
2036     // IA32's memory-model is SPO, so STs are ordered with respect to
2037     // each other and there's no need for an explicit barrier (fence).
2038     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2039 #ifndef _LP64
2040     get_thread (boxReg);
2041     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2042       // prefetchw [ebx + Offset(_owner)-2]
2043       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2044     }
2045 
2046     // Note that we could employ various encoding schemes to reduce
2047     // the number of loads below (currently 4) to just 2 or 3.
2048     // Refer to the comments in synchronizer.cpp.
2049     // In practice the chain of fetches doesn't seem to impact performance, however.
2050     xorptr(boxReg, boxReg);
2051     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2052        // Attempt to reduce branch density - AMD's branch predictor.
2053        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2054        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2056        jccb  (Assembler::notZero, DONE_LABEL);
2057        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2058        jmpb  (DONE_LABEL);
2059     } else {
2060        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2061        jccb  (Assembler::notZero, DONE_LABEL);
2062        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2064        jccb  (Assembler::notZero, CheckSucc);
2065        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2066        jmpb  (DONE_LABEL);
2067     }
2068 
2069     // The Following code fragment (EmitSync & 65536) improves the performance of
2070     // contended applications and contended synchronization microbenchmarks.
2071     // Unfortunately the emission of the code - even though not executed - causes regressions
2072     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2073     // with an equal number of never-executed NOPs results in the same regression.
2074     // We leave it off by default.
2075 
2076     if ((EmitSync & 65536) != 0) {
2077        Label LSuccess, LGoSlowPath ;
2078 
2079        bind  (CheckSucc);
2080 
2081        // Optional pre-test ... it's safe to elide this
2082        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2083        jccb(Assembler::zero, LGoSlowPath);
2084 
2085        // We have a classic Dekker-style idiom:
2086        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2087        // There are a number of ways to implement the barrier:
2088        // (1) lock:andl &m->_owner, 0
2089        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2090        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2091        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2092        // (2) If supported, an explicit MFENCE is appealing.
2093        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2094        //     particularly if the write-buffer is full as might be the case if
2095        //     if stores closely precede the fence or fence-equivalent instruction.
2096        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2097        //     as the situation has changed with Nehalem and Shanghai.
2098        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2099        //     The $lines underlying the top-of-stack should be in M-state.
2100        //     The locked add instruction is serializing, of course.
2101        // (4) Use xchg, which is serializing
2102        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2103        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2104        //     The integer condition codes will tell us if succ was 0.
2105        //     Since _succ and _owner should reside in the same $line and
2106        //     we just stored into _owner, it's likely that the $line
2107        //     remains in M-state for the lock:orl.
2108        //
2109        // We currently use (3), although it's likely that switching to (2)
2110        // is correct for the future.
2111 
2112        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2113        if (os::is_MP()) {
2114          lock(); addptr(Address(rsp, 0), 0);
2115        }
2116        // Ratify _succ remains non-null
2117        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2118        jccb  (Assembler::notZero, LSuccess);
2119 
2120        xorptr(boxReg, boxReg);                  // box is really EAX
2121        if (os::is_MP()) { lock(); }
2122        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2123        // There's no successor so we tried to regrab the lock with the
2124        // placeholder value. If that didn't work, then another thread
2125        // grabbed the lock so we're done (and exit was a success).
2126        jccb  (Assembler::notEqual, LSuccess);
2127        // Since we're low on registers we installed rsp as a placeholding in _owner.
2128        // Now install Self over rsp.  This is safe as we're transitioning from
2129        // non-null to non=null
2130        get_thread (boxReg);
2131        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2132        // Intentional fall-through into LGoSlowPath ...
2133 
2134        bind  (LGoSlowPath);
2135        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2136        jmpb  (DONE_LABEL);
2137 
2138        bind  (LSuccess);
2139        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2140        jmpb  (DONE_LABEL);
2141     }
2142 
2143     bind (Stacked);
2144     // It's not inflated and it's not recursively stack-locked and it's not biased.
2145     // It must be stack-locked.
2146     // Try to reset the header to displaced header.
2147     // The "box" value on the stack is stable, so we can reload
2148     // and be assured we observe the same value as above.
2149     movptr(tmpReg, Address(boxReg, 0));
2150     if (os::is_MP()) {
2151       lock();
2152     }
2153     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2154     // Intention fall-thru into DONE_LABEL
2155 
2156     // DONE_LABEL is a hot target - we'd really like to place it at the
2157     // start of cache line by padding with NOPs.
2158     // See the AMD and Intel software optimization manuals for the
2159     // most efficient "long" NOP encodings.
2160     // Unfortunately none of our alignment mechanisms suffice.
2161     if ((EmitSync & 65536) == 0) {
2162        bind (CheckSucc);
2163     }
2164 #else // _LP64
2165     // It's inflated
2166     if (EmitSync & 1024) {
2167       // Emit code to check that _owner == Self
2168       // We could fold the _owner test into subsequent code more efficiently
2169       // than using a stand-alone check, but since _owner checking is off by
2170       // default we don't bother. We also might consider predicating the
2171       // _owner==Self check on Xcheck:jni or running on a debug build.
2172       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2173       xorptr(boxReg, r15_thread);
2174     } else {
2175       xorptr(boxReg, boxReg);
2176     }
2177     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2178     jccb  (Assembler::notZero, DONE_LABEL);
2179     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2180     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2181     jccb  (Assembler::notZero, CheckSucc);
2182     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2183     jmpb  (DONE_LABEL);
2184 
2185     if ((EmitSync & 65536) == 0) {
2186       // Try to avoid passing control into the slow_path ...
2187       Label LSuccess, LGoSlowPath ;
2188       bind  (CheckSucc);
2189 
2190       // The following optional optimization can be elided if necessary
2191       // Effectively: if (succ == null) goto SlowPath
2192       // The code reduces the window for a race, however,
2193       // and thus benefits performance.
2194       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2195       jccb  (Assembler::zero, LGoSlowPath);
2196 
2197       if ((EmitSync & 16) && os::is_MP()) {
2198         orptr(boxReg, boxReg);
2199         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2200       } else {
2201         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2202         if (os::is_MP()) {
2203           // Memory barrier/fence
2204           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2205           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2206           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2207           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2208           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2209           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2210           lock(); addl(Address(rsp, 0), 0);
2211         }
2212       }
2213       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2214       jccb  (Assembler::notZero, LSuccess);
2215 
2216       // Rare inopportune interleaving - race.
2217       // The successor vanished in the small window above.
2218       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2219       // We need to ensure progress and succession.
2220       // Try to reacquire the lock.
2221       // If that fails then the new owner is responsible for succession and this
2222       // thread needs to take no further action and can exit via the fast path (success).
2223       // If the re-acquire succeeds then pass control into the slow path.
2224       // As implemented, this latter mode is horrible because we generated more
2225       // coherence traffic on the lock *and* artifically extended the critical section
2226       // length while by virtue of passing control into the slow path.
2227 
2228       // box is really RAX -- the following CMPXCHG depends on that binding
2229       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2230       movptr(boxReg, (int32_t)NULL_WORD);
2231       if (os::is_MP()) { lock(); }
2232       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2233       // There's no successor so we tried to regrab the lock.
2234       // If that didn't work, then another thread grabbed the
2235       // lock so we're done (and exit was a success).
2236       jccb  (Assembler::notEqual, LSuccess);
2237       // Intentional fall-through into slow-path
2238 
2239       bind  (LGoSlowPath);
2240       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2241       jmpb  (DONE_LABEL);
2242 
2243       bind  (LSuccess);
2244       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2245       jmpb  (DONE_LABEL);
2246     }
2247 
2248     bind  (Stacked);
2249     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2250     if (os::is_MP()) { lock(); }
2251     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2252 
2253     if (EmitSync & 65536) {
2254        bind (CheckSucc);
2255     }
2256 #endif
2257     bind(DONE_LABEL);
2258   }
2259 }
2260 #endif // COMPILER2
2261 
2262 void MacroAssembler::c2bool(Register x) {
2263   // implements x == 0 ? 0 : 1
2264   // note: must only look at least-significant byte of x
2265   //       since C-style booleans are stored in one byte
2266   //       only! (was bug)
2267   andl(x, 0xFF);
2268   setb(Assembler::notZero, x);
2269 }
2270 
2271 // Wouldn't need if AddressLiteral version had new name
2272 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2273   Assembler::call(L, rtype);
2274 }
2275 
2276 void MacroAssembler::call(Register entry) {
2277   Assembler::call(entry);
2278 }
2279 
2280 void MacroAssembler::call(AddressLiteral entry) {
2281   if (reachable(entry)) {
2282     Assembler::call_literal(entry.target(), entry.rspec());
2283   } else {
2284     lea(rscratch1, entry);
2285     Assembler::call(rscratch1);
2286   }
2287 }
2288 
2289 void MacroAssembler::ic_call(address entry, jint method_index) {
2290   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2291   movptr(rax, (intptr_t)Universe::non_oop_word());
2292   call(AddressLiteral(entry, rh));
2293 }
2294 
2295 // Implementation of call_VM versions
2296 
2297 void MacroAssembler::call_VM(Register oop_result,
2298                              address entry_point,
2299                              bool check_exceptions) {
2300   Label C, E;
2301   call(C, relocInfo::none);
2302   jmp(E);
2303 
2304   bind(C);
2305   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2306   ret(0);
2307 
2308   bind(E);
2309 }
2310 
2311 void MacroAssembler::call_VM(Register oop_result,
2312                              address entry_point,
2313                              Register arg_1,
2314                              bool check_exceptions) {
2315   Label C, E;
2316   call(C, relocInfo::none);
2317   jmp(E);
2318 
2319   bind(C);
2320   pass_arg1(this, arg_1);
2321   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2322   ret(0);
2323 
2324   bind(E);
2325 }
2326 
2327 void MacroAssembler::call_VM(Register oop_result,
2328                              address entry_point,
2329                              Register arg_1,
2330                              Register arg_2,
2331                              bool check_exceptions) {
2332   Label C, E;
2333   call(C, relocInfo::none);
2334   jmp(E);
2335 
2336   bind(C);
2337 
2338   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2339 
2340   pass_arg2(this, arg_2);
2341   pass_arg1(this, arg_1);
2342   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2343   ret(0);
2344 
2345   bind(E);
2346 }
2347 
2348 void MacroAssembler::call_VM(Register oop_result,
2349                              address entry_point,
2350                              Register arg_1,
2351                              Register arg_2,
2352                              Register arg_3,
2353                              bool check_exceptions) {
2354   Label C, E;
2355   call(C, relocInfo::none);
2356   jmp(E);
2357 
2358   bind(C);
2359 
2360   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2361   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2362   pass_arg3(this, arg_3);
2363 
2364   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2365   pass_arg2(this, arg_2);
2366 
2367   pass_arg1(this, arg_1);
2368   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2369   ret(0);
2370 
2371   bind(E);
2372 }
2373 
2374 void MacroAssembler::call_VM(Register oop_result,
2375                              Register last_java_sp,
2376                              address entry_point,
2377                              int number_of_arguments,
2378                              bool check_exceptions) {
2379   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2380   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2381 }
2382 
2383 void MacroAssembler::call_VM(Register oop_result,
2384                              Register last_java_sp,
2385                              address entry_point,
2386                              Register arg_1,
2387                              bool check_exceptions) {
2388   pass_arg1(this, arg_1);
2389   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2390 }
2391 
2392 void MacroAssembler::call_VM(Register oop_result,
2393                              Register last_java_sp,
2394                              address entry_point,
2395                              Register arg_1,
2396                              Register arg_2,
2397                              bool check_exceptions) {
2398 
2399   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2400   pass_arg2(this, arg_2);
2401   pass_arg1(this, arg_1);
2402   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2403 }
2404 
2405 void MacroAssembler::call_VM(Register oop_result,
2406                              Register last_java_sp,
2407                              address entry_point,
2408                              Register arg_1,
2409                              Register arg_2,
2410                              Register arg_3,
2411                              bool check_exceptions) {
2412   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2413   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2414   pass_arg3(this, arg_3);
2415   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2416   pass_arg2(this, arg_2);
2417   pass_arg1(this, arg_1);
2418   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2419 }
2420 
2421 void MacroAssembler::super_call_VM(Register oop_result,
2422                                    Register last_java_sp,
2423                                    address entry_point,
2424                                    int number_of_arguments,
2425                                    bool check_exceptions) {
2426   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2427   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2428 }
2429 
2430 void MacroAssembler::super_call_VM(Register oop_result,
2431                                    Register last_java_sp,
2432                                    address entry_point,
2433                                    Register arg_1,
2434                                    bool check_exceptions) {
2435   pass_arg1(this, arg_1);
2436   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2437 }
2438 
2439 void MacroAssembler::super_call_VM(Register oop_result,
2440                                    Register last_java_sp,
2441                                    address entry_point,
2442                                    Register arg_1,
2443                                    Register arg_2,
2444                                    bool check_exceptions) {
2445 
2446   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2447   pass_arg2(this, arg_2);
2448   pass_arg1(this, arg_1);
2449   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2450 }
2451 
2452 void MacroAssembler::super_call_VM(Register oop_result,
2453                                    Register last_java_sp,
2454                                    address entry_point,
2455                                    Register arg_1,
2456                                    Register arg_2,
2457                                    Register arg_3,
2458                                    bool check_exceptions) {
2459   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2460   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2461   pass_arg3(this, arg_3);
2462   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2463   pass_arg2(this, arg_2);
2464   pass_arg1(this, arg_1);
2465   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2466 }
2467 
2468 void MacroAssembler::call_VM_base(Register oop_result,
2469                                   Register java_thread,
2470                                   Register last_java_sp,
2471                                   address  entry_point,
2472                                   int      number_of_arguments,
2473                                   bool     check_exceptions) {
2474   // determine java_thread register
2475   if (!java_thread->is_valid()) {
2476 #ifdef _LP64
2477     java_thread = r15_thread;
2478 #else
2479     java_thread = rdi;
2480     get_thread(java_thread);
2481 #endif // LP64
2482   }
2483   // determine last_java_sp register
2484   if (!last_java_sp->is_valid()) {
2485     last_java_sp = rsp;
2486   }
2487   // debugging support
2488   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2489   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2490 #ifdef ASSERT
2491   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2492   // r12 is the heapbase.
2493   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2494 #endif // ASSERT
2495 
2496   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2497   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2498 
2499   // push java thread (becomes first argument of C function)
2500 
2501   NOT_LP64(push(java_thread); number_of_arguments++);
2502   LP64_ONLY(mov(c_rarg0, r15_thread));
2503 
2504   // set last Java frame before call
2505   assert(last_java_sp != rbp, "can't use ebp/rbp");
2506 
2507   // Only interpreter should have to set fp
2508   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2509 
2510   // do the call, remove parameters
2511   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2512 
2513   // restore the thread (cannot use the pushed argument since arguments
2514   // may be overwritten by C code generated by an optimizing compiler);
2515   // however can use the register value directly if it is callee saved.
2516   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2517     // rdi & rsi (also r15) are callee saved -> nothing to do
2518 #ifdef ASSERT
2519     guarantee(java_thread != rax, "change this code");
2520     push(rax);
2521     { Label L;
2522       get_thread(rax);
2523       cmpptr(java_thread, rax);
2524       jcc(Assembler::equal, L);
2525       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2526       bind(L);
2527     }
2528     pop(rax);
2529 #endif
2530   } else {
2531     get_thread(java_thread);
2532   }
2533   // reset last Java frame
2534   // Only interpreter should have to clear fp
2535   reset_last_Java_frame(java_thread, true, false);
2536 
2537    // C++ interp handles this in the interpreter
2538   check_and_handle_popframe(java_thread);
2539   check_and_handle_earlyret(java_thread);
2540 
2541   if (check_exceptions) {
2542     // check for pending exceptions (java_thread is set upon return)
2543     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2544 #ifndef _LP64
2545     jump_cc(Assembler::notEqual,
2546             RuntimeAddress(StubRoutines::forward_exception_entry()));
2547 #else
2548     // This used to conditionally jump to forward_exception however it is
2549     // possible if we relocate that the branch will not reach. So we must jump
2550     // around so we can always reach
2551 
2552     Label ok;
2553     jcc(Assembler::equal, ok);
2554     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2555     bind(ok);
2556 #endif // LP64
2557   }
2558 
2559   // get oop result if there is one and reset the value in the thread
2560   if (oop_result->is_valid()) {
2561     get_vm_result(oop_result, java_thread);
2562   }
2563 }
2564 
2565 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2566 
2567   // Calculate the value for last_Java_sp
2568   // somewhat subtle. call_VM does an intermediate call
2569   // which places a return address on the stack just under the
2570   // stack pointer as the user finsihed with it. This allows
2571   // use to retrieve last_Java_pc from last_Java_sp[-1].
2572   // On 32bit we then have to push additional args on the stack to accomplish
2573   // the actual requested call. On 64bit call_VM only can use register args
2574   // so the only extra space is the return address that call_VM created.
2575   // This hopefully explains the calculations here.
2576 
2577 #ifdef _LP64
2578   // We've pushed one address, correct last_Java_sp
2579   lea(rax, Address(rsp, wordSize));
2580 #else
2581   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2582 #endif // LP64
2583 
2584   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2585 
2586 }
2587 
2588 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2589   call_VM_leaf_base(entry_point, number_of_arguments);
2590 }
2591 
2592 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2593   pass_arg0(this, arg_0);
2594   call_VM_leaf(entry_point, 1);
2595 }
2596 
2597 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2598 
2599   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2600   pass_arg1(this, arg_1);
2601   pass_arg0(this, arg_0);
2602   call_VM_leaf(entry_point, 2);
2603 }
2604 
2605 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2606   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2607   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2608   pass_arg2(this, arg_2);
2609   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2610   pass_arg1(this, arg_1);
2611   pass_arg0(this, arg_0);
2612   call_VM_leaf(entry_point, 3);
2613 }
2614 
2615 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2616   pass_arg0(this, arg_0);
2617   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2618 }
2619 
2620 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2621 
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, 2);
2626 }
2627 
2628 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2629   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2630   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2631   pass_arg2(this, arg_2);
2632   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2633   pass_arg1(this, arg_1);
2634   pass_arg0(this, arg_0);
2635   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2636 }
2637 
2638 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2639   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2640   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2641   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2642   pass_arg3(this, arg_3);
2643   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2644   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2645   pass_arg2(this, arg_2);
2646   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2647   pass_arg1(this, arg_1);
2648   pass_arg0(this, arg_0);
2649   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2650 }
2651 
2652 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2653   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2654   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2655   verify_oop(oop_result, "broken oop in call_VM_base");
2656 }
2657 
2658 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2659   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2660   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2661 }
2662 
2663 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2664 }
2665 
2666 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2667 }
2668 
2669 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2670   if (reachable(src1)) {
2671     cmpl(as_Address(src1), imm);
2672   } else {
2673     lea(rscratch1, src1);
2674     cmpl(Address(rscratch1, 0), imm);
2675   }
2676 }
2677 
2678 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2679   assert(!src2.is_lval(), "use cmpptr");
2680   if (reachable(src2)) {
2681     cmpl(src1, as_Address(src2));
2682   } else {
2683     lea(rscratch1, src2);
2684     cmpl(src1, Address(rscratch1, 0));
2685   }
2686 }
2687 
2688 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2689   Assembler::cmpl(src1, imm);
2690 }
2691 
2692 void MacroAssembler::cmp32(Register src1, Address src2) {
2693   Assembler::cmpl(src1, src2);
2694 }
2695 
2696 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2697   ucomisd(opr1, opr2);
2698 
2699   Label L;
2700   if (unordered_is_less) {
2701     movl(dst, -1);
2702     jcc(Assembler::parity, L);
2703     jcc(Assembler::below , L);
2704     movl(dst, 0);
2705     jcc(Assembler::equal , L);
2706     increment(dst);
2707   } else { // unordered is greater
2708     movl(dst, 1);
2709     jcc(Assembler::parity, L);
2710     jcc(Assembler::above , L);
2711     movl(dst, 0);
2712     jcc(Assembler::equal , L);
2713     decrementl(dst);
2714   }
2715   bind(L);
2716 }
2717 
2718 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2719   ucomiss(opr1, opr2);
2720 
2721   Label L;
2722   if (unordered_is_less) {
2723     movl(dst, -1);
2724     jcc(Assembler::parity, L);
2725     jcc(Assembler::below , L);
2726     movl(dst, 0);
2727     jcc(Assembler::equal , L);
2728     increment(dst);
2729   } else { // unordered is greater
2730     movl(dst, 1);
2731     jcc(Assembler::parity, L);
2732     jcc(Assembler::above , L);
2733     movl(dst, 0);
2734     jcc(Assembler::equal , L);
2735     decrementl(dst);
2736   }
2737   bind(L);
2738 }
2739 
2740 
2741 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2742   if (reachable(src1)) {
2743     cmpb(as_Address(src1), imm);
2744   } else {
2745     lea(rscratch1, src1);
2746     cmpb(Address(rscratch1, 0), imm);
2747   }
2748 }
2749 
2750 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2751 #ifdef _LP64
2752   if (src2.is_lval()) {
2753     movptr(rscratch1, src2);
2754     Assembler::cmpq(src1, rscratch1);
2755   } else if (reachable(src2)) {
2756     cmpq(src1, as_Address(src2));
2757   } else {
2758     lea(rscratch1, src2);
2759     Assembler::cmpq(src1, Address(rscratch1, 0));
2760   }
2761 #else
2762   if (src2.is_lval()) {
2763     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2764   } else {
2765     cmpl(src1, as_Address(src2));
2766   }
2767 #endif // _LP64
2768 }
2769 
2770 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2771   assert(src2.is_lval(), "not a mem-mem compare");
2772 #ifdef _LP64
2773   // moves src2's literal address
2774   movptr(rscratch1, src2);
2775   Assembler::cmpq(src1, rscratch1);
2776 #else
2777   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2778 #endif // _LP64
2779 }
2780 
2781 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2782   if (reachable(adr)) {
2783     if (os::is_MP())
2784       lock();
2785     cmpxchgptr(reg, as_Address(adr));
2786   } else {
2787     lea(rscratch1, adr);
2788     if (os::is_MP())
2789       lock();
2790     cmpxchgptr(reg, Address(rscratch1, 0));
2791   }
2792 }
2793 
2794 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2795   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2796 }
2797 
2798 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2799   if (reachable(src)) {
2800     Assembler::comisd(dst, as_Address(src));
2801   } else {
2802     lea(rscratch1, src);
2803     Assembler::comisd(dst, Address(rscratch1, 0));
2804   }
2805 }
2806 
2807 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2808   if (reachable(src)) {
2809     Assembler::comiss(dst, as_Address(src));
2810   } else {
2811     lea(rscratch1, src);
2812     Assembler::comiss(dst, Address(rscratch1, 0));
2813   }
2814 }
2815 
2816 
2817 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2818   Condition negated_cond = negate_condition(cond);
2819   Label L;
2820   jcc(negated_cond, L);
2821   pushf(); // Preserve flags
2822   atomic_incl(counter_addr);
2823   popf();
2824   bind(L);
2825 }
2826 
2827 int MacroAssembler::corrected_idivl(Register reg) {
2828   // Full implementation of Java idiv and irem; checks for
2829   // special case as described in JVM spec., p.243 & p.271.
2830   // The function returns the (pc) offset of the idivl
2831   // instruction - may be needed for implicit exceptions.
2832   //
2833   //         normal case                           special case
2834   //
2835   // input : rax,: dividend                         min_int
2836   //         reg: divisor   (may not be rax,/rdx)   -1
2837   //
2838   // output: rax,: quotient  (= rax, idiv reg)       min_int
2839   //         rdx: remainder (= rax, irem reg)       0
2840   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2841   const int min_int = 0x80000000;
2842   Label normal_case, special_case;
2843 
2844   // check for special case
2845   cmpl(rax, min_int);
2846   jcc(Assembler::notEqual, normal_case);
2847   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2848   cmpl(reg, -1);
2849   jcc(Assembler::equal, special_case);
2850 
2851   // handle normal case
2852   bind(normal_case);
2853   cdql();
2854   int idivl_offset = offset();
2855   idivl(reg);
2856 
2857   // normal and special case exit
2858   bind(special_case);
2859 
2860   return idivl_offset;
2861 }
2862 
2863 
2864 
2865 void MacroAssembler::decrementl(Register reg, int value) {
2866   if (value == min_jint) {subl(reg, value) ; return; }
2867   if (value <  0) { incrementl(reg, -value); return; }
2868   if (value == 0) {                        ; return; }
2869   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2870   /* else */      { subl(reg, value)       ; return; }
2871 }
2872 
2873 void MacroAssembler::decrementl(Address dst, int value) {
2874   if (value == min_jint) {subl(dst, value) ; return; }
2875   if (value <  0) { incrementl(dst, -value); return; }
2876   if (value == 0) {                        ; return; }
2877   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2878   /* else */      { subl(dst, value)       ; return; }
2879 }
2880 
2881 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2882   assert (shift_value > 0, "illegal shift value");
2883   Label _is_positive;
2884   testl (reg, reg);
2885   jcc (Assembler::positive, _is_positive);
2886   int offset = (1 << shift_value) - 1 ;
2887 
2888   if (offset == 1) {
2889     incrementl(reg);
2890   } else {
2891     addl(reg, offset);
2892   }
2893 
2894   bind (_is_positive);
2895   sarl(reg, shift_value);
2896 }
2897 
2898 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2899   if (reachable(src)) {
2900     Assembler::divsd(dst, as_Address(src));
2901   } else {
2902     lea(rscratch1, src);
2903     Assembler::divsd(dst, Address(rscratch1, 0));
2904   }
2905 }
2906 
2907 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2908   if (reachable(src)) {
2909     Assembler::divss(dst, as_Address(src));
2910   } else {
2911     lea(rscratch1, src);
2912     Assembler::divss(dst, Address(rscratch1, 0));
2913   }
2914 }
2915 
2916 // !defined(COMPILER2) is because of stupid core builds
2917 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2918 void MacroAssembler::empty_FPU_stack() {
2919   if (VM_Version::supports_mmx()) {
2920     emms();
2921   } else {
2922     for (int i = 8; i-- > 0; ) ffree(i);
2923   }
2924 }
2925 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2926 
2927 
2928 // Defines obj, preserves var_size_in_bytes
2929 void MacroAssembler::eden_allocate(Register obj,
2930                                    Register var_size_in_bytes,
2931                                    int con_size_in_bytes,
2932                                    Register t1,
2933                                    Label& slow_case) {
2934   assert(obj == rax, "obj must be in rax, for cmpxchg");
2935   assert_different_registers(obj, var_size_in_bytes, t1);
2936   if (!Universe::heap()->supports_inline_contig_alloc()) {
2937     jmp(slow_case);
2938   } else {
2939     Register end = t1;
2940     Label retry;
2941     bind(retry);
2942     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2943     movptr(obj, heap_top);
2944     if (var_size_in_bytes == noreg) {
2945       lea(end, Address(obj, con_size_in_bytes));
2946     } else {
2947       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2948     }
2949     // if end < obj then we wrapped around => object too long => slow case
2950     cmpptr(end, obj);
2951     jcc(Assembler::below, slow_case);
2952     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2953     jcc(Assembler::above, slow_case);
2954     // Compare obj with the top addr, and if still equal, store the new top addr in
2955     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2956     // it otherwise. Use lock prefix for atomicity on MPs.
2957     locked_cmpxchgptr(end, heap_top);
2958     jcc(Assembler::notEqual, retry);
2959   }
2960 }
2961 
2962 void MacroAssembler::enter() {
2963   push(rbp);
2964   mov(rbp, rsp);
2965 }
2966 
2967 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2968 void MacroAssembler::fat_nop() {
2969   if (UseAddressNop) {
2970     addr_nop_5();
2971   } else {
2972     emit_int8(0x26); // es:
2973     emit_int8(0x2e); // cs:
2974     emit_int8(0x64); // fs:
2975     emit_int8(0x65); // gs:
2976     emit_int8((unsigned char)0x90);
2977   }
2978 }
2979 
2980 void MacroAssembler::fcmp(Register tmp) {
2981   fcmp(tmp, 1, true, true);
2982 }
2983 
2984 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2985   assert(!pop_right || pop_left, "usage error");
2986   if (VM_Version::supports_cmov()) {
2987     assert(tmp == noreg, "unneeded temp");
2988     if (pop_left) {
2989       fucomip(index);
2990     } else {
2991       fucomi(index);
2992     }
2993     if (pop_right) {
2994       fpop();
2995     }
2996   } else {
2997     assert(tmp != noreg, "need temp");
2998     if (pop_left) {
2999       if (pop_right) {
3000         fcompp();
3001       } else {
3002         fcomp(index);
3003       }
3004     } else {
3005       fcom(index);
3006     }
3007     // convert FPU condition into eflags condition via rax,
3008     save_rax(tmp);
3009     fwait(); fnstsw_ax();
3010     sahf();
3011     restore_rax(tmp);
3012   }
3013   // condition codes set as follows:
3014   //
3015   // CF (corresponds to C0) if x < y
3016   // PF (corresponds to C2) if unordered
3017   // ZF (corresponds to C3) if x = y
3018 }
3019 
3020 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3021   fcmp2int(dst, unordered_is_less, 1, true, true);
3022 }
3023 
3024 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3025   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3026   Label L;
3027   if (unordered_is_less) {
3028     movl(dst, -1);
3029     jcc(Assembler::parity, L);
3030     jcc(Assembler::below , L);
3031     movl(dst, 0);
3032     jcc(Assembler::equal , L);
3033     increment(dst);
3034   } else { // unordered is greater
3035     movl(dst, 1);
3036     jcc(Assembler::parity, L);
3037     jcc(Assembler::above , L);
3038     movl(dst, 0);
3039     jcc(Assembler::equal , L);
3040     decrementl(dst);
3041   }
3042   bind(L);
3043 }
3044 
3045 void MacroAssembler::fld_d(AddressLiteral src) {
3046   fld_d(as_Address(src));
3047 }
3048 
3049 void MacroAssembler::fld_s(AddressLiteral src) {
3050   fld_s(as_Address(src));
3051 }
3052 
3053 void MacroAssembler::fld_x(AddressLiteral src) {
3054   Assembler::fld_x(as_Address(src));
3055 }
3056 
3057 void MacroAssembler::fldcw(AddressLiteral src) {
3058   Assembler::fldcw(as_Address(src));
3059 }
3060 
3061 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3062   if (reachable(src)) {
3063     Assembler::mulpd(dst, as_Address(src));
3064   } else {
3065     lea(rscratch1, src);
3066     Assembler::mulpd(dst, Address(rscratch1, 0));
3067   }
3068 }
3069 
3070 void MacroAssembler::increase_precision() {
3071   subptr(rsp, BytesPerWord);
3072   fnstcw(Address(rsp, 0));
3073   movl(rax, Address(rsp, 0));
3074   orl(rax, 0x300);
3075   push(rax);
3076   fldcw(Address(rsp, 0));
3077   pop(rax);
3078 }
3079 
3080 void MacroAssembler::restore_precision() {
3081   fldcw(Address(rsp, 0));
3082   addptr(rsp, BytesPerWord);
3083 }
3084 
3085 void MacroAssembler::fpop() {
3086   ffree();
3087   fincstp();
3088 }
3089 
3090 void MacroAssembler::load_float(Address src) {
3091   if (UseSSE >= 1) {
3092     movflt(xmm0, src);
3093   } else {
3094     LP64_ONLY(ShouldNotReachHere());
3095     NOT_LP64(fld_s(src));
3096   }
3097 }
3098 
3099 void MacroAssembler::store_float(Address dst) {
3100   if (UseSSE >= 1) {
3101     movflt(dst, xmm0);
3102   } else {
3103     LP64_ONLY(ShouldNotReachHere());
3104     NOT_LP64(fstp_s(dst));
3105   }
3106 }
3107 
3108 void MacroAssembler::load_double(Address src) {
3109   if (UseSSE >= 2) {
3110     movdbl(xmm0, src);
3111   } else {
3112     LP64_ONLY(ShouldNotReachHere());
3113     NOT_LP64(fld_d(src));
3114   }
3115 }
3116 
3117 void MacroAssembler::store_double(Address dst) {
3118   if (UseSSE >= 2) {
3119     movdbl(dst, xmm0);
3120   } else {
3121     LP64_ONLY(ShouldNotReachHere());
3122     NOT_LP64(fstp_d(dst));
3123   }
3124 }
3125 
3126 void MacroAssembler::fremr(Register tmp) {
3127   save_rax(tmp);
3128   { Label L;
3129     bind(L);
3130     fprem();
3131     fwait(); fnstsw_ax();
3132 #ifdef _LP64
3133     testl(rax, 0x400);
3134     jcc(Assembler::notEqual, L);
3135 #else
3136     sahf();
3137     jcc(Assembler::parity, L);
3138 #endif // _LP64
3139   }
3140   restore_rax(tmp);
3141   // Result is in ST0.
3142   // Note: fxch & fpop to get rid of ST1
3143   // (otherwise FPU stack could overflow eventually)
3144   fxch(1);
3145   fpop();
3146 }
3147 
3148 
3149 void MacroAssembler::incrementl(AddressLiteral dst) {
3150   if (reachable(dst)) {
3151     incrementl(as_Address(dst));
3152   } else {
3153     lea(rscratch1, dst);
3154     incrementl(Address(rscratch1, 0));
3155   }
3156 }
3157 
3158 void MacroAssembler::incrementl(ArrayAddress dst) {
3159   incrementl(as_Address(dst));
3160 }
3161 
3162 void MacroAssembler::incrementl(Register reg, int value) {
3163   if (value == min_jint) {addl(reg, value) ; return; }
3164   if (value <  0) { decrementl(reg, -value); return; }
3165   if (value == 0) {                        ; return; }
3166   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3167   /* else */      { addl(reg, value)       ; return; }
3168 }
3169 
3170 void MacroAssembler::incrementl(Address dst, int value) {
3171   if (value == min_jint) {addl(dst, value) ; return; }
3172   if (value <  0) { decrementl(dst, -value); return; }
3173   if (value == 0) {                        ; return; }
3174   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3175   /* else */      { addl(dst, value)       ; return; }
3176 }
3177 
3178 void MacroAssembler::jump(AddressLiteral dst) {
3179   if (reachable(dst)) {
3180     jmp_literal(dst.target(), dst.rspec());
3181   } else {
3182     lea(rscratch1, dst);
3183     jmp(rscratch1);
3184   }
3185 }
3186 
3187 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3188   if (reachable(dst)) {
3189     InstructionMark im(this);
3190     relocate(dst.reloc());
3191     const int short_size = 2;
3192     const int long_size = 6;
3193     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3194     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3195       // 0111 tttn #8-bit disp
3196       emit_int8(0x70 | cc);
3197       emit_int8((offs - short_size) & 0xFF);
3198     } else {
3199       // 0000 1111 1000 tttn #32-bit disp
3200       emit_int8(0x0F);
3201       emit_int8((unsigned char)(0x80 | cc));
3202       emit_int32(offs - long_size);
3203     }
3204   } else {
3205 #ifdef ASSERT
3206     warning("reversing conditional branch");
3207 #endif /* ASSERT */
3208     Label skip;
3209     jccb(reverse[cc], skip);
3210     lea(rscratch1, dst);
3211     Assembler::jmp(rscratch1);
3212     bind(skip);
3213   }
3214 }
3215 
3216 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3217   if (reachable(src)) {
3218     Assembler::ldmxcsr(as_Address(src));
3219   } else {
3220     lea(rscratch1, src);
3221     Assembler::ldmxcsr(Address(rscratch1, 0));
3222   }
3223 }
3224 
3225 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3226   int off;
3227   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3228     off = offset();
3229     movsbl(dst, src); // movsxb
3230   } else {
3231     off = load_unsigned_byte(dst, src);
3232     shll(dst, 24);
3233     sarl(dst, 24);
3234   }
3235   return off;
3236 }
3237 
3238 // Note: load_signed_short used to be called load_signed_word.
3239 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3240 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3241 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3242 int MacroAssembler::load_signed_short(Register dst, Address src) {
3243   int off;
3244   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3245     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3246     // version but this is what 64bit has always done. This seems to imply
3247     // that users are only using 32bits worth.
3248     off = offset();
3249     movswl(dst, src); // movsxw
3250   } else {
3251     off = load_unsigned_short(dst, src);
3252     shll(dst, 16);
3253     sarl(dst, 16);
3254   }
3255   return off;
3256 }
3257 
3258 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3259   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3260   // and "3.9 Partial Register Penalties", p. 22).
3261   int off;
3262   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3263     off = offset();
3264     movzbl(dst, src); // movzxb
3265   } else {
3266     xorl(dst, dst);
3267     off = offset();
3268     movb(dst, src);
3269   }
3270   return off;
3271 }
3272 
3273 // Note: load_unsigned_short used to be called load_unsigned_word.
3274 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3275   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3276   // and "3.9 Partial Register Penalties", p. 22).
3277   int off;
3278   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3279     off = offset();
3280     movzwl(dst, src); // movzxw
3281   } else {
3282     xorl(dst, dst);
3283     off = offset();
3284     movw(dst, src);
3285   }
3286   return off;
3287 }
3288 
3289 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3290   switch (size_in_bytes) {
3291 #ifndef _LP64
3292   case  8:
3293     assert(dst2 != noreg, "second dest register required");
3294     movl(dst,  src);
3295     movl(dst2, src.plus_disp(BytesPerInt));
3296     break;
3297 #else
3298   case  8:  movq(dst, src); break;
3299 #endif
3300   case  4:  movl(dst, src); break;
3301   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3302   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3303   default:  ShouldNotReachHere();
3304   }
3305 }
3306 
3307 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3308   switch (size_in_bytes) {
3309 #ifndef _LP64
3310   case  8:
3311     assert(src2 != noreg, "second source register required");
3312     movl(dst,                        src);
3313     movl(dst.plus_disp(BytesPerInt), src2);
3314     break;
3315 #else
3316   case  8:  movq(dst, src); break;
3317 #endif
3318   case  4:  movl(dst, src); break;
3319   case  2:  movw(dst, src); break;
3320   case  1:  movb(dst, src); break;
3321   default:  ShouldNotReachHere();
3322   }
3323 }
3324 
3325 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3326   if (reachable(dst)) {
3327     movl(as_Address(dst), src);
3328   } else {
3329     lea(rscratch1, dst);
3330     movl(Address(rscratch1, 0), src);
3331   }
3332 }
3333 
3334 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3335   if (reachable(src)) {
3336     movl(dst, as_Address(src));
3337   } else {
3338     lea(rscratch1, src);
3339     movl(dst, Address(rscratch1, 0));
3340   }
3341 }
3342 
3343 // C++ bool manipulation
3344 
3345 void MacroAssembler::movbool(Register dst, Address src) {
3346   if(sizeof(bool) == 1)
3347     movb(dst, src);
3348   else if(sizeof(bool) == 2)
3349     movw(dst, src);
3350   else if(sizeof(bool) == 4)
3351     movl(dst, src);
3352   else
3353     // unsupported
3354     ShouldNotReachHere();
3355 }
3356 
3357 void MacroAssembler::movbool(Address dst, bool boolconst) {
3358   if(sizeof(bool) == 1)
3359     movb(dst, (int) boolconst);
3360   else if(sizeof(bool) == 2)
3361     movw(dst, (int) boolconst);
3362   else if(sizeof(bool) == 4)
3363     movl(dst, (int) boolconst);
3364   else
3365     // unsupported
3366     ShouldNotReachHere();
3367 }
3368 
3369 void MacroAssembler::movbool(Address dst, Register src) {
3370   if(sizeof(bool) == 1)
3371     movb(dst, src);
3372   else if(sizeof(bool) == 2)
3373     movw(dst, src);
3374   else if(sizeof(bool) == 4)
3375     movl(dst, src);
3376   else
3377     // unsupported
3378     ShouldNotReachHere();
3379 }
3380 
3381 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3382   movb(as_Address(dst), src);
3383 }
3384 
3385 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3386   if (reachable(src)) {
3387     movdl(dst, as_Address(src));
3388   } else {
3389     lea(rscratch1, src);
3390     movdl(dst, Address(rscratch1, 0));
3391   }
3392 }
3393 
3394 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3395   if (reachable(src)) {
3396     movq(dst, as_Address(src));
3397   } else {
3398     lea(rscratch1, src);
3399     movq(dst, Address(rscratch1, 0));
3400   }
3401 }
3402 
3403 // AVX512 masks used for fixup loops
3404 jushort evex_simd_mask_table[] =
3405 {
3406   0xffff, 0x0001, 0x0003, 0x0007, 0x000f,
3407   0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff,
3408   0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff,
3409   0x7fff
3410 };
3411 
3412 void MacroAssembler::createmsk(Register dst, Register src) {
3413   ExternalAddress mask_table((address)evex_simd_mask_table);
3414   lea(dst, mask_table);
3415   Assembler::kmovwl(k1, Address(dst, src, Address::times_2, 0));
3416   Assembler::movl(dst, src);
3417 }
3418 
3419 void MacroAssembler::restoremsk() {
3420   ExternalAddress mask_table((address)evex_simd_mask_table);
3421   if (reachable(mask_table)) {
3422     Assembler::kmovwl(k1, as_Address(mask_table));
3423   } else {
3424     lea(rscratch1, mask_table);
3425     Assembler::kmovwl(k1, Address(rscratch1, 0));
3426   }
3427 }
3428 
3429 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3430   if (reachable(src)) {
3431     if (UseXmmLoadAndClearUpper) {
3432       movsd (dst, as_Address(src));
3433     } else {
3434       movlpd(dst, as_Address(src));
3435     }
3436   } else {
3437     lea(rscratch1, src);
3438     if (UseXmmLoadAndClearUpper) {
3439       movsd (dst, Address(rscratch1, 0));
3440     } else {
3441       movlpd(dst, Address(rscratch1, 0));
3442     }
3443   }
3444 }
3445 
3446 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3447   if (reachable(src)) {
3448     movss(dst, as_Address(src));
3449   } else {
3450     lea(rscratch1, src);
3451     movss(dst, Address(rscratch1, 0));
3452   }
3453 }
3454 
3455 void MacroAssembler::movptr(Register dst, Register src) {
3456   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3457 }
3458 
3459 void MacroAssembler::movptr(Register dst, Address src) {
3460   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3461 }
3462 
3463 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3464 void MacroAssembler::movptr(Register dst, intptr_t src) {
3465   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3466 }
3467 
3468 void MacroAssembler::movptr(Address dst, Register src) {
3469   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3470 }
3471 
3472 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3473   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3474     Assembler::vextractf32x4(dst, src, 0);
3475   } else {
3476     Assembler::movdqu(dst, src);
3477   }
3478 }
3479 
3480 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3481   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3482     Assembler::vinsertf32x4(dst, dst, src, 0);
3483   } else {
3484     Assembler::movdqu(dst, src);
3485   }
3486 }
3487 
3488 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3489   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3490     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3491   } else {
3492     Assembler::movdqu(dst, src);
3493   }
3494 }
3495 
3496 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3497   if (reachable(src)) {
3498     movdqu(dst, as_Address(src));
3499   } else {
3500     lea(rscratch1, src);
3501     movdqu(dst, Address(rscratch1, 0));
3502   }
3503 }
3504 
3505 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3506   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3507     vextractf64x4_low(dst, src);
3508   } else {
3509     Assembler::vmovdqu(dst, src);
3510   }
3511 }
3512 
3513 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3514   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3515     vinsertf64x4_low(dst, src);
3516   } else {
3517     Assembler::vmovdqu(dst, src);
3518   }
3519 }
3520 
3521 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3522   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3523     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3524   }
3525   else {
3526     Assembler::vmovdqu(dst, src);
3527   }
3528 }
3529 
3530 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3531   if (reachable(src)) {
3532     vmovdqu(dst, as_Address(src));
3533   }
3534   else {
3535     lea(rscratch1, src);
3536     vmovdqu(dst, Address(rscratch1, 0));
3537   }
3538 }
3539 
3540 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3541   if (reachable(src)) {
3542     Assembler::movdqa(dst, as_Address(src));
3543   } else {
3544     lea(rscratch1, src);
3545     Assembler::movdqa(dst, Address(rscratch1, 0));
3546   }
3547 }
3548 
3549 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3550   if (reachable(src)) {
3551     Assembler::movsd(dst, as_Address(src));
3552   } else {
3553     lea(rscratch1, src);
3554     Assembler::movsd(dst, Address(rscratch1, 0));
3555   }
3556 }
3557 
3558 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3559   if (reachable(src)) {
3560     Assembler::movss(dst, as_Address(src));
3561   } else {
3562     lea(rscratch1, src);
3563     Assembler::movss(dst, Address(rscratch1, 0));
3564   }
3565 }
3566 
3567 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3568   if (reachable(src)) {
3569     Assembler::mulsd(dst, as_Address(src));
3570   } else {
3571     lea(rscratch1, src);
3572     Assembler::mulsd(dst, Address(rscratch1, 0));
3573   }
3574 }
3575 
3576 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3577   if (reachable(src)) {
3578     Assembler::mulss(dst, as_Address(src));
3579   } else {
3580     lea(rscratch1, src);
3581     Assembler::mulss(dst, Address(rscratch1, 0));
3582   }
3583 }
3584 
3585 void MacroAssembler::null_check(Register reg, int offset) {
3586   if (needs_explicit_null_check(offset)) {
3587     // provoke OS NULL exception if reg = NULL by
3588     // accessing M[reg] w/o changing any (non-CC) registers
3589     // NOTE: cmpl is plenty here to provoke a segv
3590     cmpptr(rax, Address(reg, 0));
3591     // Note: should probably use testl(rax, Address(reg, 0));
3592     //       may be shorter code (however, this version of
3593     //       testl needs to be implemented first)
3594   } else {
3595     // nothing to do, (later) access of M[reg + offset]
3596     // will provoke OS NULL exception if reg = NULL
3597   }
3598 }
3599 
3600 void MacroAssembler::os_breakpoint() {
3601   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3602   // (e.g., MSVC can't call ps() otherwise)
3603   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3604 }
3605 
3606 #ifdef _LP64
3607 #define XSTATE_BV 0x200
3608 #endif
3609 
3610 void MacroAssembler::pop_CPU_state() {
3611   pop_FPU_state();
3612   pop_IU_state();
3613 }
3614 
3615 void MacroAssembler::pop_FPU_state() {
3616 #ifndef _LP64
3617   frstor(Address(rsp, 0));
3618 #else
3619   fxrstor(Address(rsp, 0));
3620 #endif
3621   addptr(rsp, FPUStateSizeInWords * wordSize);
3622 }
3623 
3624 void MacroAssembler::pop_IU_state() {
3625   popa();
3626   LP64_ONLY(addq(rsp, 8));
3627   popf();
3628 }
3629 
3630 // Save Integer and Float state
3631 // Warning: Stack must be 16 byte aligned (64bit)
3632 void MacroAssembler::push_CPU_state() {
3633   push_IU_state();
3634   push_FPU_state();
3635 }
3636 
3637 void MacroAssembler::push_FPU_state() {
3638   subptr(rsp, FPUStateSizeInWords * wordSize);
3639 #ifndef _LP64
3640   fnsave(Address(rsp, 0));
3641   fwait();
3642 #else
3643   fxsave(Address(rsp, 0));
3644 #endif // LP64
3645 }
3646 
3647 void MacroAssembler::push_IU_state() {
3648   // Push flags first because pusha kills them
3649   pushf();
3650   // Make sure rsp stays 16-byte aligned
3651   LP64_ONLY(subq(rsp, 8));
3652   pusha();
3653 }
3654 
3655 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3656   // determine java_thread register
3657   if (!java_thread->is_valid()) {
3658     java_thread = rdi;
3659     get_thread(java_thread);
3660   }
3661   // we must set sp to zero to clear frame
3662   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3663   if (clear_fp) {
3664     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3665   }
3666 
3667   if (clear_pc)
3668     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3669 
3670 }
3671 
3672 void MacroAssembler::restore_rax(Register tmp) {
3673   if (tmp == noreg) pop(rax);
3674   else if (tmp != rax) mov(rax, tmp);
3675 }
3676 
3677 void MacroAssembler::round_to(Register reg, int modulus) {
3678   addptr(reg, modulus - 1);
3679   andptr(reg, -modulus);
3680 }
3681 
3682 void MacroAssembler::save_rax(Register tmp) {
3683   if (tmp == noreg) push(rax);
3684   else if (tmp != rax) mov(tmp, rax);
3685 }
3686 
3687 // Write serialization page so VM thread can do a pseudo remote membar.
3688 // We use the current thread pointer to calculate a thread specific
3689 // offset to write to within the page. This minimizes bus traffic
3690 // due to cache line collision.
3691 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3692   movl(tmp, thread);
3693   shrl(tmp, os::get_serialize_page_shift_count());
3694   andl(tmp, (os::vm_page_size() - sizeof(int)));
3695 
3696   Address index(noreg, tmp, Address::times_1);
3697   ExternalAddress page(os::get_memory_serialize_page());
3698 
3699   // Size of store must match masking code above
3700   movl(as_Address(ArrayAddress(page, index)), tmp);
3701 }
3702 
3703 // Calls to C land
3704 //
3705 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3706 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3707 // has to be reset to 0. This is required to allow proper stack traversal.
3708 void MacroAssembler::set_last_Java_frame(Register java_thread,
3709                                          Register last_java_sp,
3710                                          Register last_java_fp,
3711                                          address  last_java_pc) {
3712   // determine java_thread register
3713   if (!java_thread->is_valid()) {
3714     java_thread = rdi;
3715     get_thread(java_thread);
3716   }
3717   // determine last_java_sp register
3718   if (!last_java_sp->is_valid()) {
3719     last_java_sp = rsp;
3720   }
3721 
3722   // last_java_fp is optional
3723 
3724   if (last_java_fp->is_valid()) {
3725     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3726   }
3727 
3728   // last_java_pc is optional
3729 
3730   if (last_java_pc != NULL) {
3731     lea(Address(java_thread,
3732                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3733         InternalAddress(last_java_pc));
3734 
3735   }
3736   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3737 }
3738 
3739 void MacroAssembler::shlptr(Register dst, int imm8) {
3740   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3741 }
3742 
3743 void MacroAssembler::shrptr(Register dst, int imm8) {
3744   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3745 }
3746 
3747 void MacroAssembler::sign_extend_byte(Register reg) {
3748   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3749     movsbl(reg, reg); // movsxb
3750   } else {
3751     shll(reg, 24);
3752     sarl(reg, 24);
3753   }
3754 }
3755 
3756 void MacroAssembler::sign_extend_short(Register reg) {
3757   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3758     movswl(reg, reg); // movsxw
3759   } else {
3760     shll(reg, 16);
3761     sarl(reg, 16);
3762   }
3763 }
3764 
3765 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3766   assert(reachable(src), "Address should be reachable");
3767   testl(dst, as_Address(src));
3768 }
3769 
3770 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3771   int dst_enc = dst->encoding();
3772   int src_enc = src->encoding();
3773   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3774     Assembler::pcmpeqb(dst, src);
3775   } else if ((dst_enc < 16) && (src_enc < 16)) {
3776     Assembler::pcmpeqb(dst, src);
3777   } else if (src_enc < 16) {
3778     subptr(rsp, 64);
3779     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3780     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3781     Assembler::pcmpeqb(xmm0, src);
3782     movdqu(dst, xmm0);
3783     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3784     addptr(rsp, 64);
3785   } else if (dst_enc < 16) {
3786     subptr(rsp, 64);
3787     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3788     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3789     Assembler::pcmpeqb(dst, xmm0);
3790     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3791     addptr(rsp, 64);
3792   } else {
3793     subptr(rsp, 64);
3794     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3795     subptr(rsp, 64);
3796     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3797     movdqu(xmm0, src);
3798     movdqu(xmm1, dst);
3799     Assembler::pcmpeqb(xmm1, xmm0);
3800     movdqu(dst, xmm1);
3801     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3802     addptr(rsp, 64);
3803     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3804     addptr(rsp, 64);
3805   }
3806 }
3807 
3808 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3809   int dst_enc = dst->encoding();
3810   int src_enc = src->encoding();
3811   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3812     Assembler::pcmpeqw(dst, src);
3813   } else if ((dst_enc < 16) && (src_enc < 16)) {
3814     Assembler::pcmpeqw(dst, src);
3815   } else if (src_enc < 16) {
3816     subptr(rsp, 64);
3817     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3818     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3819     Assembler::pcmpeqw(xmm0, src);
3820     movdqu(dst, xmm0);
3821     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3822     addptr(rsp, 64);
3823   } else if (dst_enc < 16) {
3824     subptr(rsp, 64);
3825     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3826     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3827     Assembler::pcmpeqw(dst, xmm0);
3828     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3829     addptr(rsp, 64);
3830   } else {
3831     subptr(rsp, 64);
3832     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3833     subptr(rsp, 64);
3834     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3835     movdqu(xmm0, src);
3836     movdqu(xmm1, dst);
3837     Assembler::pcmpeqw(xmm1, xmm0);
3838     movdqu(dst, xmm1);
3839     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3840     addptr(rsp, 64);
3841     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3842     addptr(rsp, 64);
3843   }
3844 }
3845 
3846 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3847   int dst_enc = dst->encoding();
3848   if (dst_enc < 16) {
3849     Assembler::pcmpestri(dst, src, imm8);
3850   } else {
3851     subptr(rsp, 64);
3852     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3853     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3854     Assembler::pcmpestri(xmm0, src, imm8);
3855     movdqu(dst, xmm0);
3856     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3857     addptr(rsp, 64);
3858   }
3859 }
3860 
3861 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3862   int dst_enc = dst->encoding();
3863   int src_enc = src->encoding();
3864   if ((dst_enc < 16) && (src_enc < 16)) {
3865     Assembler::pcmpestri(dst, src, imm8);
3866   } else if (src_enc < 16) {
3867     subptr(rsp, 64);
3868     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3869     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3870     Assembler::pcmpestri(xmm0, src, imm8);
3871     movdqu(dst, xmm0);
3872     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3873     addptr(rsp, 64);
3874   } else if (dst_enc < 16) {
3875     subptr(rsp, 64);
3876     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3877     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3878     Assembler::pcmpestri(dst, xmm0, imm8);
3879     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3880     addptr(rsp, 64);
3881   } else {
3882     subptr(rsp, 64);
3883     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3884     subptr(rsp, 64);
3885     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3886     movdqu(xmm0, src);
3887     movdqu(xmm1, dst);
3888     Assembler::pcmpestri(xmm1, xmm0, imm8);
3889     movdqu(dst, xmm1);
3890     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3891     addptr(rsp, 64);
3892     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3893     addptr(rsp, 64);
3894   }
3895 }
3896 
3897 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3898   int dst_enc = dst->encoding();
3899   int src_enc = src->encoding();
3900   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3901     Assembler::pmovzxbw(dst, src);
3902   } else if ((dst_enc < 16) && (src_enc < 16)) {
3903     Assembler::pmovzxbw(dst, src);
3904   } else if (src_enc < 16) {
3905     subptr(rsp, 64);
3906     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3907     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3908     Assembler::pmovzxbw(xmm0, src);
3909     movdqu(dst, xmm0);
3910     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3911     addptr(rsp, 64);
3912   } else if (dst_enc < 16) {
3913     subptr(rsp, 64);
3914     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3915     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3916     Assembler::pmovzxbw(dst, xmm0);
3917     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3918     addptr(rsp, 64);
3919   } else {
3920     subptr(rsp, 64);
3921     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3922     subptr(rsp, 64);
3923     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3924     movdqu(xmm0, src);
3925     movdqu(xmm1, dst);
3926     Assembler::pmovzxbw(xmm1, xmm0);
3927     movdqu(dst, xmm1);
3928     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3929     addptr(rsp, 64);
3930     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3931     addptr(rsp, 64);
3932   }
3933 }
3934 
3935 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3936   int dst_enc = dst->encoding();
3937   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3938     Assembler::pmovzxbw(dst, src);
3939   } else if (dst_enc < 16) {
3940     Assembler::pmovzxbw(dst, src);
3941   } else {
3942     subptr(rsp, 64);
3943     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3944     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3945     Assembler::pmovzxbw(xmm0, src);
3946     movdqu(dst, xmm0);
3947     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3948     addptr(rsp, 64);
3949   }
3950 }
3951 
3952 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3953   int src_enc = src->encoding();
3954   if (src_enc < 16) {
3955     Assembler::pmovmskb(dst, src);
3956   } else {
3957     subptr(rsp, 64);
3958     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3959     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3960     Assembler::pmovmskb(dst, xmm0);
3961     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3962     addptr(rsp, 64);
3963   }
3964 }
3965 
3966 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3967   int dst_enc = dst->encoding();
3968   int src_enc = src->encoding();
3969   if ((dst_enc < 16) && (src_enc < 16)) {
3970     Assembler::ptest(dst, src);
3971   } else if (src_enc < 16) {
3972     subptr(rsp, 64);
3973     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3974     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3975     Assembler::ptest(xmm0, src);
3976     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3977     addptr(rsp, 64);
3978   } else if (dst_enc < 16) {
3979     subptr(rsp, 64);
3980     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3981     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3982     Assembler::ptest(dst, xmm0);
3983     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985   } else {
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3988     subptr(rsp, 64);
3989     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3990     movdqu(xmm0, src);
3991     movdqu(xmm1, dst);
3992     Assembler::ptest(xmm1, xmm0);
3993     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3994     addptr(rsp, 64);
3995     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3996     addptr(rsp, 64);
3997   }
3998 }
3999 
4000 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4001   if (reachable(src)) {
4002     Assembler::sqrtsd(dst, as_Address(src));
4003   } else {
4004     lea(rscratch1, src);
4005     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4006   }
4007 }
4008 
4009 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4010   if (reachable(src)) {
4011     Assembler::sqrtss(dst, as_Address(src));
4012   } else {
4013     lea(rscratch1, src);
4014     Assembler::sqrtss(dst, Address(rscratch1, 0));
4015   }
4016 }
4017 
4018 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4019   if (reachable(src)) {
4020     Assembler::subsd(dst, as_Address(src));
4021   } else {
4022     lea(rscratch1, src);
4023     Assembler::subsd(dst, Address(rscratch1, 0));
4024   }
4025 }
4026 
4027 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4028   if (reachable(src)) {
4029     Assembler::subss(dst, as_Address(src));
4030   } else {
4031     lea(rscratch1, src);
4032     Assembler::subss(dst, Address(rscratch1, 0));
4033   }
4034 }
4035 
4036 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4037   if (reachable(src)) {
4038     Assembler::ucomisd(dst, as_Address(src));
4039   } else {
4040     lea(rscratch1, src);
4041     Assembler::ucomisd(dst, Address(rscratch1, 0));
4042   }
4043 }
4044 
4045 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4046   if (reachable(src)) {
4047     Assembler::ucomiss(dst, as_Address(src));
4048   } else {
4049     lea(rscratch1, src);
4050     Assembler::ucomiss(dst, Address(rscratch1, 0));
4051   }
4052 }
4053 
4054 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4055   // Used in sign-bit flipping with aligned address.
4056   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4057   if (reachable(src)) {
4058     Assembler::xorpd(dst, as_Address(src));
4059   } else {
4060     lea(rscratch1, src);
4061     Assembler::xorpd(dst, Address(rscratch1, 0));
4062   }
4063 }
4064 
4065 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4066   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4067     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4068   }
4069   else {
4070     Assembler::xorpd(dst, src);
4071   }
4072 }
4073 
4074 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4075   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4076     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4077   } else {
4078     Assembler::xorps(dst, src);
4079   }
4080 }
4081 
4082 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4083   // Used in sign-bit flipping with aligned address.
4084   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4085   if (reachable(src)) {
4086     Assembler::xorps(dst, as_Address(src));
4087   } else {
4088     lea(rscratch1, src);
4089     Assembler::xorps(dst, Address(rscratch1, 0));
4090   }
4091 }
4092 
4093 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4094   // Used in sign-bit flipping with aligned address.
4095   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4096   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4097   if (reachable(src)) {
4098     Assembler::pshufb(dst, as_Address(src));
4099   } else {
4100     lea(rscratch1, src);
4101     Assembler::pshufb(dst, Address(rscratch1, 0));
4102   }
4103 }
4104 
4105 // AVX 3-operands instructions
4106 
4107 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4108   if (reachable(src)) {
4109     vaddsd(dst, nds, as_Address(src));
4110   } else {
4111     lea(rscratch1, src);
4112     vaddsd(dst, nds, Address(rscratch1, 0));
4113   }
4114 }
4115 
4116 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4117   if (reachable(src)) {
4118     vaddss(dst, nds, as_Address(src));
4119   } else {
4120     lea(rscratch1, src);
4121     vaddss(dst, nds, Address(rscratch1, 0));
4122   }
4123 }
4124 
4125 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4126   int dst_enc = dst->encoding();
4127   int nds_enc = nds->encoding();
4128   int src_enc = src->encoding();
4129   if ((dst_enc < 16) && (nds_enc < 16)) {
4130     vandps(dst, nds, negate_field, vector_len);
4131   } else if ((src_enc < 16) && (dst_enc < 16)) {
4132     movss(src, nds);
4133     vandps(dst, src, negate_field, vector_len);
4134   } else if (src_enc < 16) {
4135     movss(src, nds);
4136     vandps(src, src, negate_field, vector_len);
4137     movss(dst, src);
4138   } else if (dst_enc < 16) {
4139     movdqu(src, xmm0);
4140     movss(xmm0, nds);
4141     vandps(dst, xmm0, negate_field, vector_len);
4142     movdqu(xmm0, src);
4143   } else if (nds_enc < 16) {
4144     movdqu(src, xmm0);
4145     vandps(xmm0, nds, negate_field, vector_len);
4146     movss(dst, xmm0);
4147     movdqu(xmm0, src);
4148   } else {
4149     movdqu(src, xmm0);
4150     movss(xmm0, nds);
4151     vandps(xmm0, xmm0, negate_field, vector_len);
4152     movss(dst, xmm0);
4153     movdqu(xmm0, src);
4154   }
4155 }
4156 
4157 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4158   int dst_enc = dst->encoding();
4159   int nds_enc = nds->encoding();
4160   int src_enc = src->encoding();
4161   if ((dst_enc < 16) && (nds_enc < 16)) {
4162     vandpd(dst, nds, negate_field, vector_len);
4163   } else if ((src_enc < 16) && (dst_enc < 16)) {
4164     movsd(src, nds);
4165     vandpd(dst, src, negate_field, vector_len);
4166   } else if (src_enc < 16) {
4167     movsd(src, nds);
4168     vandpd(src, src, negate_field, vector_len);
4169     movsd(dst, src);
4170   } else if (dst_enc < 16) {
4171     movdqu(src, xmm0);
4172     movsd(xmm0, nds);
4173     vandpd(dst, xmm0, negate_field, vector_len);
4174     movdqu(xmm0, src);
4175   } else if (nds_enc < 16) {
4176     movdqu(src, xmm0);
4177     vandpd(xmm0, nds, negate_field, vector_len);
4178     movsd(dst, xmm0);
4179     movdqu(xmm0, src);
4180   } else {
4181     movdqu(src, xmm0);
4182     movsd(xmm0, nds);
4183     vandpd(xmm0, xmm0, negate_field, vector_len);
4184     movsd(dst, xmm0);
4185     movdqu(xmm0, src);
4186   }
4187 }
4188 
4189 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4190   int dst_enc = dst->encoding();
4191   int nds_enc = nds->encoding();
4192   int src_enc = src->encoding();
4193   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4194     Assembler::vpaddb(dst, nds, src, vector_len);
4195   } else if ((dst_enc < 16) && (src_enc < 16)) {
4196     Assembler::vpaddb(dst, dst, src, vector_len);
4197   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4198     // use nds as scratch for src
4199     evmovdqul(nds, src, Assembler::AVX_512bit);
4200     Assembler::vpaddb(dst, dst, nds, vector_len);
4201   } else if ((src_enc < 16) && (nds_enc < 16)) {
4202     // use nds as scratch for dst
4203     evmovdqul(nds, dst, Assembler::AVX_512bit);
4204     Assembler::vpaddb(nds, nds, src, vector_len);
4205     evmovdqul(dst, nds, Assembler::AVX_512bit);
4206   } else if (dst_enc < 16) {
4207     // use nds as scatch for xmm0 to hold src
4208     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4209     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4210     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4211     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4212   } else {
4213     // worse case scenario, all regs are in the upper bank
4214     subptr(rsp, 64);
4215     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4216     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4217     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4218     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4219     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4220     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4221     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4222     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4223     addptr(rsp, 64);
4224   }
4225 }
4226 
4227 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4228   int dst_enc = dst->encoding();
4229   int nds_enc = nds->encoding();
4230   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4231     Assembler::vpaddb(dst, nds, src, vector_len);
4232   } else if (dst_enc < 16) {
4233     Assembler::vpaddb(dst, dst, src, vector_len);
4234   } else if (nds_enc < 16) {
4235     // implies dst_enc in upper bank with src as scratch
4236     evmovdqul(nds, dst, Assembler::AVX_512bit);
4237     Assembler::vpaddb(nds, nds, src, vector_len);
4238     evmovdqul(dst, nds, Assembler::AVX_512bit);
4239   } else {
4240     // worse case scenario, all regs in upper bank
4241     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4242     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4243     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4244     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4245   }
4246 }
4247 
4248 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4249   int dst_enc = dst->encoding();
4250   int nds_enc = nds->encoding();
4251   int src_enc = src->encoding();
4252   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4253     Assembler::vpaddw(dst, nds, src, vector_len);
4254   } else if ((dst_enc < 16) && (src_enc < 16)) {
4255     Assembler::vpaddw(dst, dst, src, vector_len);
4256   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4257     // use nds as scratch for src
4258     evmovdqul(nds, src, Assembler::AVX_512bit);
4259     Assembler::vpaddw(dst, dst, nds, vector_len);
4260   } else if ((src_enc < 16) && (nds_enc < 16)) {
4261     // use nds as scratch for dst
4262     evmovdqul(nds, dst, Assembler::AVX_512bit);
4263     Assembler::vpaddw(nds, nds, src, vector_len);
4264     evmovdqul(dst, nds, Assembler::AVX_512bit);
4265   } else if (dst_enc < 16) {
4266     // use nds as scatch for xmm0 to hold src
4267     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4268     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4269     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4270     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4271   } else {
4272     // worse case scenario, all regs are in the upper bank
4273     subptr(rsp, 64);
4274     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4275     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4276     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4277     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4278     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4279     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4280     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4281     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4282     addptr(rsp, 64);
4283   }
4284 }
4285 
4286 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4287   int dst_enc = dst->encoding();
4288   int nds_enc = nds->encoding();
4289   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4290     Assembler::vpaddw(dst, nds, src, vector_len);
4291   } else if (dst_enc < 16) {
4292     Assembler::vpaddw(dst, dst, src, vector_len);
4293   } else if (nds_enc < 16) {
4294     // implies dst_enc in upper bank with src as scratch
4295     evmovdqul(nds, dst, Assembler::AVX_512bit);
4296     Assembler::vpaddw(nds, nds, src, vector_len);
4297     evmovdqul(dst, nds, Assembler::AVX_512bit);
4298   } else {
4299     // worse case scenario, all regs in upper bank
4300     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4301     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4302     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4303     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4304   }
4305 }
4306 
4307 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4308   int dst_enc = dst->encoding();
4309   int src_enc = src->encoding();
4310   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4311     Assembler::vpbroadcastw(dst, src);
4312   } else if ((dst_enc < 16) && (src_enc < 16)) {
4313     Assembler::vpbroadcastw(dst, src);
4314   } else if (src_enc < 16) {
4315     subptr(rsp, 64);
4316     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4317     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4318     Assembler::vpbroadcastw(xmm0, src);
4319     movdqu(dst, xmm0);
4320     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4321     addptr(rsp, 64);
4322   } else if (dst_enc < 16) {
4323     subptr(rsp, 64);
4324     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4325     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4326     Assembler::vpbroadcastw(dst, xmm0);
4327     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4328     addptr(rsp, 64);
4329   } else {
4330     subptr(rsp, 64);
4331     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4332     subptr(rsp, 64);
4333     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4334     movdqu(xmm0, src);
4335     movdqu(xmm1, dst);
4336     Assembler::vpbroadcastw(xmm1, xmm0);
4337     movdqu(dst, xmm1);
4338     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4339     addptr(rsp, 64);
4340     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4341     addptr(rsp, 64);
4342   }
4343 }
4344 
4345 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4346   int dst_enc = dst->encoding();
4347   int nds_enc = nds->encoding();
4348   int src_enc = src->encoding();
4349   assert(dst_enc == nds_enc, "");
4350   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4351     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4352   } else if ((dst_enc < 16) && (src_enc < 16)) {
4353     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4354   } else if (src_enc < 16) {
4355     subptr(rsp, 64);
4356     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4357     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4358     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4359     movdqu(dst, xmm0);
4360     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4361     addptr(rsp, 64);
4362   } else if (dst_enc < 16) {
4363     subptr(rsp, 64);
4364     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4365     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4366     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4367     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4368     addptr(rsp, 64);
4369   } else {
4370     subptr(rsp, 64);
4371     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4372     subptr(rsp, 64);
4373     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4374     movdqu(xmm0, src);
4375     movdqu(xmm1, dst);
4376     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4377     movdqu(dst, xmm1);
4378     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4379     addptr(rsp, 64);
4380     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4381     addptr(rsp, 64);
4382   }
4383 }
4384 
4385 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4386   int dst_enc = dst->encoding();
4387   int nds_enc = nds->encoding();
4388   int src_enc = src->encoding();
4389   assert(dst_enc == nds_enc, "");
4390   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4391     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4392   } else if ((dst_enc < 16) && (src_enc < 16)) {
4393     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4394   } else if (src_enc < 16) {
4395     subptr(rsp, 64);
4396     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4397     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4398     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4399     movdqu(dst, xmm0);
4400     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4401     addptr(rsp, 64);
4402   } else if (dst_enc < 16) {
4403     subptr(rsp, 64);
4404     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4405     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4406     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4407     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4408     addptr(rsp, 64);
4409   } else {
4410     subptr(rsp, 64);
4411     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4412     subptr(rsp, 64);
4413     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4414     movdqu(xmm0, src);
4415     movdqu(xmm1, dst);
4416     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4417     movdqu(dst, xmm1);
4418     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4419     addptr(rsp, 64);
4420     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4421     addptr(rsp, 64);
4422   }
4423 }
4424 
4425 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4426   int dst_enc = dst->encoding();
4427   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4428     Assembler::vpmovzxbw(dst, src, vector_len);
4429   } else if (dst_enc < 16) {
4430     Assembler::vpmovzxbw(dst, src, vector_len);
4431   } else {
4432     subptr(rsp, 64);
4433     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4434     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4435     Assembler::vpmovzxbw(xmm0, src, vector_len);
4436     movdqu(dst, xmm0);
4437     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4438     addptr(rsp, 64);
4439   }
4440 }
4441 
4442 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4443   int src_enc = src->encoding();
4444   if (src_enc < 16) {
4445     Assembler::vpmovmskb(dst, src);
4446   } else {
4447     subptr(rsp, 64);
4448     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4449     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4450     Assembler::vpmovmskb(dst, xmm0);
4451     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4452     addptr(rsp, 64);
4453   }
4454 }
4455 
4456 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4457   int dst_enc = dst->encoding();
4458   int nds_enc = nds->encoding();
4459   int src_enc = src->encoding();
4460   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4461     Assembler::vpmullw(dst, nds, src, vector_len);
4462   } else if ((dst_enc < 16) && (src_enc < 16)) {
4463     Assembler::vpmullw(dst, dst, src, vector_len);
4464   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4465     // use nds as scratch for src
4466     evmovdqul(nds, src, Assembler::AVX_512bit);
4467     Assembler::vpmullw(dst, dst, nds, vector_len);
4468   } else if ((src_enc < 16) && (nds_enc < 16)) {
4469     // use nds as scratch for dst
4470     evmovdqul(nds, dst, Assembler::AVX_512bit);
4471     Assembler::vpmullw(nds, nds, src, vector_len);
4472     evmovdqul(dst, nds, Assembler::AVX_512bit);
4473   } else if (dst_enc < 16) {
4474     // use nds as scatch for xmm0 to hold src
4475     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4476     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4477     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4478     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4479   } else {
4480     // worse case scenario, all regs are in the upper bank
4481     subptr(rsp, 64);
4482     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4483     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4484     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4485     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4486     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4487     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4488     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4489     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4490     addptr(rsp, 64);
4491   }
4492 }
4493 
4494 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4495   int dst_enc = dst->encoding();
4496   int nds_enc = nds->encoding();
4497   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4498     Assembler::vpmullw(dst, nds, src, vector_len);
4499   } else if (dst_enc < 16) {
4500     Assembler::vpmullw(dst, dst, src, vector_len);
4501   } else if (nds_enc < 16) {
4502     // implies dst_enc in upper bank with src as scratch
4503     evmovdqul(nds, dst, Assembler::AVX_512bit);
4504     Assembler::vpmullw(nds, nds, src, vector_len);
4505     evmovdqul(dst, nds, Assembler::AVX_512bit);
4506   } else {
4507     // worse case scenario, all regs in upper bank
4508     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4509     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4510     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4511     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4512   }
4513 }
4514 
4515 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4516   int dst_enc = dst->encoding();
4517   int nds_enc = nds->encoding();
4518   int src_enc = src->encoding();
4519   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4520     Assembler::vpsubb(dst, nds, src, vector_len);
4521   } else if ((dst_enc < 16) && (src_enc < 16)) {
4522     Assembler::vpsubb(dst, dst, src, vector_len);
4523   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4524     // use nds as scratch for src
4525     evmovdqul(nds, src, Assembler::AVX_512bit);
4526     Assembler::vpsubb(dst, dst, nds, vector_len);
4527   } else if ((src_enc < 16) && (nds_enc < 16)) {
4528     // use nds as scratch for dst
4529     evmovdqul(nds, dst, Assembler::AVX_512bit);
4530     Assembler::vpsubb(nds, nds, src, vector_len);
4531     evmovdqul(dst, nds, Assembler::AVX_512bit);
4532   } else if (dst_enc < 16) {
4533     // use nds as scatch for xmm0 to hold src
4534     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4535     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4536     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4537     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4538   } else {
4539     // worse case scenario, all regs are in the upper bank
4540     subptr(rsp, 64);
4541     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4542     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4543     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4544     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4545     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4546     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4547     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4548     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4549     addptr(rsp, 64);
4550   }
4551 }
4552 
4553 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4554   int dst_enc = dst->encoding();
4555   int nds_enc = nds->encoding();
4556   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4557     Assembler::vpsubb(dst, nds, src, vector_len);
4558   } else if (dst_enc < 16) {
4559     Assembler::vpsubb(dst, dst, src, vector_len);
4560   } else if (nds_enc < 16) {
4561     // implies dst_enc in upper bank with src as scratch
4562     evmovdqul(nds, dst, Assembler::AVX_512bit);
4563     Assembler::vpsubb(nds, nds, src, vector_len);
4564     evmovdqul(dst, nds, Assembler::AVX_512bit);
4565   } else {
4566     // worse case scenario, all regs in upper bank
4567     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4568     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4569     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4570     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4571   }
4572 }
4573 
4574 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4575   int dst_enc = dst->encoding();
4576   int nds_enc = nds->encoding();
4577   int src_enc = src->encoding();
4578   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4579     Assembler::vpsubw(dst, nds, src, vector_len);
4580   } else if ((dst_enc < 16) && (src_enc < 16)) {
4581     Assembler::vpsubw(dst, dst, src, vector_len);
4582   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4583     // use nds as scratch for src
4584     evmovdqul(nds, src, Assembler::AVX_512bit);
4585     Assembler::vpsubw(dst, dst, nds, vector_len);
4586   } else if ((src_enc < 16) && (nds_enc < 16)) {
4587     // use nds as scratch for dst
4588     evmovdqul(nds, dst, Assembler::AVX_512bit);
4589     Assembler::vpsubw(nds, nds, src, vector_len);
4590     evmovdqul(dst, nds, Assembler::AVX_512bit);
4591   } else if (dst_enc < 16) {
4592     // use nds as scatch for xmm0 to hold src
4593     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4594     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4595     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4596     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4597   } else {
4598     // worse case scenario, all regs are in the upper bank
4599     subptr(rsp, 64);
4600     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4601     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4603     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4604     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4605     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4606     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4607     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4608     addptr(rsp, 64);
4609   }
4610 }
4611 
4612 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4613   int dst_enc = dst->encoding();
4614   int nds_enc = nds->encoding();
4615   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4616     Assembler::vpsubw(dst, nds, src, vector_len);
4617   } else if (dst_enc < 16) {
4618     Assembler::vpsubw(dst, dst, src, vector_len);
4619   } else if (nds_enc < 16) {
4620     // implies dst_enc in upper bank with src as scratch
4621     evmovdqul(nds, dst, Assembler::AVX_512bit);
4622     Assembler::vpsubw(nds, nds, src, vector_len);
4623     evmovdqul(dst, nds, Assembler::AVX_512bit);
4624   } else {
4625     // worse case scenario, all regs in upper bank
4626     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4627     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4628     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4629     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4630   }
4631 }
4632 
4633 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4634   int dst_enc = dst->encoding();
4635   int nds_enc = nds->encoding();
4636   int shift_enc = shift->encoding();
4637   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4638     Assembler::vpsraw(dst, nds, shift, vector_len);
4639   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4640     Assembler::vpsraw(dst, dst, shift, vector_len);
4641   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4642     // use nds_enc as scratch with shift
4643     evmovdqul(nds, shift, Assembler::AVX_512bit);
4644     Assembler::vpsraw(dst, dst, nds, vector_len);
4645   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4646     // use nds as scratch with dst
4647     evmovdqul(nds, dst, Assembler::AVX_512bit);
4648     Assembler::vpsraw(nds, nds, shift, vector_len);
4649     evmovdqul(dst, nds, Assembler::AVX_512bit);
4650   } else if (dst_enc < 16) {
4651     // use nds to save a copy of xmm0 and hold shift
4652     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4653     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4654     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4655     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4656   } else if (nds_enc < 16) {
4657     // use nds as dest as temps
4658     evmovdqul(nds, dst, Assembler::AVX_512bit);
4659     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4660     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4661     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4662     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4663     evmovdqul(dst, nds, Assembler::AVX_512bit);
4664   } else {
4665     // worse case scenario, all regs are in the upper bank
4666     subptr(rsp, 64);
4667     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4668     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4669     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4670     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4671     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4672     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4673     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4674     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4675     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4676     addptr(rsp, 64);
4677   }
4678 }
4679 
4680 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4681   int dst_enc = dst->encoding();
4682   int nds_enc = nds->encoding();
4683   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4684     Assembler::vpsraw(dst, nds, shift, vector_len);
4685   } else if (dst_enc < 16) {
4686     Assembler::vpsraw(dst, dst, shift, vector_len);
4687   } else if (nds_enc < 16) {
4688     // use nds as scratch
4689     evmovdqul(nds, dst, Assembler::AVX_512bit);
4690     Assembler::vpsraw(nds, nds, shift, vector_len);
4691     evmovdqul(dst, nds, Assembler::AVX_512bit);
4692   } else {
4693     // use nds as scratch for xmm0
4694     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4695     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4696     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4697     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4698   }
4699 }
4700 
4701 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4702   int dst_enc = dst->encoding();
4703   int nds_enc = nds->encoding();
4704   int shift_enc = shift->encoding();
4705   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4706     Assembler::vpsrlw(dst, nds, shift, vector_len);
4707   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4708     Assembler::vpsrlw(dst, dst, shift, vector_len);
4709   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4710     // use nds_enc as scratch with shift
4711     evmovdqul(nds, shift, Assembler::AVX_512bit);
4712     Assembler::vpsrlw(dst, dst, nds, vector_len);
4713   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4714     // use nds as scratch with dst
4715     evmovdqul(nds, dst, Assembler::AVX_512bit);
4716     Assembler::vpsrlw(nds, nds, shift, vector_len);
4717     evmovdqul(dst, nds, Assembler::AVX_512bit);
4718   } else if (dst_enc < 16) {
4719     // use nds to save a copy of xmm0 and hold shift
4720     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4721     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4722     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4723     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4724   } else if (nds_enc < 16) {
4725     // use nds as dest as temps
4726     evmovdqul(nds, dst, Assembler::AVX_512bit);
4727     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4728     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4729     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4730     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4731     evmovdqul(dst, nds, Assembler::AVX_512bit);
4732   } else {
4733     // worse case scenario, all regs are in the upper bank
4734     subptr(rsp, 64);
4735     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4736     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4737     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4738     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4739     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4740     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4741     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4742     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4743     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4744     addptr(rsp, 64);
4745   }
4746 }
4747 
4748 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4749   int dst_enc = dst->encoding();
4750   int nds_enc = nds->encoding();
4751   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4752     Assembler::vpsrlw(dst, nds, shift, vector_len);
4753   } else if (dst_enc < 16) {
4754     Assembler::vpsrlw(dst, dst, shift, vector_len);
4755   } else if (nds_enc < 16) {
4756     // use nds as scratch
4757     evmovdqul(nds, dst, Assembler::AVX_512bit);
4758     Assembler::vpsrlw(nds, nds, shift, vector_len);
4759     evmovdqul(dst, nds, Assembler::AVX_512bit);
4760   } else {
4761     // use nds as scratch for xmm0
4762     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4763     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4764     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4765     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4766   }
4767 }
4768 
4769 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4770   int dst_enc = dst->encoding();
4771   int nds_enc = nds->encoding();
4772   int shift_enc = shift->encoding();
4773   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4774     Assembler::vpsllw(dst, nds, shift, vector_len);
4775   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4776     Assembler::vpsllw(dst, dst, shift, vector_len);
4777   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4778     // use nds_enc as scratch with shift
4779     evmovdqul(nds, shift, Assembler::AVX_512bit);
4780     Assembler::vpsllw(dst, dst, nds, vector_len);
4781   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4782     // use nds as scratch with dst
4783     evmovdqul(nds, dst, Assembler::AVX_512bit);
4784     Assembler::vpsllw(nds, nds, shift, vector_len);
4785     evmovdqul(dst, nds, Assembler::AVX_512bit);
4786   } else if (dst_enc < 16) {
4787     // use nds to save a copy of xmm0 and hold shift
4788     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4789     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4790     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4791     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4792   } else if (nds_enc < 16) {
4793     // use nds as dest as temps
4794     evmovdqul(nds, dst, Assembler::AVX_512bit);
4795     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4796     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4797     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4798     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4799     evmovdqul(dst, nds, Assembler::AVX_512bit);
4800   } else {
4801     // worse case scenario, all regs are in the upper bank
4802     subptr(rsp, 64);
4803     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4804     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4805     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4806     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4807     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4808     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4809     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4810     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4811     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4812     addptr(rsp, 64);
4813   }
4814 }
4815 
4816 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4817   int dst_enc = dst->encoding();
4818   int nds_enc = nds->encoding();
4819   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4820     Assembler::vpsllw(dst, nds, shift, vector_len);
4821   } else if (dst_enc < 16) {
4822     Assembler::vpsllw(dst, dst, shift, vector_len);
4823   } else if (nds_enc < 16) {
4824     // use nds as scratch
4825     evmovdqul(nds, dst, Assembler::AVX_512bit);
4826     Assembler::vpsllw(nds, nds, shift, vector_len);
4827     evmovdqul(dst, nds, Assembler::AVX_512bit);
4828   } else {
4829     // use nds as scratch for xmm0
4830     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4831     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4832     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4833     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4834   }
4835 }
4836 
4837 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4838   int dst_enc = dst->encoding();
4839   int src_enc = src->encoding();
4840   if ((dst_enc < 16) && (src_enc < 16)) {
4841     Assembler::vptest(dst, src);
4842   } else if (src_enc < 16) {
4843     subptr(rsp, 64);
4844     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4845     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4846     Assembler::vptest(xmm0, src);
4847     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4848     addptr(rsp, 64);
4849   } else if (dst_enc < 16) {
4850     subptr(rsp, 64);
4851     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4852     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4853     Assembler::vptest(dst, xmm0);
4854     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4855     addptr(rsp, 64);
4856   } else {
4857     subptr(rsp, 64);
4858     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4859     subptr(rsp, 64);
4860     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4861     movdqu(xmm0, src);
4862     movdqu(xmm1, dst);
4863     Assembler::vptest(xmm1, xmm0);
4864     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4865     addptr(rsp, 64);
4866     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4867     addptr(rsp, 64);
4868   }
4869 }
4870 
4871 // This instruction exists within macros, ergo we cannot control its input
4872 // when emitted through those patterns.
4873 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4874   if (VM_Version::supports_avx512nobw()) {
4875     int dst_enc = dst->encoding();
4876     int src_enc = src->encoding();
4877     if (dst_enc == src_enc) {
4878       if (dst_enc < 16) {
4879         Assembler::punpcklbw(dst, src);
4880       } else {
4881         subptr(rsp, 64);
4882         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4883         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4884         Assembler::punpcklbw(xmm0, xmm0);
4885         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4886         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4887         addptr(rsp, 64);
4888       }
4889     } else {
4890       if ((src_enc < 16) && (dst_enc < 16)) {
4891         Assembler::punpcklbw(dst, src);
4892       } else if (src_enc < 16) {
4893         subptr(rsp, 64);
4894         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4895         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4896         Assembler::punpcklbw(xmm0, src);
4897         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4898         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4899         addptr(rsp, 64);
4900       } else if (dst_enc < 16) {
4901         subptr(rsp, 64);
4902         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4903         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4904         Assembler::punpcklbw(dst, xmm0);
4905         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4906         addptr(rsp, 64);
4907       } else {
4908         subptr(rsp, 64);
4909         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4910         subptr(rsp, 64);
4911         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4912         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4913         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4914         Assembler::punpcklbw(xmm0, xmm1);
4915         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4916         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4917         addptr(rsp, 64);
4918         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4919         addptr(rsp, 64);
4920       }
4921     }
4922   } else {
4923     Assembler::punpcklbw(dst, src);
4924   }
4925 }
4926 
4927 // This instruction exists within macros, ergo we cannot control its input
4928 // when emitted through those patterns.
4929 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4930   if (VM_Version::supports_avx512nobw()) {
4931     int dst_enc = dst->encoding();
4932     int src_enc = src->encoding();
4933     if (dst_enc == src_enc) {
4934       if (dst_enc < 16) {
4935         Assembler::pshuflw(dst, src, mode);
4936       } else {
4937         subptr(rsp, 64);
4938         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4939         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4940         Assembler::pshuflw(xmm0, xmm0, mode);
4941         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4942         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4943         addptr(rsp, 64);
4944       }
4945     } else {
4946       if ((src_enc < 16) && (dst_enc < 16)) {
4947         Assembler::pshuflw(dst, src, mode);
4948       } else if (src_enc < 16) {
4949         subptr(rsp, 64);
4950         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4951         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4952         Assembler::pshuflw(xmm0, src, mode);
4953         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4954         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4955         addptr(rsp, 64);
4956       } else if (dst_enc < 16) {
4957         subptr(rsp, 64);
4958         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4959         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4960         Assembler::pshuflw(dst, xmm0, mode);
4961         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4962         addptr(rsp, 64);
4963       } else {
4964         subptr(rsp, 64);
4965         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4966         subptr(rsp, 64);
4967         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4968         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4969         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4970         Assembler::pshuflw(xmm0, xmm1, mode);
4971         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4972         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4973         addptr(rsp, 64);
4974         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4975         addptr(rsp, 64);
4976       }
4977     }
4978   } else {
4979     Assembler::pshuflw(dst, src, mode);
4980   }
4981 }
4982 
4983 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4984   if (reachable(src)) {
4985     vandpd(dst, nds, as_Address(src), vector_len);
4986   } else {
4987     lea(rscratch1, src);
4988     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4989   }
4990 }
4991 
4992 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4993   if (reachable(src)) {
4994     vandps(dst, nds, as_Address(src), vector_len);
4995   } else {
4996     lea(rscratch1, src);
4997     vandps(dst, nds, Address(rscratch1, 0), vector_len);
4998   }
4999 }
5000 
5001 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5002   if (reachable(src)) {
5003     vdivsd(dst, nds, as_Address(src));
5004   } else {
5005     lea(rscratch1, src);
5006     vdivsd(dst, nds, Address(rscratch1, 0));
5007   }
5008 }
5009 
5010 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5011   if (reachable(src)) {
5012     vdivss(dst, nds, as_Address(src));
5013   } else {
5014     lea(rscratch1, src);
5015     vdivss(dst, nds, Address(rscratch1, 0));
5016   }
5017 }
5018 
5019 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5020   if (reachable(src)) {
5021     vmulsd(dst, nds, as_Address(src));
5022   } else {
5023     lea(rscratch1, src);
5024     vmulsd(dst, nds, Address(rscratch1, 0));
5025   }
5026 }
5027 
5028 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5029   if (reachable(src)) {
5030     vmulss(dst, nds, as_Address(src));
5031   } else {
5032     lea(rscratch1, src);
5033     vmulss(dst, nds, Address(rscratch1, 0));
5034   }
5035 }
5036 
5037 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5038   if (reachable(src)) {
5039     vsubsd(dst, nds, as_Address(src));
5040   } else {
5041     lea(rscratch1, src);
5042     vsubsd(dst, nds, Address(rscratch1, 0));
5043   }
5044 }
5045 
5046 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5047   if (reachable(src)) {
5048     vsubss(dst, nds, as_Address(src));
5049   } else {
5050     lea(rscratch1, src);
5051     vsubss(dst, nds, Address(rscratch1, 0));
5052   }
5053 }
5054 
5055 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5056   int nds_enc = nds->encoding();
5057   int dst_enc = dst->encoding();
5058   bool dst_upper_bank = (dst_enc > 15);
5059   bool nds_upper_bank = (nds_enc > 15);
5060   if (VM_Version::supports_avx512novl() &&
5061       (nds_upper_bank || dst_upper_bank)) {
5062     if (dst_upper_bank) {
5063       subptr(rsp, 64);
5064       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5065       movflt(xmm0, nds);
5066       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5067       movflt(dst, xmm0);
5068       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5069       addptr(rsp, 64);
5070     } else {
5071       movflt(dst, nds);
5072       vxorps(dst, dst, src, Assembler::AVX_128bit);
5073     }
5074   } else {
5075     vxorps(dst, nds, src, Assembler::AVX_128bit);
5076   }
5077 }
5078 
5079 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5080   int nds_enc = nds->encoding();
5081   int dst_enc = dst->encoding();
5082   bool dst_upper_bank = (dst_enc > 15);
5083   bool nds_upper_bank = (nds_enc > 15);
5084   if (VM_Version::supports_avx512novl() &&
5085       (nds_upper_bank || dst_upper_bank)) {
5086     if (dst_upper_bank) {
5087       subptr(rsp, 64);
5088       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5089       movdbl(xmm0, nds);
5090       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5091       movdbl(dst, xmm0);
5092       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5093       addptr(rsp, 64);
5094     } else {
5095       movdbl(dst, nds);
5096       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5097     }
5098   } else {
5099     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5100   }
5101 }
5102 
5103 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5104   if (reachable(src)) {
5105     vxorpd(dst, nds, as_Address(src), vector_len);
5106   } else {
5107     lea(rscratch1, src);
5108     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5109   }
5110 }
5111 
5112 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5113   if (reachable(src)) {
5114     vxorps(dst, nds, as_Address(src), vector_len);
5115   } else {
5116     lea(rscratch1, src);
5117     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5118   }
5119 }
5120 
5121 
5122 //////////////////////////////////////////////////////////////////////////////////
5123 #if INCLUDE_ALL_GCS
5124 
5125 void MacroAssembler::g1_write_barrier_pre(Register obj,
5126                                           Register pre_val,
5127                                           Register thread,
5128                                           Register tmp,
5129                                           bool tosca_live,
5130                                           bool expand_call) {
5131 
5132   // If expand_call is true then we expand the call_VM_leaf macro
5133   // directly to skip generating the check by
5134   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5135 
5136 #ifdef _LP64
5137   assert(thread == r15_thread, "must be");
5138 #endif // _LP64
5139 
5140   Label done;
5141   Label runtime;
5142 
5143   assert(pre_val != noreg, "check this code");
5144 
5145   if (obj != noreg) {
5146     assert_different_registers(obj, pre_val, tmp);
5147     assert(pre_val != rax, "check this code");
5148   }
5149 
5150   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5151                                        SATBMarkQueue::byte_offset_of_active()));
5152   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5153                                        SATBMarkQueue::byte_offset_of_index()));
5154   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5155                                        SATBMarkQueue::byte_offset_of_buf()));
5156 
5157 
5158   // Is marking active?
5159   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5160     cmpl(in_progress, 0);
5161   } else {
5162     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5163     cmpb(in_progress, 0);
5164   }
5165   jcc(Assembler::equal, done);
5166 
5167   // Do we need to load the previous value?
5168   if (obj != noreg) {
5169     load_heap_oop(pre_val, Address(obj, 0));
5170   }
5171 
5172   // Is the previous value null?
5173   cmpptr(pre_val, (int32_t) NULL_WORD);
5174   jcc(Assembler::equal, done);
5175 
5176   // Can we store original value in the thread's buffer?
5177   // Is index == 0?
5178   // (The index field is typed as size_t.)
5179 
5180   movptr(tmp, index);                   // tmp := *index_adr
5181   cmpptr(tmp, 0);                       // tmp == 0?
5182   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5183 
5184   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5185   movptr(index, tmp);                   // *index_adr := tmp
5186   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5187 
5188   // Record the previous value
5189   movptr(Address(tmp, 0), pre_val);
5190   jmp(done);
5191 
5192   bind(runtime);
5193   // save the live input values
5194   if(tosca_live) push(rax);
5195 
5196   if (obj != noreg && obj != rax)
5197     push(obj);
5198 
5199   if (pre_val != rax)
5200     push(pre_val);
5201 
5202   // Calling the runtime using the regular call_VM_leaf mechanism generates
5203   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5204   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5205   //
5206   // If we care generating the pre-barrier without a frame (e.g. in the
5207   // intrinsified Reference.get() routine) then ebp might be pointing to
5208   // the caller frame and so this check will most likely fail at runtime.
5209   //
5210   // Expanding the call directly bypasses the generation of the check.
5211   // So when we do not have have a full interpreter frame on the stack
5212   // expand_call should be passed true.
5213 
5214   NOT_LP64( push(thread); )
5215 
5216   if (expand_call) {
5217     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5218     pass_arg1(this, thread);
5219     pass_arg0(this, pre_val);
5220     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5221   } else {
5222     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5223   }
5224 
5225   NOT_LP64( pop(thread); )
5226 
5227   // save the live input values
5228   if (pre_val != rax)
5229     pop(pre_val);
5230 
5231   if (obj != noreg && obj != rax)
5232     pop(obj);
5233 
5234   if(tosca_live) pop(rax);
5235 
5236   bind(done);
5237 }
5238 
5239 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5240                                            Register new_val,
5241                                            Register thread,
5242                                            Register tmp,
5243                                            Register tmp2) {
5244 #ifdef _LP64
5245   assert(thread == r15_thread, "must be");
5246 #endif // _LP64
5247 
5248   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5249                                        DirtyCardQueue::byte_offset_of_index()));
5250   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5251                                        DirtyCardQueue::byte_offset_of_buf()));
5252 
5253   CardTableModRefBS* ct =
5254     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5255   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5256 
5257   Label done;
5258   Label runtime;
5259 
5260   // Does store cross heap regions?
5261 
5262   movptr(tmp, store_addr);
5263   xorptr(tmp, new_val);
5264   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5265   jcc(Assembler::equal, done);
5266 
5267   // crosses regions, storing NULL?
5268 
5269   cmpptr(new_val, (int32_t) NULL_WORD);
5270   jcc(Assembler::equal, done);
5271 
5272   // storing region crossing non-NULL, is card already dirty?
5273 
5274   const Register card_addr = tmp;
5275   const Register cardtable = tmp2;
5276 
5277   movptr(card_addr, store_addr);
5278   shrptr(card_addr, CardTableModRefBS::card_shift);
5279   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5280   // a valid address and therefore is not properly handled by the relocation code.
5281   movptr(cardtable, (intptr_t)ct->byte_map_base);
5282   addptr(card_addr, cardtable);
5283 
5284   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5285   jcc(Assembler::equal, done);
5286 
5287   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5288   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5289   jcc(Assembler::equal, done);
5290 
5291 
5292   // storing a region crossing, non-NULL oop, card is clean.
5293   // dirty card and log.
5294 
5295   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5296 
5297   cmpl(queue_index, 0);
5298   jcc(Assembler::equal, runtime);
5299   subl(queue_index, wordSize);
5300   movptr(tmp2, buffer);
5301 #ifdef _LP64
5302   movslq(rscratch1, queue_index);
5303   addq(tmp2, rscratch1);
5304   movq(Address(tmp2, 0), card_addr);
5305 #else
5306   addl(tmp2, queue_index);
5307   movl(Address(tmp2, 0), card_addr);
5308 #endif
5309   jmp(done);
5310 
5311   bind(runtime);
5312   // save the live input values
5313   push(store_addr);
5314   push(new_val);
5315 #ifdef _LP64
5316   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5317 #else
5318   push(thread);
5319   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5320   pop(thread);
5321 #endif
5322   pop(new_val);
5323   pop(store_addr);
5324 
5325   bind(done);
5326 }
5327 
5328 #endif // INCLUDE_ALL_GCS
5329 //////////////////////////////////////////////////////////////////////////////////
5330 
5331 
5332 void MacroAssembler::store_check(Register obj, Address dst) {
5333   store_check(obj);
5334 }
5335 
5336 void MacroAssembler::store_check(Register obj) {
5337   // Does a store check for the oop in register obj. The content of
5338   // register obj is destroyed afterwards.
5339   BarrierSet* bs = Universe::heap()->barrier_set();
5340   assert(bs->kind() == BarrierSet::CardTableForRS ||
5341          bs->kind() == BarrierSet::CardTableExtension,
5342          "Wrong barrier set kind");
5343 
5344   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5345   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5346 
5347   shrptr(obj, CardTableModRefBS::card_shift);
5348 
5349   Address card_addr;
5350 
5351   // The calculation for byte_map_base is as follows:
5352   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5353   // So this essentially converts an address to a displacement and it will
5354   // never need to be relocated. On 64bit however the value may be too
5355   // large for a 32bit displacement.
5356   intptr_t disp = (intptr_t) ct->byte_map_base;
5357   if (is_simm32(disp)) {
5358     card_addr = Address(noreg, obj, Address::times_1, disp);
5359   } else {
5360     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5361     // displacement and done in a single instruction given favorable mapping and a
5362     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5363     // entry and that entry is not properly handled by the relocation code.
5364     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5365     Address index(noreg, obj, Address::times_1);
5366     card_addr = as_Address(ArrayAddress(cardtable, index));
5367   }
5368 
5369   int dirty = CardTableModRefBS::dirty_card_val();
5370   if (UseCondCardMark) {
5371     Label L_already_dirty;
5372     if (UseConcMarkSweepGC) {
5373       membar(Assembler::StoreLoad);
5374     }
5375     cmpb(card_addr, dirty);
5376     jcc(Assembler::equal, L_already_dirty);
5377     movb(card_addr, dirty);
5378     bind(L_already_dirty);
5379   } else {
5380     movb(card_addr, dirty);
5381   }
5382 }
5383 
5384 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5385   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5386 }
5387 
5388 // Force generation of a 4 byte immediate value even if it fits into 8bit
5389 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5390   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5391 }
5392 
5393 void MacroAssembler::subptr(Register dst, Register src) {
5394   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5395 }
5396 
5397 // C++ bool manipulation
5398 void MacroAssembler::testbool(Register dst) {
5399   if(sizeof(bool) == 1)
5400     testb(dst, 0xff);
5401   else if(sizeof(bool) == 2) {
5402     // testw implementation needed for two byte bools
5403     ShouldNotReachHere();
5404   } else if(sizeof(bool) == 4)
5405     testl(dst, dst);
5406   else
5407     // unsupported
5408     ShouldNotReachHere();
5409 }
5410 
5411 void MacroAssembler::testptr(Register dst, Register src) {
5412   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5413 }
5414 
5415 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5416 void MacroAssembler::tlab_allocate(Register obj,
5417                                    Register var_size_in_bytes,
5418                                    int con_size_in_bytes,
5419                                    Register t1,
5420                                    Register t2,
5421                                    Label& slow_case) {
5422   assert_different_registers(obj, t1, t2);
5423   assert_different_registers(obj, var_size_in_bytes, t1);
5424   Register end = t2;
5425   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5426 
5427   verify_tlab();
5428 
5429   NOT_LP64(get_thread(thread));
5430 
5431   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5432   if (var_size_in_bytes == noreg) {
5433     lea(end, Address(obj, con_size_in_bytes));
5434   } else {
5435     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5436   }
5437   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5438   jcc(Assembler::above, slow_case);
5439 
5440   // update the tlab top pointer
5441   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5442 
5443   // recover var_size_in_bytes if necessary
5444   if (var_size_in_bytes == end) {
5445     subptr(var_size_in_bytes, obj);
5446   }
5447   verify_tlab();
5448 }
5449 
5450 // Preserves rbx, and rdx.
5451 Register MacroAssembler::tlab_refill(Label& retry,
5452                                      Label& try_eden,
5453                                      Label& slow_case) {
5454   Register top = rax;
5455   Register t1  = rcx; // object size
5456   Register t2  = rsi;
5457   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5458   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5459   Label do_refill, discard_tlab;
5460 
5461   if (!Universe::heap()->supports_inline_contig_alloc()) {
5462     // No allocation in the shared eden.
5463     jmp(slow_case);
5464   }
5465 
5466   NOT_LP64(get_thread(thread_reg));
5467 
5468   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5469   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5470 
5471   // calculate amount of free space
5472   subptr(t1, top);
5473   shrptr(t1, LogHeapWordSize);
5474 
5475   // Retain tlab and allocate object in shared space if
5476   // the amount free in the tlab is too large to discard.
5477   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5478   jcc(Assembler::lessEqual, discard_tlab);
5479 
5480   // Retain
5481   // %%% yuck as movptr...
5482   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5483   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5484   if (TLABStats) {
5485     // increment number of slow_allocations
5486     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5487   }
5488   jmp(try_eden);
5489 
5490   bind(discard_tlab);
5491   if (TLABStats) {
5492     // increment number of refills
5493     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5494     // accumulate wastage -- t1 is amount free in tlab
5495     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5496   }
5497 
5498   // if tlab is currently allocated (top or end != null) then
5499   // fill [top, end + alignment_reserve) with array object
5500   testptr(top, top);
5501   jcc(Assembler::zero, do_refill);
5502 
5503   // set up the mark word
5504   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5505   // set the length to the remaining space
5506   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5507   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5508   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5509   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5510   // set klass to intArrayKlass
5511   // dubious reloc why not an oop reloc?
5512   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5513   // store klass last.  concurrent gcs assumes klass length is valid if
5514   // klass field is not null.
5515   store_klass(top, t1);
5516 
5517   movptr(t1, top);
5518   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5519   incr_allocated_bytes(thread_reg, t1, 0);
5520 
5521   // refill the tlab with an eden allocation
5522   bind(do_refill);
5523   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5524   shlptr(t1, LogHeapWordSize);
5525   // allocate new tlab, address returned in top
5526   eden_allocate(top, t1, 0, t2, slow_case);
5527 
5528   // Check that t1 was preserved in eden_allocate.
5529 #ifdef ASSERT
5530   if (UseTLAB) {
5531     Label ok;
5532     Register tsize = rsi;
5533     assert_different_registers(tsize, thread_reg, t1);
5534     push(tsize);
5535     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5536     shlptr(tsize, LogHeapWordSize);
5537     cmpptr(t1, tsize);
5538     jcc(Assembler::equal, ok);
5539     STOP("assert(t1 != tlab size)");
5540     should_not_reach_here();
5541 
5542     bind(ok);
5543     pop(tsize);
5544   }
5545 #endif
5546   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5547   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5548   addptr(top, t1);
5549   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5550   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5551 
5552   if (ZeroTLAB) {
5553     // This is a fast TLAB refill, therefore the GC is not notified of it.
5554     // So compiled code must fill the new TLAB with zeroes.
5555     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5556     zero_memory(top, t1, 0, t2);
5557   }
5558 
5559   verify_tlab();
5560   jmp(retry);
5561 
5562   return thread_reg; // for use by caller
5563 }
5564 
5565 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5566 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5567   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5568   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5569   Label done;
5570 
5571   testptr(length_in_bytes, length_in_bytes);
5572   jcc(Assembler::zero, done);
5573 
5574   // initialize topmost word, divide index by 2, check if odd and test if zero
5575   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5576 #ifdef ASSERT
5577   {
5578     Label L;
5579     testptr(length_in_bytes, BytesPerWord - 1);
5580     jcc(Assembler::zero, L);
5581     stop("length must be a multiple of BytesPerWord");
5582     bind(L);
5583   }
5584 #endif
5585   Register index = length_in_bytes;
5586   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5587   if (UseIncDec) {
5588     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5589   } else {
5590     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5591     shrptr(index, 1);
5592   }
5593 #ifndef _LP64
5594   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5595   {
5596     Label even;
5597     // note: if index was a multiple of 8, then it cannot
5598     //       be 0 now otherwise it must have been 0 before
5599     //       => if it is even, we don't need to check for 0 again
5600     jcc(Assembler::carryClear, even);
5601     // clear topmost word (no jump would be needed if conditional assignment worked here)
5602     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5603     // index could be 0 now, must check again
5604     jcc(Assembler::zero, done);
5605     bind(even);
5606   }
5607 #endif // !_LP64
5608   // initialize remaining object fields: index is a multiple of 2 now
5609   {
5610     Label loop;
5611     bind(loop);
5612     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5613     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5614     decrement(index);
5615     jcc(Assembler::notZero, loop);
5616   }
5617 
5618   bind(done);
5619 }
5620 
5621 void MacroAssembler::incr_allocated_bytes(Register thread,
5622                                           Register var_size_in_bytes,
5623                                           int con_size_in_bytes,
5624                                           Register t1) {
5625   if (!thread->is_valid()) {
5626 #ifdef _LP64
5627     thread = r15_thread;
5628 #else
5629     assert(t1->is_valid(), "need temp reg");
5630     thread = t1;
5631     get_thread(thread);
5632 #endif
5633   }
5634 
5635 #ifdef _LP64
5636   if (var_size_in_bytes->is_valid()) {
5637     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5638   } else {
5639     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5640   }
5641 #else
5642   if (var_size_in_bytes->is_valid()) {
5643     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5644   } else {
5645     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5646   }
5647   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5648 #endif
5649 }
5650 
5651 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5652   pusha();
5653 
5654   // if we are coming from c1, xmm registers may be live
5655   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5656   if (UseAVX > 2) {
5657     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5658   }
5659 
5660   if (UseSSE == 1)  {
5661     subptr(rsp, sizeof(jdouble)*8);
5662     for (int n = 0; n < 8; n++) {
5663       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5664     }
5665   } else if (UseSSE >= 2)  {
5666     if (UseAVX > 2) {
5667       push(rbx);
5668       movl(rbx, 0xffff);
5669       kmovwl(k1, rbx);
5670       pop(rbx);
5671     }
5672 #ifdef COMPILER2
5673     if (MaxVectorSize > 16) {
5674       if(UseAVX > 2) {
5675         // Save upper half of ZMM registers
5676         subptr(rsp, 32*num_xmm_regs);
5677         for (int n = 0; n < num_xmm_regs; n++) {
5678           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
5679         }
5680       }
5681       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5682       // Save upper half of YMM registers
5683       subptr(rsp, 16*num_xmm_regs);
5684       for (int n = 0; n < num_xmm_regs; n++) {
5685         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
5686       }
5687     }
5688 #endif
5689     // Save whole 128bit (16 bytes) XMM registers
5690     subptr(rsp, 16*num_xmm_regs);
5691 #ifdef _LP64
5692     if (VM_Version::supports_evex()) {
5693       for (int n = 0; n < num_xmm_regs; n++) {
5694         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
5695       }
5696     } else {
5697       for (int n = 0; n < num_xmm_regs; n++) {
5698         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5699       }
5700     }
5701 #else
5702     for (int n = 0; n < num_xmm_regs; n++) {
5703       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5704     }
5705 #endif
5706   }
5707 
5708   // Preserve registers across runtime call
5709   int incoming_argument_and_return_value_offset = -1;
5710   if (num_fpu_regs_in_use > 1) {
5711     // Must preserve all other FPU regs (could alternatively convert
5712     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5713     // FPU state, but can not trust C compiler)
5714     NEEDS_CLEANUP;
5715     // NOTE that in this case we also push the incoming argument(s) to
5716     // the stack and restore it later; we also use this stack slot to
5717     // hold the return value from dsin, dcos etc.
5718     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5719       subptr(rsp, sizeof(jdouble));
5720       fstp_d(Address(rsp, 0));
5721     }
5722     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5723     for (int i = nb_args-1; i >= 0; i--) {
5724       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5725     }
5726   }
5727 
5728   subptr(rsp, nb_args*sizeof(jdouble));
5729   for (int i = 0; i < nb_args; i++) {
5730     fstp_d(Address(rsp, i*sizeof(jdouble)));
5731   }
5732 
5733 #ifdef _LP64
5734   if (nb_args > 0) {
5735     movdbl(xmm0, Address(rsp, 0));
5736   }
5737   if (nb_args > 1) {
5738     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5739   }
5740   assert(nb_args <= 2, "unsupported number of args");
5741 #endif // _LP64
5742 
5743   // NOTE: we must not use call_VM_leaf here because that requires a
5744   // complete interpreter frame in debug mode -- same bug as 4387334
5745   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5746   // do proper 64bit abi
5747 
5748   NEEDS_CLEANUP;
5749   // Need to add stack banging before this runtime call if it needs to
5750   // be taken; however, there is no generic stack banging routine at
5751   // the MacroAssembler level
5752 
5753   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5754 
5755 #ifdef _LP64
5756   movsd(Address(rsp, 0), xmm0);
5757   fld_d(Address(rsp, 0));
5758 #endif // _LP64
5759   addptr(rsp, sizeof(jdouble)*nb_args);
5760   if (num_fpu_regs_in_use > 1) {
5761     // Must save return value to stack and then restore entire FPU
5762     // stack except incoming arguments
5763     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5764     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5765       fld_d(Address(rsp, 0));
5766       addptr(rsp, sizeof(jdouble));
5767     }
5768     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5769     addptr(rsp, sizeof(jdouble)*nb_args);
5770   }
5771 
5772   if (UseSSE == 1)  {
5773     for (int n = 0; n < 8; n++) {
5774       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5775     }
5776     addptr(rsp, sizeof(jdouble)*8);
5777   } else if (UseSSE >= 2)  {
5778     // Restore whole 128bit (16 bytes) XMM registers
5779 #ifdef _LP64
5780   if (VM_Version::supports_evex()) {
5781     for (int n = 0; n < num_xmm_regs; n++) {
5782       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
5783     }
5784   } else {
5785     for (int n = 0; n < num_xmm_regs; n++) {
5786       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5787     }
5788   }
5789 #else
5790   for (int n = 0; n < num_xmm_regs; n++) {
5791     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5792   }
5793 #endif
5794     addptr(rsp, 16*num_xmm_regs);
5795 
5796 #ifdef COMPILER2
5797     if (MaxVectorSize > 16) {
5798       // Restore upper half of YMM registers.
5799       for (int n = 0; n < num_xmm_regs; n++) {
5800         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
5801       }
5802       addptr(rsp, 16*num_xmm_regs);
5803       if(UseAVX > 2) {
5804         for (int n = 0; n < num_xmm_regs; n++) {
5805           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
5806         }
5807         addptr(rsp, 32*num_xmm_regs);
5808       }
5809     }
5810 #endif
5811   }
5812   popa();
5813 }
5814 
5815 static const double     pi_4 =  0.7853981633974483;
5816 
5817 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5818   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5819   // was attempted in this code; unfortunately it appears that the
5820   // switch to 80-bit precision and back causes this to be
5821   // unprofitable compared with simply performing a runtime call if
5822   // the argument is out of the (-pi/4, pi/4) range.
5823 
5824   Register tmp = noreg;
5825   if (!VM_Version::supports_cmov()) {
5826     // fcmp needs a temporary so preserve rbx,
5827     tmp = rbx;
5828     push(tmp);
5829   }
5830 
5831   Label slow_case, done;
5832   if (trig == 't') {
5833     ExternalAddress pi4_adr = (address)&pi_4;
5834     if (reachable(pi4_adr)) {
5835       // x ?<= pi/4
5836       fld_d(pi4_adr);
5837       fld_s(1);                // Stack:  X  PI/4  X
5838       fabs();                  // Stack: |X| PI/4  X
5839       fcmp(tmp);
5840       jcc(Assembler::above, slow_case);
5841 
5842       // fastest case: -pi/4 <= x <= pi/4
5843       ftan();
5844 
5845       jmp(done);
5846     }
5847   }
5848   // slow case: runtime call
5849   bind(slow_case);
5850 
5851   switch(trig) {
5852   case 's':
5853     {
5854       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
5855     }
5856     break;
5857   case 'c':
5858     {
5859       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
5860     }
5861     break;
5862   case 't':
5863     {
5864       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
5865     }
5866     break;
5867   default:
5868     assert(false, "bad intrinsic");
5869     break;
5870   }
5871 
5872   // Come here with result in F-TOS
5873   bind(done);
5874 
5875   if (tmp != noreg) {
5876     pop(tmp);
5877   }
5878 }
5879 
5880 // Look up the method for a megamorphic invokeinterface call.
5881 // The target method is determined by <intf_klass, itable_index>.
5882 // The receiver klass is in recv_klass.
5883 // On success, the result will be in method_result, and execution falls through.
5884 // On failure, execution transfers to the given label.
5885 void MacroAssembler::lookup_interface_method(Register recv_klass,
5886                                              Register intf_klass,
5887                                              RegisterOrConstant itable_index,
5888                                              Register method_result,
5889                                              Register scan_temp,
5890                                              Label& L_no_such_interface) {
5891   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5892   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5893          "caller must use same register for non-constant itable index as for method");
5894 
5895   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5896   int vtable_base = in_bytes(Klass::vtable_start_offset());
5897   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5898   int scan_step   = itableOffsetEntry::size() * wordSize;
5899   int vte_size    = vtableEntry::size_in_bytes();
5900   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5901   assert(vte_size == wordSize, "else adjust times_vte_scale");
5902 
5903   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5904 
5905   // %%% Could store the aligned, prescaled offset in the klassoop.
5906   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5907 
5908   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5909   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5910   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5911 
5912   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5913   //   if (scan->interface() == intf) {
5914   //     result = (klass + scan->offset() + itable_index);
5915   //   }
5916   // }
5917   Label search, found_method;
5918 
5919   for (int peel = 1; peel >= 0; peel--) {
5920     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5921     cmpptr(intf_klass, method_result);
5922 
5923     if (peel) {
5924       jccb(Assembler::equal, found_method);
5925     } else {
5926       jccb(Assembler::notEqual, search);
5927       // (invert the test to fall through to found_method...)
5928     }
5929 
5930     if (!peel)  break;
5931 
5932     bind(search);
5933 
5934     // Check that the previous entry is non-null.  A null entry means that
5935     // the receiver class doesn't implement the interface, and wasn't the
5936     // same as when the caller was compiled.
5937     testptr(method_result, method_result);
5938     jcc(Assembler::zero, L_no_such_interface);
5939     addptr(scan_temp, scan_step);
5940   }
5941 
5942   bind(found_method);
5943 
5944   // Got a hit.
5945   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5946   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5947 }
5948 
5949 
5950 // virtual method calling
5951 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5952                                            RegisterOrConstant vtable_index,
5953                                            Register method_result) {
5954   const int base = in_bytes(Klass::vtable_start_offset());
5955   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5956   Address vtable_entry_addr(recv_klass,
5957                             vtable_index, Address::times_ptr,
5958                             base + vtableEntry::method_offset_in_bytes());
5959   movptr(method_result, vtable_entry_addr);
5960 }
5961 
5962 
5963 void MacroAssembler::check_klass_subtype(Register sub_klass,
5964                            Register super_klass,
5965                            Register temp_reg,
5966                            Label& L_success) {
5967   Label L_failure;
5968   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5969   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5970   bind(L_failure);
5971 }
5972 
5973 
5974 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5975                                                    Register super_klass,
5976                                                    Register temp_reg,
5977                                                    Label* L_success,
5978                                                    Label* L_failure,
5979                                                    Label* L_slow_path,
5980                                         RegisterOrConstant super_check_offset) {
5981   assert_different_registers(sub_klass, super_klass, temp_reg);
5982   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5983   if (super_check_offset.is_register()) {
5984     assert_different_registers(sub_klass, super_klass,
5985                                super_check_offset.as_register());
5986   } else if (must_load_sco) {
5987     assert(temp_reg != noreg, "supply either a temp or a register offset");
5988   }
5989 
5990   Label L_fallthrough;
5991   int label_nulls = 0;
5992   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5993   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5994   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5995   assert(label_nulls <= 1, "at most one NULL in the batch");
5996 
5997   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5998   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5999   Address super_check_offset_addr(super_klass, sco_offset);
6000 
6001   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
6002   // range of a jccb.  If this routine grows larger, reconsider at
6003   // least some of these.
6004 #define local_jcc(assembler_cond, label)                                \
6005   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
6006   else                             jcc( assembler_cond, label) /*omit semi*/
6007 
6008   // Hacked jmp, which may only be used just before L_fallthrough.
6009 #define final_jmp(label)                                                \
6010   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
6011   else                            jmp(label)                /*omit semi*/
6012 
6013   // If the pointers are equal, we are done (e.g., String[] elements).
6014   // This self-check enables sharing of secondary supertype arrays among
6015   // non-primary types such as array-of-interface.  Otherwise, each such
6016   // type would need its own customized SSA.
6017   // We move this check to the front of the fast path because many
6018   // type checks are in fact trivially successful in this manner,
6019   // so we get a nicely predicted branch right at the start of the check.
6020   cmpptr(sub_klass, super_klass);
6021   local_jcc(Assembler::equal, *L_success);
6022 
6023   // Check the supertype display:
6024   if (must_load_sco) {
6025     // Positive movl does right thing on LP64.
6026     movl(temp_reg, super_check_offset_addr);
6027     super_check_offset = RegisterOrConstant(temp_reg);
6028   }
6029   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
6030   cmpptr(super_klass, super_check_addr); // load displayed supertype
6031 
6032   // This check has worked decisively for primary supers.
6033   // Secondary supers are sought in the super_cache ('super_cache_addr').
6034   // (Secondary supers are interfaces and very deeply nested subtypes.)
6035   // This works in the same check above because of a tricky aliasing
6036   // between the super_cache and the primary super display elements.
6037   // (The 'super_check_addr' can address either, as the case requires.)
6038   // Note that the cache is updated below if it does not help us find
6039   // what we need immediately.
6040   // So if it was a primary super, we can just fail immediately.
6041   // Otherwise, it's the slow path for us (no success at this point).
6042 
6043   if (super_check_offset.is_register()) {
6044     local_jcc(Assembler::equal, *L_success);
6045     cmpl(super_check_offset.as_register(), sc_offset);
6046     if (L_failure == &L_fallthrough) {
6047       local_jcc(Assembler::equal, *L_slow_path);
6048     } else {
6049       local_jcc(Assembler::notEqual, *L_failure);
6050       final_jmp(*L_slow_path);
6051     }
6052   } else if (super_check_offset.as_constant() == sc_offset) {
6053     // Need a slow path; fast failure is impossible.
6054     if (L_slow_path == &L_fallthrough) {
6055       local_jcc(Assembler::equal, *L_success);
6056     } else {
6057       local_jcc(Assembler::notEqual, *L_slow_path);
6058       final_jmp(*L_success);
6059     }
6060   } else {
6061     // No slow path; it's a fast decision.
6062     if (L_failure == &L_fallthrough) {
6063       local_jcc(Assembler::equal, *L_success);
6064     } else {
6065       local_jcc(Assembler::notEqual, *L_failure);
6066       final_jmp(*L_success);
6067     }
6068   }
6069 
6070   bind(L_fallthrough);
6071 
6072 #undef local_jcc
6073 #undef final_jmp
6074 }
6075 
6076 
6077 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
6078                                                    Register super_klass,
6079                                                    Register temp_reg,
6080                                                    Register temp2_reg,
6081                                                    Label* L_success,
6082                                                    Label* L_failure,
6083                                                    bool set_cond_codes) {
6084   assert_different_registers(sub_klass, super_klass, temp_reg);
6085   if (temp2_reg != noreg)
6086     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
6087 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
6088 
6089   Label L_fallthrough;
6090   int label_nulls = 0;
6091   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
6092   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
6093   assert(label_nulls <= 1, "at most one NULL in the batch");
6094 
6095   // a couple of useful fields in sub_klass:
6096   int ss_offset = in_bytes(Klass::secondary_supers_offset());
6097   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
6098   Address secondary_supers_addr(sub_klass, ss_offset);
6099   Address super_cache_addr(     sub_klass, sc_offset);
6100 
6101   // Do a linear scan of the secondary super-klass chain.
6102   // This code is rarely used, so simplicity is a virtue here.
6103   // The repne_scan instruction uses fixed registers, which we must spill.
6104   // Don't worry too much about pre-existing connections with the input regs.
6105 
6106   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6107   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6108 
6109   // Get super_klass value into rax (even if it was in rdi or rcx).
6110   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6111   if (super_klass != rax || UseCompressedOops) {
6112     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6113     mov(rax, super_klass);
6114   }
6115   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6116   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6117 
6118 #ifndef PRODUCT
6119   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6120   ExternalAddress pst_counter_addr((address) pst_counter);
6121   NOT_LP64(  incrementl(pst_counter_addr) );
6122   LP64_ONLY( lea(rcx, pst_counter_addr) );
6123   LP64_ONLY( incrementl(Address(rcx, 0)) );
6124 #endif //PRODUCT
6125 
6126   // We will consult the secondary-super array.
6127   movptr(rdi, secondary_supers_addr);
6128   // Load the array length.  (Positive movl does right thing on LP64.)
6129   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6130   // Skip to start of data.
6131   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6132 
6133   // Scan RCX words at [RDI] for an occurrence of RAX.
6134   // Set NZ/Z based on last compare.
6135   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6136   // not change flags (only scas instruction which is repeated sets flags).
6137   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6138 
6139     testptr(rax,rax); // Set Z = 0
6140     repne_scan();
6141 
6142   // Unspill the temp. registers:
6143   if (pushed_rdi)  pop(rdi);
6144   if (pushed_rcx)  pop(rcx);
6145   if (pushed_rax)  pop(rax);
6146 
6147   if (set_cond_codes) {
6148     // Special hack for the AD files:  rdi is guaranteed non-zero.
6149     assert(!pushed_rdi, "rdi must be left non-NULL");
6150     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6151   }
6152 
6153   if (L_failure == &L_fallthrough)
6154         jccb(Assembler::notEqual, *L_failure);
6155   else  jcc(Assembler::notEqual, *L_failure);
6156 
6157   // Success.  Cache the super we found and proceed in triumph.
6158   movptr(super_cache_addr, super_klass);
6159 
6160   if (L_success != &L_fallthrough) {
6161     jmp(*L_success);
6162   }
6163 
6164 #undef IS_A_TEMP
6165 
6166   bind(L_fallthrough);
6167 }
6168 
6169 
6170 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6171   if (VM_Version::supports_cmov()) {
6172     cmovl(cc, dst, src);
6173   } else {
6174     Label L;
6175     jccb(negate_condition(cc), L);
6176     movl(dst, src);
6177     bind(L);
6178   }
6179 }
6180 
6181 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6182   if (VM_Version::supports_cmov()) {
6183     cmovl(cc, dst, src);
6184   } else {
6185     Label L;
6186     jccb(negate_condition(cc), L);
6187     movl(dst, src);
6188     bind(L);
6189   }
6190 }
6191 
6192 void MacroAssembler::verify_oop(Register reg, const char* s) {
6193   if (!VerifyOops) return;
6194 
6195   // Pass register number to verify_oop_subroutine
6196   const char* b = NULL;
6197   {
6198     ResourceMark rm;
6199     stringStream ss;
6200     ss.print("verify_oop: %s: %s", reg->name(), s);
6201     b = code_string(ss.as_string());
6202   }
6203   BLOCK_COMMENT("verify_oop {");
6204 #ifdef _LP64
6205   push(rscratch1);                    // save r10, trashed by movptr()
6206 #endif
6207   push(rax);                          // save rax,
6208   push(reg);                          // pass register argument
6209   ExternalAddress buffer((address) b);
6210   // avoid using pushptr, as it modifies scratch registers
6211   // and our contract is not to modify anything
6212   movptr(rax, buffer.addr());
6213   push(rax);
6214   // call indirectly to solve generation ordering problem
6215   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6216   call(rax);
6217   // Caller pops the arguments (oop, message) and restores rax, r10
6218   BLOCK_COMMENT("} verify_oop");
6219 }
6220 
6221 
6222 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6223                                                       Register tmp,
6224                                                       int offset) {
6225   intptr_t value = *delayed_value_addr;
6226   if (value != 0)
6227     return RegisterOrConstant(value + offset);
6228 
6229   // load indirectly to solve generation ordering problem
6230   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6231 
6232 #ifdef ASSERT
6233   { Label L;
6234     testptr(tmp, tmp);
6235     if (WizardMode) {
6236       const char* buf = NULL;
6237       {
6238         ResourceMark rm;
6239         stringStream ss;
6240         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6241         buf = code_string(ss.as_string());
6242       }
6243       jcc(Assembler::notZero, L);
6244       STOP(buf);
6245     } else {
6246       jccb(Assembler::notZero, L);
6247       hlt();
6248     }
6249     bind(L);
6250   }
6251 #endif
6252 
6253   if (offset != 0)
6254     addptr(tmp, offset);
6255 
6256   return RegisterOrConstant(tmp);
6257 }
6258 
6259 
6260 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6261                                          int extra_slot_offset) {
6262   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6263   int stackElementSize = Interpreter::stackElementSize;
6264   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6265 #ifdef ASSERT
6266   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6267   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6268 #endif
6269   Register             scale_reg    = noreg;
6270   Address::ScaleFactor scale_factor = Address::no_scale;
6271   if (arg_slot.is_constant()) {
6272     offset += arg_slot.as_constant() * stackElementSize;
6273   } else {
6274     scale_reg    = arg_slot.as_register();
6275     scale_factor = Address::times(stackElementSize);
6276   }
6277   offset += wordSize;           // return PC is on stack
6278   return Address(rsp, scale_reg, scale_factor, offset);
6279 }
6280 
6281 
6282 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6283   if (!VerifyOops) return;
6284 
6285   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6286   // Pass register number to verify_oop_subroutine
6287   const char* b = NULL;
6288   {
6289     ResourceMark rm;
6290     stringStream ss;
6291     ss.print("verify_oop_addr: %s", s);
6292     b = code_string(ss.as_string());
6293   }
6294 #ifdef _LP64
6295   push(rscratch1);                    // save r10, trashed by movptr()
6296 #endif
6297   push(rax);                          // save rax,
6298   // addr may contain rsp so we will have to adjust it based on the push
6299   // we just did (and on 64 bit we do two pushes)
6300   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6301   // stores rax into addr which is backwards of what was intended.
6302   if (addr.uses(rsp)) {
6303     lea(rax, addr);
6304     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6305   } else {
6306     pushptr(addr);
6307   }
6308 
6309   ExternalAddress buffer((address) b);
6310   // pass msg argument
6311   // avoid using pushptr, as it modifies scratch registers
6312   // and our contract is not to modify anything
6313   movptr(rax, buffer.addr());
6314   push(rax);
6315 
6316   // call indirectly to solve generation ordering problem
6317   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6318   call(rax);
6319   // Caller pops the arguments (addr, message) and restores rax, r10.
6320 }
6321 
6322 void MacroAssembler::verify_tlab() {
6323 #ifdef ASSERT
6324   if (UseTLAB && VerifyOops) {
6325     Label next, ok;
6326     Register t1 = rsi;
6327     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6328 
6329     push(t1);
6330     NOT_LP64(push(thread_reg));
6331     NOT_LP64(get_thread(thread_reg));
6332 
6333     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6334     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6335     jcc(Assembler::aboveEqual, next);
6336     STOP("assert(top >= start)");
6337     should_not_reach_here();
6338 
6339     bind(next);
6340     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6341     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6342     jcc(Assembler::aboveEqual, ok);
6343     STOP("assert(top <= end)");
6344     should_not_reach_here();
6345 
6346     bind(ok);
6347     NOT_LP64(pop(thread_reg));
6348     pop(t1);
6349   }
6350 #endif
6351 }
6352 
6353 class ControlWord {
6354  public:
6355   int32_t _value;
6356 
6357   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6358   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6359   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6360   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6361   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6362   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6363   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6364   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6365 
6366   void print() const {
6367     // rounding control
6368     const char* rc;
6369     switch (rounding_control()) {
6370       case 0: rc = "round near"; break;
6371       case 1: rc = "round down"; break;
6372       case 2: rc = "round up  "; break;
6373       case 3: rc = "chop      "; break;
6374     };
6375     // precision control
6376     const char* pc;
6377     switch (precision_control()) {
6378       case 0: pc = "24 bits "; break;
6379       case 1: pc = "reserved"; break;
6380       case 2: pc = "53 bits "; break;
6381       case 3: pc = "64 bits "; break;
6382     };
6383     // flags
6384     char f[9];
6385     f[0] = ' ';
6386     f[1] = ' ';
6387     f[2] = (precision   ()) ? 'P' : 'p';
6388     f[3] = (underflow   ()) ? 'U' : 'u';
6389     f[4] = (overflow    ()) ? 'O' : 'o';
6390     f[5] = (zero_divide ()) ? 'Z' : 'z';
6391     f[6] = (denormalized()) ? 'D' : 'd';
6392     f[7] = (invalid     ()) ? 'I' : 'i';
6393     f[8] = '\x0';
6394     // output
6395     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6396   }
6397 
6398 };
6399 
6400 class StatusWord {
6401  public:
6402   int32_t _value;
6403 
6404   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6405   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6406   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6407   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6408   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6409   int  top() const                     { return  (_value >> 11) & 7      ; }
6410   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6411   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6412   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6413   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6414   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6415   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6416   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6417   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6418 
6419   void print() const {
6420     // condition codes
6421     char c[5];
6422     c[0] = (C3()) ? '3' : '-';
6423     c[1] = (C2()) ? '2' : '-';
6424     c[2] = (C1()) ? '1' : '-';
6425     c[3] = (C0()) ? '0' : '-';
6426     c[4] = '\x0';
6427     // flags
6428     char f[9];
6429     f[0] = (error_status()) ? 'E' : '-';
6430     f[1] = (stack_fault ()) ? 'S' : '-';
6431     f[2] = (precision   ()) ? 'P' : '-';
6432     f[3] = (underflow   ()) ? 'U' : '-';
6433     f[4] = (overflow    ()) ? 'O' : '-';
6434     f[5] = (zero_divide ()) ? 'Z' : '-';
6435     f[6] = (denormalized()) ? 'D' : '-';
6436     f[7] = (invalid     ()) ? 'I' : '-';
6437     f[8] = '\x0';
6438     // output
6439     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6440   }
6441 
6442 };
6443 
6444 class TagWord {
6445  public:
6446   int32_t _value;
6447 
6448   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6449 
6450   void print() const {
6451     printf("%04x", _value & 0xFFFF);
6452   }
6453 
6454 };
6455 
6456 class FPU_Register {
6457  public:
6458   int32_t _m0;
6459   int32_t _m1;
6460   int16_t _ex;
6461 
6462   bool is_indefinite() const           {
6463     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6464   }
6465 
6466   void print() const {
6467     char  sign = (_ex < 0) ? '-' : '+';
6468     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6469     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6470   };
6471 
6472 };
6473 
6474 class FPU_State {
6475  public:
6476   enum {
6477     register_size       = 10,
6478     number_of_registers =  8,
6479     register_mask       =  7
6480   };
6481 
6482   ControlWord  _control_word;
6483   StatusWord   _status_word;
6484   TagWord      _tag_word;
6485   int32_t      _error_offset;
6486   int32_t      _error_selector;
6487   int32_t      _data_offset;
6488   int32_t      _data_selector;
6489   int8_t       _register[register_size * number_of_registers];
6490 
6491   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6492   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6493 
6494   const char* tag_as_string(int tag) const {
6495     switch (tag) {
6496       case 0: return "valid";
6497       case 1: return "zero";
6498       case 2: return "special";
6499       case 3: return "empty";
6500     }
6501     ShouldNotReachHere();
6502     return NULL;
6503   }
6504 
6505   void print() const {
6506     // print computation registers
6507     { int t = _status_word.top();
6508       for (int i = 0; i < number_of_registers; i++) {
6509         int j = (i - t) & register_mask;
6510         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6511         st(j)->print();
6512         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6513       }
6514     }
6515     printf("\n");
6516     // print control registers
6517     printf("ctrl = "); _control_word.print(); printf("\n");
6518     printf("stat = "); _status_word .print(); printf("\n");
6519     printf("tags = "); _tag_word    .print(); printf("\n");
6520   }
6521 
6522 };
6523 
6524 class Flag_Register {
6525  public:
6526   int32_t _value;
6527 
6528   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6529   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6530   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6531   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6532   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6533   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6534   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6535 
6536   void print() const {
6537     // flags
6538     char f[8];
6539     f[0] = (overflow       ()) ? 'O' : '-';
6540     f[1] = (direction      ()) ? 'D' : '-';
6541     f[2] = (sign           ()) ? 'S' : '-';
6542     f[3] = (zero           ()) ? 'Z' : '-';
6543     f[4] = (auxiliary_carry()) ? 'A' : '-';
6544     f[5] = (parity         ()) ? 'P' : '-';
6545     f[6] = (carry          ()) ? 'C' : '-';
6546     f[7] = '\x0';
6547     // output
6548     printf("%08x  flags = %s", _value, f);
6549   }
6550 
6551 };
6552 
6553 class IU_Register {
6554  public:
6555   int32_t _value;
6556 
6557   void print() const {
6558     printf("%08x  %11d", _value, _value);
6559   }
6560 
6561 };
6562 
6563 class IU_State {
6564  public:
6565   Flag_Register _eflags;
6566   IU_Register   _rdi;
6567   IU_Register   _rsi;
6568   IU_Register   _rbp;
6569   IU_Register   _rsp;
6570   IU_Register   _rbx;
6571   IU_Register   _rdx;
6572   IU_Register   _rcx;
6573   IU_Register   _rax;
6574 
6575   void print() const {
6576     // computation registers
6577     printf("rax,  = "); _rax.print(); printf("\n");
6578     printf("rbx,  = "); _rbx.print(); printf("\n");
6579     printf("rcx  = "); _rcx.print(); printf("\n");
6580     printf("rdx  = "); _rdx.print(); printf("\n");
6581     printf("rdi  = "); _rdi.print(); printf("\n");
6582     printf("rsi  = "); _rsi.print(); printf("\n");
6583     printf("rbp,  = "); _rbp.print(); printf("\n");
6584     printf("rsp  = "); _rsp.print(); printf("\n");
6585     printf("\n");
6586     // control registers
6587     printf("flgs = "); _eflags.print(); printf("\n");
6588   }
6589 };
6590 
6591 
6592 class CPU_State {
6593  public:
6594   FPU_State _fpu_state;
6595   IU_State  _iu_state;
6596 
6597   void print() const {
6598     printf("--------------------------------------------------\n");
6599     _iu_state .print();
6600     printf("\n");
6601     _fpu_state.print();
6602     printf("--------------------------------------------------\n");
6603   }
6604 
6605 };
6606 
6607 
6608 static void _print_CPU_state(CPU_State* state) {
6609   state->print();
6610 };
6611 
6612 
6613 void MacroAssembler::print_CPU_state() {
6614   push_CPU_state();
6615   push(rsp);                // pass CPU state
6616   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6617   addptr(rsp, wordSize);       // discard argument
6618   pop_CPU_state();
6619 }
6620 
6621 
6622 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6623   static int counter = 0;
6624   FPU_State* fs = &state->_fpu_state;
6625   counter++;
6626   // For leaf calls, only verify that the top few elements remain empty.
6627   // We only need 1 empty at the top for C2 code.
6628   if( stack_depth < 0 ) {
6629     if( fs->tag_for_st(7) != 3 ) {
6630       printf("FPR7 not empty\n");
6631       state->print();
6632       assert(false, "error");
6633       return false;
6634     }
6635     return true;                // All other stack states do not matter
6636   }
6637 
6638   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6639          "bad FPU control word");
6640 
6641   // compute stack depth
6642   int i = 0;
6643   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6644   int d = i;
6645   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6646   // verify findings
6647   if (i != FPU_State::number_of_registers) {
6648     // stack not contiguous
6649     printf("%s: stack not contiguous at ST%d\n", s, i);
6650     state->print();
6651     assert(false, "error");
6652     return false;
6653   }
6654   // check if computed stack depth corresponds to expected stack depth
6655   if (stack_depth < 0) {
6656     // expected stack depth is -stack_depth or less
6657     if (d > -stack_depth) {
6658       // too many elements on the stack
6659       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6660       state->print();
6661       assert(false, "error");
6662       return false;
6663     }
6664   } else {
6665     // expected stack depth is stack_depth
6666     if (d != stack_depth) {
6667       // wrong stack depth
6668       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6669       state->print();
6670       assert(false, "error");
6671       return false;
6672     }
6673   }
6674   // everything is cool
6675   return true;
6676 }
6677 
6678 
6679 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6680   if (!VerifyFPU) return;
6681   push_CPU_state();
6682   push(rsp);                // pass CPU state
6683   ExternalAddress msg((address) s);
6684   // pass message string s
6685   pushptr(msg.addr());
6686   push(stack_depth);        // pass stack depth
6687   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6688   addptr(rsp, 3 * wordSize);   // discard arguments
6689   // check for error
6690   { Label L;
6691     testl(rax, rax);
6692     jcc(Assembler::notZero, L);
6693     int3();                  // break if error condition
6694     bind(L);
6695   }
6696   pop_CPU_state();
6697 }
6698 
6699 void MacroAssembler::restore_cpu_control_state_after_jni() {
6700   // Either restore the MXCSR register after returning from the JNI Call
6701   // or verify that it wasn't changed (with -Xcheck:jni flag).
6702   if (VM_Version::supports_sse()) {
6703     if (RestoreMXCSROnJNICalls) {
6704       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6705     } else if (CheckJNICalls) {
6706       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6707     }
6708   }
6709   if (VM_Version::supports_avx()) {
6710     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6711     vzeroupper();
6712   }
6713 
6714 #ifndef _LP64
6715   // Either restore the x87 floating pointer control word after returning
6716   // from the JNI call or verify that it wasn't changed.
6717   if (CheckJNICalls) {
6718     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6719   }
6720 #endif // _LP64
6721 }
6722 
6723 
6724 void MacroAssembler::load_klass(Register dst, Register src) {
6725 #ifdef _LP64
6726   if (UseCompressedClassPointers) {
6727     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6728     decode_klass_not_null(dst);
6729   } else
6730 #endif
6731     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6732 }
6733 
6734 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6735   load_klass(dst, src);
6736   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6737 }
6738 
6739 void MacroAssembler::store_klass(Register dst, Register src) {
6740 #ifdef _LP64
6741   if (UseCompressedClassPointers) {
6742     encode_klass_not_null(src);
6743     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6744   } else
6745 #endif
6746     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6747 }
6748 
6749 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6750 #ifdef _LP64
6751   // FIXME: Must change all places where we try to load the klass.
6752   if (UseCompressedOops) {
6753     movl(dst, src);
6754     decode_heap_oop(dst);
6755   } else
6756 #endif
6757     movptr(dst, src);
6758 }
6759 
6760 // Doesn't do verfication, generates fixed size code
6761 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6762 #ifdef _LP64
6763   if (UseCompressedOops) {
6764     movl(dst, src);
6765     decode_heap_oop_not_null(dst);
6766   } else
6767 #endif
6768     movptr(dst, src);
6769 }
6770 
6771 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6772 #ifdef _LP64
6773   if (UseCompressedOops) {
6774     assert(!dst.uses(src), "not enough registers");
6775     encode_heap_oop(src);
6776     movl(dst, src);
6777   } else
6778 #endif
6779     movptr(dst, src);
6780 }
6781 
6782 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6783   assert_different_registers(src1, tmp);
6784 #ifdef _LP64
6785   if (UseCompressedOops) {
6786     bool did_push = false;
6787     if (tmp == noreg) {
6788       tmp = rax;
6789       push(tmp);
6790       did_push = true;
6791       assert(!src2.uses(rsp), "can't push");
6792     }
6793     load_heap_oop(tmp, src2);
6794     cmpptr(src1, tmp);
6795     if (did_push)  pop(tmp);
6796   } else
6797 #endif
6798     cmpptr(src1, src2);
6799 }
6800 
6801 // Used for storing NULLs.
6802 void MacroAssembler::store_heap_oop_null(Address dst) {
6803 #ifdef _LP64
6804   if (UseCompressedOops) {
6805     movl(dst, (int32_t)NULL_WORD);
6806   } else {
6807     movslq(dst, (int32_t)NULL_WORD);
6808   }
6809 #else
6810   movl(dst, (int32_t)NULL_WORD);
6811 #endif
6812 }
6813 
6814 #ifdef _LP64
6815 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6816   if (UseCompressedClassPointers) {
6817     // Store to klass gap in destination
6818     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6819   }
6820 }
6821 
6822 #ifdef ASSERT
6823 void MacroAssembler::verify_heapbase(const char* msg) {
6824   assert (UseCompressedOops, "should be compressed");
6825   assert (Universe::heap() != NULL, "java heap should be initialized");
6826   if (CheckCompressedOops) {
6827     Label ok;
6828     push(rscratch1); // cmpptr trashes rscratch1
6829     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6830     jcc(Assembler::equal, ok);
6831     STOP(msg);
6832     bind(ok);
6833     pop(rscratch1);
6834   }
6835 }
6836 #endif
6837 
6838 // Algorithm must match oop.inline.hpp encode_heap_oop.
6839 void MacroAssembler::encode_heap_oop(Register r) {
6840 #ifdef ASSERT
6841   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6842 #endif
6843   verify_oop(r, "broken oop in encode_heap_oop");
6844   if (Universe::narrow_oop_base() == NULL) {
6845     if (Universe::narrow_oop_shift() != 0) {
6846       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6847       shrq(r, LogMinObjAlignmentInBytes);
6848     }
6849     return;
6850   }
6851   testq(r, r);
6852   cmovq(Assembler::equal, r, r12_heapbase);
6853   subq(r, r12_heapbase);
6854   shrq(r, LogMinObjAlignmentInBytes);
6855 }
6856 
6857 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6858 #ifdef ASSERT
6859   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6860   if (CheckCompressedOops) {
6861     Label ok;
6862     testq(r, r);
6863     jcc(Assembler::notEqual, ok);
6864     STOP("null oop passed to encode_heap_oop_not_null");
6865     bind(ok);
6866   }
6867 #endif
6868   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6869   if (Universe::narrow_oop_base() != NULL) {
6870     subq(r, r12_heapbase);
6871   }
6872   if (Universe::narrow_oop_shift() != 0) {
6873     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6874     shrq(r, LogMinObjAlignmentInBytes);
6875   }
6876 }
6877 
6878 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6879 #ifdef ASSERT
6880   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6881   if (CheckCompressedOops) {
6882     Label ok;
6883     testq(src, src);
6884     jcc(Assembler::notEqual, ok);
6885     STOP("null oop passed to encode_heap_oop_not_null2");
6886     bind(ok);
6887   }
6888 #endif
6889   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6890   if (dst != src) {
6891     movq(dst, src);
6892   }
6893   if (Universe::narrow_oop_base() != NULL) {
6894     subq(dst, r12_heapbase);
6895   }
6896   if (Universe::narrow_oop_shift() != 0) {
6897     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6898     shrq(dst, LogMinObjAlignmentInBytes);
6899   }
6900 }
6901 
6902 void  MacroAssembler::decode_heap_oop(Register r) {
6903 #ifdef ASSERT
6904   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6905 #endif
6906   if (Universe::narrow_oop_base() == NULL) {
6907     if (Universe::narrow_oop_shift() != 0) {
6908       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6909       shlq(r, LogMinObjAlignmentInBytes);
6910     }
6911   } else {
6912     Label done;
6913     shlq(r, LogMinObjAlignmentInBytes);
6914     jccb(Assembler::equal, done);
6915     addq(r, r12_heapbase);
6916     bind(done);
6917   }
6918   verify_oop(r, "broken oop in decode_heap_oop");
6919 }
6920 
6921 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6922   // Note: it will change flags
6923   assert (UseCompressedOops, "should only be used for compressed headers");
6924   assert (Universe::heap() != NULL, "java heap should be initialized");
6925   // Cannot assert, unverified entry point counts instructions (see .ad file)
6926   // vtableStubs also counts instructions in pd_code_size_limit.
6927   // Also do not verify_oop as this is called by verify_oop.
6928   if (Universe::narrow_oop_shift() != 0) {
6929     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6930     shlq(r, LogMinObjAlignmentInBytes);
6931     if (Universe::narrow_oop_base() != NULL) {
6932       addq(r, r12_heapbase);
6933     }
6934   } else {
6935     assert (Universe::narrow_oop_base() == NULL, "sanity");
6936   }
6937 }
6938 
6939 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6940   // Note: it will change flags
6941   assert (UseCompressedOops, "should only be used for compressed headers");
6942   assert (Universe::heap() != NULL, "java heap should be initialized");
6943   // Cannot assert, unverified entry point counts instructions (see .ad file)
6944   // vtableStubs also counts instructions in pd_code_size_limit.
6945   // Also do not verify_oop as this is called by verify_oop.
6946   if (Universe::narrow_oop_shift() != 0) {
6947     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6948     if (LogMinObjAlignmentInBytes == Address::times_8) {
6949       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6950     } else {
6951       if (dst != src) {
6952         movq(dst, src);
6953       }
6954       shlq(dst, LogMinObjAlignmentInBytes);
6955       if (Universe::narrow_oop_base() != NULL) {
6956         addq(dst, r12_heapbase);
6957       }
6958     }
6959   } else {
6960     assert (Universe::narrow_oop_base() == NULL, "sanity");
6961     if (dst != src) {
6962       movq(dst, src);
6963     }
6964   }
6965 }
6966 
6967 void MacroAssembler::encode_klass_not_null(Register r) {
6968   if (Universe::narrow_klass_base() != NULL) {
6969     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6970     assert(r != r12_heapbase, "Encoding a klass in r12");
6971     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6972     subq(r, r12_heapbase);
6973   }
6974   if (Universe::narrow_klass_shift() != 0) {
6975     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6976     shrq(r, LogKlassAlignmentInBytes);
6977   }
6978   if (Universe::narrow_klass_base() != NULL) {
6979     reinit_heapbase();
6980   }
6981 }
6982 
6983 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6984   if (dst == src) {
6985     encode_klass_not_null(src);
6986   } else {
6987     if (Universe::narrow_klass_base() != NULL) {
6988       mov64(dst, (int64_t)Universe::narrow_klass_base());
6989       negq(dst);
6990       addq(dst, src);
6991     } else {
6992       movptr(dst, src);
6993     }
6994     if (Universe::narrow_klass_shift() != 0) {
6995       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6996       shrq(dst, LogKlassAlignmentInBytes);
6997     }
6998   }
6999 }
7000 
7001 // Function instr_size_for_decode_klass_not_null() counts the instructions
7002 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7003 // when (Universe::heap() != NULL).  Hence, if the instructions they
7004 // generate change, then this method needs to be updated.
7005 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7006   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7007   if (Universe::narrow_klass_base() != NULL) {
7008     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7009     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7010   } else {
7011     // longest load decode klass function, mov64, leaq
7012     return 16;
7013   }
7014 }
7015 
7016 // !!! If the instructions that get generated here change then function
7017 // instr_size_for_decode_klass_not_null() needs to get updated.
7018 void  MacroAssembler::decode_klass_not_null(Register r) {
7019   // Note: it will change flags
7020   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7021   assert(r != r12_heapbase, "Decoding a klass in r12");
7022   // Cannot assert, unverified entry point counts instructions (see .ad file)
7023   // vtableStubs also counts instructions in pd_code_size_limit.
7024   // Also do not verify_oop as this is called by verify_oop.
7025   if (Universe::narrow_klass_shift() != 0) {
7026     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7027     shlq(r, LogKlassAlignmentInBytes);
7028   }
7029   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7030   if (Universe::narrow_klass_base() != NULL) {
7031     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7032     addq(r, r12_heapbase);
7033     reinit_heapbase();
7034   }
7035 }
7036 
7037 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7038   // Note: it will change flags
7039   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7040   if (dst == src) {
7041     decode_klass_not_null(dst);
7042   } else {
7043     // Cannot assert, unverified entry point counts instructions (see .ad file)
7044     // vtableStubs also counts instructions in pd_code_size_limit.
7045     // Also do not verify_oop as this is called by verify_oop.
7046     mov64(dst, (int64_t)Universe::narrow_klass_base());
7047     if (Universe::narrow_klass_shift() != 0) {
7048       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7049       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7050       leaq(dst, Address(dst, src, Address::times_8, 0));
7051     } else {
7052       addq(dst, src);
7053     }
7054   }
7055 }
7056 
7057 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7058   assert (UseCompressedOops, "should only be used for compressed headers");
7059   assert (Universe::heap() != NULL, "java heap should be initialized");
7060   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7061   int oop_index = oop_recorder()->find_index(obj);
7062   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7063   mov_narrow_oop(dst, oop_index, rspec);
7064 }
7065 
7066 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7067   assert (UseCompressedOops, "should only be used for compressed headers");
7068   assert (Universe::heap() != NULL, "java heap should be initialized");
7069   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7070   int oop_index = oop_recorder()->find_index(obj);
7071   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7072   mov_narrow_oop(dst, oop_index, rspec);
7073 }
7074 
7075 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7076   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7077   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7078   int klass_index = oop_recorder()->find_index(k);
7079   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7080   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7081 }
7082 
7083 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7084   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7085   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7086   int klass_index = oop_recorder()->find_index(k);
7087   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7088   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7089 }
7090 
7091 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7092   assert (UseCompressedOops, "should only be used for compressed headers");
7093   assert (Universe::heap() != NULL, "java heap should be initialized");
7094   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7095   int oop_index = oop_recorder()->find_index(obj);
7096   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7097   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7098 }
7099 
7100 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7101   assert (UseCompressedOops, "should only be used for compressed headers");
7102   assert (Universe::heap() != NULL, "java heap should be initialized");
7103   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7104   int oop_index = oop_recorder()->find_index(obj);
7105   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7106   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7107 }
7108 
7109 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7110   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7111   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7112   int klass_index = oop_recorder()->find_index(k);
7113   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7114   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7115 }
7116 
7117 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7118   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7119   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7120   int klass_index = oop_recorder()->find_index(k);
7121   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7122   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7123 }
7124 
7125 void MacroAssembler::reinit_heapbase() {
7126   if (UseCompressedOops || UseCompressedClassPointers) {
7127     if (Universe::heap() != NULL) {
7128       if (Universe::narrow_oop_base() == NULL) {
7129         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7130       } else {
7131         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7132       }
7133     } else {
7134       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7135     }
7136   }
7137 }
7138 
7139 #endif // _LP64
7140 
7141 
7142 // C2 compiled method's prolog code.
7143 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7144 
7145   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7146   // NativeJump::patch_verified_entry will be able to patch out the entry
7147   // code safely. The push to verify stack depth is ok at 5 bytes,
7148   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7149   // stack bang then we must use the 6 byte frame allocation even if
7150   // we have no frame. :-(
7151   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7152 
7153   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7154   // Remove word for return addr
7155   framesize -= wordSize;
7156   stack_bang_size -= wordSize;
7157 
7158   // Calls to C2R adapters often do not accept exceptional returns.
7159   // We require that their callers must bang for them.  But be careful, because
7160   // some VM calls (such as call site linkage) can use several kilobytes of
7161   // stack.  But the stack safety zone should account for that.
7162   // See bugs 4446381, 4468289, 4497237.
7163   if (stack_bang_size > 0) {
7164     generate_stack_overflow_check(stack_bang_size);
7165 
7166     // We always push rbp, so that on return to interpreter rbp, will be
7167     // restored correctly and we can correct the stack.
7168     push(rbp);
7169     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7170     if (PreserveFramePointer) {
7171       mov(rbp, rsp);
7172     }
7173     // Remove word for ebp
7174     framesize -= wordSize;
7175 
7176     // Create frame
7177     if (framesize) {
7178       subptr(rsp, framesize);
7179     }
7180   } else {
7181     // Create frame (force generation of a 4 byte immediate value)
7182     subptr_imm32(rsp, framesize);
7183 
7184     // Save RBP register now.
7185     framesize -= wordSize;
7186     movptr(Address(rsp, framesize), rbp);
7187     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7188     if (PreserveFramePointer) {
7189       movptr(rbp, rsp);
7190       if (framesize > 0) {
7191         addptr(rbp, framesize);
7192       }
7193     }
7194   }
7195 
7196   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7197     framesize -= wordSize;
7198     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7199   }
7200 
7201 #ifndef _LP64
7202   // If method sets FPU control word do it now
7203   if (fp_mode_24b) {
7204     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7205   }
7206   if (UseSSE >= 2 && VerifyFPU) {
7207     verify_FPU(0, "FPU stack must be clean on entry");
7208   }
7209 #endif
7210 
7211 #ifdef ASSERT
7212   if (VerifyStackAtCalls) {
7213     Label L;
7214     push(rax);
7215     mov(rax, rsp);
7216     andptr(rax, StackAlignmentInBytes-1);
7217     cmpptr(rax, StackAlignmentInBytes-wordSize);
7218     pop(rax);
7219     jcc(Assembler::equal, L);
7220     STOP("Stack is not properly aligned!");
7221     bind(L);
7222   }
7223 #endif
7224 
7225 }
7226 
7227 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7228   // cnt - number of qwords (8-byte words).
7229   // base - start address, qword aligned.
7230   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7231   assert(base==rdi, "base register must be edi for rep stos");
7232   assert(tmp==rax,   "tmp register must be eax for rep stos");
7233   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7234   assert(InitArrayShortSize % BytesPerLong == 0,
7235     "InitArrayShortSize should be the multiple of BytesPerLong");
7236 
7237   Label DONE;
7238 
7239   xorptr(tmp, tmp);
7240 
7241   if (!is_large) {
7242     Label LOOP, LONG;
7243     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7244     jccb(Assembler::greater, LONG);
7245 
7246     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7247 
7248     decrement(cnt);
7249     jccb(Assembler::negative, DONE); // Zero length
7250 
7251     // Use individual pointer-sized stores for small counts:
7252     BIND(LOOP);
7253     movptr(Address(base, cnt, Address::times_ptr), tmp);
7254     decrement(cnt);
7255     jccb(Assembler::greaterEqual, LOOP);
7256     jmpb(DONE);
7257 
7258     BIND(LONG);
7259   }
7260 
7261   // Use longer rep-prefixed ops for non-small counts:
7262   if (UseFastStosb) {
7263     shlptr(cnt, 3); // convert to number of bytes
7264     rep_stosb();
7265   } else {
7266     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7267     rep_stos();
7268   }
7269 
7270   BIND(DONE);
7271 }
7272 
7273 #ifdef COMPILER2
7274 
7275 // IndexOf for constant substrings with size >= 8 chars
7276 // which don't need to be loaded through stack.
7277 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7278                                       Register cnt1, Register cnt2,
7279                                       int int_cnt2,  Register result,
7280                                       XMMRegister vec, Register tmp,
7281                                       int ae) {
7282   ShortBranchVerifier sbv(this);
7283   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7284   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7285   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7286 
7287   // This method uses the pcmpestri instruction with bound registers
7288   //   inputs:
7289   //     xmm - substring
7290   //     rax - substring length (elements count)
7291   //     mem - scanned string
7292   //     rdx - string length (elements count)
7293   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7294   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7295   //   outputs:
7296   //     rcx - matched index in string
7297   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7298   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7299   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7300   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7301   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7302 
7303   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7304         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7305         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7306 
7307   // Note, inline_string_indexOf() generates checks:
7308   // if (substr.count > string.count) return -1;
7309   // if (substr.count == 0) return 0;
7310   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7311 
7312   // Load substring.
7313   if (ae == StrIntrinsicNode::UL) {
7314     pmovzxbw(vec, Address(str2, 0));
7315   } else {
7316     movdqu(vec, Address(str2, 0));
7317   }
7318   movl(cnt2, int_cnt2);
7319   movptr(result, str1); // string addr
7320 
7321   if (int_cnt2 > stride) {
7322     jmpb(SCAN_TO_SUBSTR);
7323 
7324     // Reload substr for rescan, this code
7325     // is executed only for large substrings (> 8 chars)
7326     bind(RELOAD_SUBSTR);
7327     if (ae == StrIntrinsicNode::UL) {
7328       pmovzxbw(vec, Address(str2, 0));
7329     } else {
7330       movdqu(vec, Address(str2, 0));
7331     }
7332     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7333 
7334     bind(RELOAD_STR);
7335     // We came here after the beginning of the substring was
7336     // matched but the rest of it was not so we need to search
7337     // again. Start from the next element after the previous match.
7338 
7339     // cnt2 is number of substring reminding elements and
7340     // cnt1 is number of string reminding elements when cmp failed.
7341     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7342     subl(cnt1, cnt2);
7343     addl(cnt1, int_cnt2);
7344     movl(cnt2, int_cnt2); // Now restore cnt2
7345 
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 
7352   } // (int_cnt2 > 8)
7353 
7354   // Scan string for start of substr in 16-byte vectors
7355   bind(SCAN_TO_SUBSTR);
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   jmpb(SCAN_TO_SUBSTR);
7364 
7365   // Found a potential substr
7366   bind(FOUND_CANDIDATE);
7367   // Matched whole vector if first element matched (tmp(rcx) == 0).
7368   if (int_cnt2 == stride) {
7369     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7370   } else { // int_cnt2 > 8
7371     jccb(Assembler::overflow, FOUND_SUBSTR);
7372   }
7373   // After pcmpestri tmp(rcx) contains matched element index
7374   // Compute start addr of substr
7375   lea(result, Address(result, tmp, scale1));
7376 
7377   // Make sure string is still long enough
7378   subl(cnt1, tmp);
7379   cmpl(cnt1, cnt2);
7380   if (int_cnt2 == stride) {
7381     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7382   } else { // int_cnt2 > 8
7383     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7384   }
7385   // Left less then substring.
7386 
7387   bind(RET_NOT_FOUND);
7388   movl(result, -1);
7389   jmpb(EXIT);
7390 
7391   if (int_cnt2 > stride) {
7392     // This code is optimized for the case when whole substring
7393     // is matched if its head is matched.
7394     bind(MATCH_SUBSTR_HEAD);
7395     pcmpestri(vec, Address(result, 0), mode);
7396     // Reload only string if does not match
7397     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7398 
7399     Label CONT_SCAN_SUBSTR;
7400     // Compare the rest of substring (> 8 chars).
7401     bind(FOUND_SUBSTR);
7402     // First 8 chars are already matched.
7403     negptr(cnt2);
7404     addptr(cnt2, stride);
7405 
7406     bind(SCAN_SUBSTR);
7407     subl(cnt1, stride);
7408     cmpl(cnt2, -stride); // Do not read beyond substring
7409     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7410     // Back-up strings to avoid reading beyond substring:
7411     // cnt1 = cnt1 - cnt2 + 8
7412     addl(cnt1, cnt2); // cnt2 is negative
7413     addl(cnt1, stride);
7414     movl(cnt2, stride); negptr(cnt2);
7415     bind(CONT_SCAN_SUBSTR);
7416     if (int_cnt2 < (int)G) {
7417       int tail_off1 = int_cnt2<<scale1;
7418       int tail_off2 = int_cnt2<<scale2;
7419       if (ae == StrIntrinsicNode::UL) {
7420         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7421       } else {
7422         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7423       }
7424       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7425     } else {
7426       // calculate index in register to avoid integer overflow (int_cnt2*2)
7427       movl(tmp, int_cnt2);
7428       addptr(tmp, cnt2);
7429       if (ae == StrIntrinsicNode::UL) {
7430         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7431       } else {
7432         movdqu(vec, Address(str2, tmp, scale2, 0));
7433       }
7434       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7435     }
7436     // Need to reload strings pointers if not matched whole vector
7437     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7438     addptr(cnt2, stride);
7439     jcc(Assembler::negative, SCAN_SUBSTR);
7440     // Fall through if found full substring
7441 
7442   } // (int_cnt2 > 8)
7443 
7444   bind(RET_FOUND);
7445   // Found result if we matched full small substring.
7446   // Compute substr offset
7447   subptr(result, str1);
7448   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7449     shrl(result, 1); // index
7450   }
7451   bind(EXIT);
7452 
7453 } // string_indexofC8
7454 
7455 // Small strings are loaded through stack if they cross page boundary.
7456 void MacroAssembler::string_indexof(Register str1, Register str2,
7457                                     Register cnt1, Register cnt2,
7458                                     int int_cnt2,  Register result,
7459                                     XMMRegister vec, Register tmp,
7460                                     int ae) {
7461   ShortBranchVerifier sbv(this);
7462   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7463   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7464   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7465 
7466   //
7467   // int_cnt2 is length of small (< 8 chars) constant substring
7468   // or (-1) for non constant substring in which case its length
7469   // is in cnt2 register.
7470   //
7471   // Note, inline_string_indexOf() generates checks:
7472   // if (substr.count > string.count) return -1;
7473   // if (substr.count == 0) return 0;
7474   //
7475   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7476   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7477   // This method uses the pcmpestri instruction with bound registers
7478   //   inputs:
7479   //     xmm - substring
7480   //     rax - substring length (elements count)
7481   //     mem - scanned string
7482   //     rdx - string length (elements count)
7483   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7484   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7485   //   outputs:
7486   //     rcx - matched index in string
7487   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7488   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7489   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7490   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7491 
7492   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7493         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7494         FOUND_CANDIDATE;
7495 
7496   { //========================================================
7497     // We don't know where these strings are located
7498     // and we can't read beyond them. Load them through stack.
7499     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7500 
7501     movptr(tmp, rsp); // save old SP
7502 
7503     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7504       if (int_cnt2 == (1>>scale2)) { // One byte
7505         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7506         load_unsigned_byte(result, Address(str2, 0));
7507         movdl(vec, result); // move 32 bits
7508       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7509         // Not enough header space in 32-bit VM: 12+3 = 15.
7510         movl(result, Address(str2, -1));
7511         shrl(result, 8);
7512         movdl(vec, result); // move 32 bits
7513       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7514         load_unsigned_short(result, Address(str2, 0));
7515         movdl(vec, result); // move 32 bits
7516       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7517         movdl(vec, Address(str2, 0)); // move 32 bits
7518       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7519         movq(vec, Address(str2, 0));  // move 64 bits
7520       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7521         // Array header size is 12 bytes in 32-bit VM
7522         // + 6 bytes for 3 chars == 18 bytes,
7523         // enough space to load vec and shift.
7524         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7525         if (ae == StrIntrinsicNode::UL) {
7526           int tail_off = int_cnt2-8;
7527           pmovzxbw(vec, Address(str2, tail_off));
7528           psrldq(vec, -2*tail_off);
7529         }
7530         else {
7531           int tail_off = int_cnt2*(1<<scale2);
7532           movdqu(vec, Address(str2, tail_off-16));
7533           psrldq(vec, 16-tail_off);
7534         }
7535       }
7536     } else { // not constant substring
7537       cmpl(cnt2, stride);
7538       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7539 
7540       // We can read beyond string if srt+16 does not cross page boundary
7541       // since heaps are aligned and mapped by pages.
7542       assert(os::vm_page_size() < (int)G, "default page should be small");
7543       movl(result, str2); // We need only low 32 bits
7544       andl(result, (os::vm_page_size()-1));
7545       cmpl(result, (os::vm_page_size()-16));
7546       jccb(Assembler::belowEqual, CHECK_STR);
7547 
7548       // Move small strings to stack to allow load 16 bytes into vec.
7549       subptr(rsp, 16);
7550       int stk_offset = wordSize-(1<<scale2);
7551       push(cnt2);
7552 
7553       bind(COPY_SUBSTR);
7554       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7555         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7556         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7557       } else if (ae == StrIntrinsicNode::UU) {
7558         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7559         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7560       }
7561       decrement(cnt2);
7562       jccb(Assembler::notZero, COPY_SUBSTR);
7563 
7564       pop(cnt2);
7565       movptr(str2, rsp);  // New substring address
7566     } // non constant
7567 
7568     bind(CHECK_STR);
7569     cmpl(cnt1, stride);
7570     jccb(Assembler::aboveEqual, BIG_STRINGS);
7571 
7572     // Check cross page boundary.
7573     movl(result, str1); // We need only low 32 bits
7574     andl(result, (os::vm_page_size()-1));
7575     cmpl(result, (os::vm_page_size()-16));
7576     jccb(Assembler::belowEqual, BIG_STRINGS);
7577 
7578     subptr(rsp, 16);
7579     int stk_offset = -(1<<scale1);
7580     if (int_cnt2 < 0) { // not constant
7581       push(cnt2);
7582       stk_offset += wordSize;
7583     }
7584     movl(cnt2, cnt1);
7585 
7586     bind(COPY_STR);
7587     if (ae == StrIntrinsicNode::LL) {
7588       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7589       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7590     } else {
7591       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7592       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7593     }
7594     decrement(cnt2);
7595     jccb(Assembler::notZero, COPY_STR);
7596 
7597     if (int_cnt2 < 0) { // not constant
7598       pop(cnt2);
7599     }
7600     movptr(str1, rsp);  // New string address
7601 
7602     bind(BIG_STRINGS);
7603     // Load substring.
7604     if (int_cnt2 < 0) { // -1
7605       if (ae == StrIntrinsicNode::UL) {
7606         pmovzxbw(vec, Address(str2, 0));
7607       } else {
7608         movdqu(vec, Address(str2, 0));
7609       }
7610       push(cnt2);       // substr count
7611       push(str2);       // substr addr
7612       push(str1);       // string addr
7613     } else {
7614       // Small (< 8 chars) constant substrings are loaded already.
7615       movl(cnt2, int_cnt2);
7616     }
7617     push(tmp);  // original SP
7618 
7619   } // Finished loading
7620 
7621   //========================================================
7622   // Start search
7623   //
7624 
7625   movptr(result, str1); // string addr
7626 
7627   if (int_cnt2  < 0) {  // Only for non constant substring
7628     jmpb(SCAN_TO_SUBSTR);
7629 
7630     // SP saved at sp+0
7631     // String saved at sp+1*wordSize
7632     // Substr saved at sp+2*wordSize
7633     // Substr count saved at sp+3*wordSize
7634 
7635     // Reload substr for rescan, this code
7636     // is executed only for large substrings (> 8 chars)
7637     bind(RELOAD_SUBSTR);
7638     movptr(str2, Address(rsp, 2*wordSize));
7639     movl(cnt2, Address(rsp, 3*wordSize));
7640     if (ae == StrIntrinsicNode::UL) {
7641       pmovzxbw(vec, Address(str2, 0));
7642     } else {
7643       movdqu(vec, Address(str2, 0));
7644     }
7645     // We came here after the beginning of the substring was
7646     // matched but the rest of it was not so we need to search
7647     // again. Start from the next element after the previous match.
7648     subptr(str1, result); // Restore counter
7649     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7650       shrl(str1, 1);
7651     }
7652     addl(cnt1, str1);
7653     decrementl(cnt1);   // Shift to next element
7654     cmpl(cnt1, cnt2);
7655     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7656 
7657     addptr(result, (1<<scale1));
7658   } // non constant
7659 
7660   // Scan string for start of substr in 16-byte vectors
7661   bind(SCAN_TO_SUBSTR);
7662   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7663   pcmpestri(vec, Address(result, 0), mode);
7664   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7665   subl(cnt1, stride);
7666   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7667   cmpl(cnt1, cnt2);
7668   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7669   addptr(result, 16);
7670 
7671   bind(ADJUST_STR);
7672   cmpl(cnt1, stride); // Do not read beyond string
7673   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7674   // Back-up string to avoid reading beyond string.
7675   lea(result, Address(result, cnt1, scale1, -16));
7676   movl(cnt1, stride);
7677   jmpb(SCAN_TO_SUBSTR);
7678 
7679   // Found a potential substr
7680   bind(FOUND_CANDIDATE);
7681   // After pcmpestri tmp(rcx) contains matched element index
7682 
7683   // Make sure string is still long enough
7684   subl(cnt1, tmp);
7685   cmpl(cnt1, cnt2);
7686   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7687   // Left less then substring.
7688 
7689   bind(RET_NOT_FOUND);
7690   movl(result, -1);
7691   jmpb(CLEANUP);
7692 
7693   bind(FOUND_SUBSTR);
7694   // Compute start addr of substr
7695   lea(result, Address(result, tmp, scale1));
7696   if (int_cnt2 > 0) { // Constant substring
7697     // Repeat search for small substring (< 8 chars)
7698     // from new point without reloading substring.
7699     // Have to check that we don't read beyond string.
7700     cmpl(tmp, stride-int_cnt2);
7701     jccb(Assembler::greater, ADJUST_STR);
7702     // Fall through if matched whole substring.
7703   } else { // non constant
7704     assert(int_cnt2 == -1, "should be != 0");
7705 
7706     addl(tmp, cnt2);
7707     // Found result if we matched whole substring.
7708     cmpl(tmp, stride);
7709     jccb(Assembler::lessEqual, RET_FOUND);
7710 
7711     // Repeat search for small substring (<= 8 chars)
7712     // from new point 'str1' without reloading substring.
7713     cmpl(cnt2, stride);
7714     // Have to check that we don't read beyond string.
7715     jccb(Assembler::lessEqual, ADJUST_STR);
7716 
7717     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7718     // Compare the rest of substring (> 8 chars).
7719     movptr(str1, result);
7720 
7721     cmpl(tmp, cnt2);
7722     // First 8 chars are already matched.
7723     jccb(Assembler::equal, CHECK_NEXT);
7724 
7725     bind(SCAN_SUBSTR);
7726     pcmpestri(vec, Address(str1, 0), mode);
7727     // Need to reload strings pointers if not matched whole vector
7728     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7729 
7730     bind(CHECK_NEXT);
7731     subl(cnt2, stride);
7732     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7733     addptr(str1, 16);
7734     if (ae == StrIntrinsicNode::UL) {
7735       addptr(str2, 8);
7736     } else {
7737       addptr(str2, 16);
7738     }
7739     subl(cnt1, stride);
7740     cmpl(cnt2, stride); // Do not read beyond substring
7741     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7742     // Back-up strings to avoid reading beyond substring.
7743 
7744     if (ae == StrIntrinsicNode::UL) {
7745       lea(str2, Address(str2, cnt2, scale2, -8));
7746       lea(str1, Address(str1, cnt2, scale1, -16));
7747     } else {
7748       lea(str2, Address(str2, cnt2, scale2, -16));
7749       lea(str1, Address(str1, cnt2, scale1, -16));
7750     }
7751     subl(cnt1, cnt2);
7752     movl(cnt2, stride);
7753     addl(cnt1, stride);
7754     bind(CONT_SCAN_SUBSTR);
7755     if (ae == StrIntrinsicNode::UL) {
7756       pmovzxbw(vec, Address(str2, 0));
7757     } else {
7758       movdqu(vec, Address(str2, 0));
7759     }
7760     jmpb(SCAN_SUBSTR);
7761 
7762     bind(RET_FOUND_LONG);
7763     movptr(str1, Address(rsp, wordSize));
7764   } // non constant
7765 
7766   bind(RET_FOUND);
7767   // Compute substr offset
7768   subptr(result, str1);
7769   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7770     shrl(result, 1); // index
7771   }
7772   bind(CLEANUP);
7773   pop(rsp); // restore SP
7774 
7775 } // string_indexof
7776 
7777 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7778                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7779   ShortBranchVerifier sbv(this);
7780   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7781   assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7782 
7783   int stride = 8;
7784 
7785   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7786         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7787         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7788         FOUND_SEQ_CHAR, DONE_LABEL;
7789 
7790   movptr(result, str1);
7791   if (UseAVX >= 2) {
7792     cmpl(cnt1, stride);
7793     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7794     cmpl(cnt1, 2*stride);
7795     jccb(Assembler::less, SCAN_TO_8_CHAR_INIT);
7796     movdl(vec1, ch);
7797     vpbroadcastw(vec1, vec1);
7798     vpxor(vec2, vec2);
7799     movl(tmp, cnt1);
7800     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7801     andl(cnt1,0x0000000F);  //tail count (in chars)
7802 
7803     bind(SCAN_TO_16_CHAR_LOOP);
7804     vmovdqu(vec3, Address(result, 0));
7805     vpcmpeqw(vec3, vec3, vec1, 1);
7806     vptest(vec2, vec3);
7807     jcc(Assembler::carryClear, FOUND_CHAR);
7808     addptr(result, 32);
7809     subl(tmp, 2*stride);
7810     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7811     jmp(SCAN_TO_8_CHAR);
7812     bind(SCAN_TO_8_CHAR_INIT);
7813     movdl(vec1, ch);
7814     pshuflw(vec1, vec1, 0x00);
7815     pshufd(vec1, vec1, 0);
7816     pxor(vec2, vec2);
7817   }
7818   bind(SCAN_TO_8_CHAR);
7819   cmpl(cnt1, stride);
7820   if (UseAVX >= 2) {
7821     jccb(Assembler::less, SCAN_TO_CHAR);
7822   } else {
7823     jccb(Assembler::less, SCAN_TO_CHAR_LOOP);
7824     movdl(vec1, ch);
7825     pshuflw(vec1, vec1, 0x00);
7826     pshufd(vec1, vec1, 0);
7827     pxor(vec2, vec2);
7828   }
7829   movl(tmp, cnt1);
7830   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7831   andl(cnt1,0x00000007);  //tail count (in chars)
7832 
7833   bind(SCAN_TO_8_CHAR_LOOP);
7834   movdqu(vec3, Address(result, 0));
7835   pcmpeqw(vec3, vec1);
7836   ptest(vec2, vec3);
7837   jcc(Assembler::carryClear, FOUND_CHAR);
7838   addptr(result, 16);
7839   subl(tmp, stride);
7840   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7841   bind(SCAN_TO_CHAR);
7842   testl(cnt1, cnt1);
7843   jcc(Assembler::zero, RET_NOT_FOUND);
7844   bind(SCAN_TO_CHAR_LOOP);
7845   load_unsigned_short(tmp, Address(result, 0));
7846   cmpl(ch, tmp);
7847   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7848   addptr(result, 2);
7849   subl(cnt1, 1);
7850   jccb(Assembler::zero, RET_NOT_FOUND);
7851   jmp(SCAN_TO_CHAR_LOOP);
7852 
7853   bind(RET_NOT_FOUND);
7854   movl(result, -1);
7855   jmpb(DONE_LABEL);
7856 
7857   bind(FOUND_CHAR);
7858   if (UseAVX >= 2) {
7859     vpmovmskb(tmp, vec3);
7860   } else {
7861     pmovmskb(tmp, vec3);
7862   }
7863   bsfl(ch, tmp);
7864   addl(result, ch);
7865 
7866   bind(FOUND_SEQ_CHAR);
7867   subptr(result, str1);
7868   shrl(result, 1);
7869 
7870   bind(DONE_LABEL);
7871 } // string_indexof_char
7872 
7873 // helper function for string_compare
7874 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7875                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7876                                         Address::ScaleFactor scale2, Register index, int ae) {
7877   if (ae == StrIntrinsicNode::LL) {
7878     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7879     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7880   } else if (ae == StrIntrinsicNode::UU) {
7881     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7882     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7883   } else {
7884     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7885     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7886   }
7887 }
7888 
7889 // Compare strings, used for char[] and byte[].
7890 void MacroAssembler::string_compare(Register str1, Register str2,
7891                                     Register cnt1, Register cnt2, Register result,
7892                                     XMMRegister vec1, int ae) {
7893   ShortBranchVerifier sbv(this);
7894   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7895   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7896   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7897   int stride2x2 = 0x40;
7898   Address::ScaleFactor scale = Address::no_scale;
7899   Address::ScaleFactor scale1 = Address::no_scale;
7900   Address::ScaleFactor scale2 = Address::no_scale;
7901 
7902   if (ae != StrIntrinsicNode::LL) {
7903     stride2x2 = 0x20;
7904   }
7905 
7906   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7907     shrl(cnt2, 1);
7908   }
7909   // Compute the minimum of the string lengths and the
7910   // difference of the string lengths (stack).
7911   // Do the conditional move stuff
7912   movl(result, cnt1);
7913   subl(cnt1, cnt2);
7914   push(cnt1);
7915   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7916 
7917   // Is the minimum length zero?
7918   testl(cnt2, cnt2);
7919   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7920   if (ae == StrIntrinsicNode::LL) {
7921     // Load first bytes
7922     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7923     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7924   } else if (ae == StrIntrinsicNode::UU) {
7925     // Load first characters
7926     load_unsigned_short(result, Address(str1, 0));
7927     load_unsigned_short(cnt1, Address(str2, 0));
7928   } else {
7929     load_unsigned_byte(result, Address(str1, 0));
7930     load_unsigned_short(cnt1, Address(str2, 0));
7931   }
7932   subl(result, cnt1);
7933   jcc(Assembler::notZero,  POP_LABEL);
7934 
7935   if (ae == StrIntrinsicNode::UU) {
7936     // Divide length by 2 to get number of chars
7937     shrl(cnt2, 1);
7938   }
7939   cmpl(cnt2, 1);
7940   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7941 
7942   // Check if the strings start at the same location and setup scale and stride
7943   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7944     cmpptr(str1, str2);
7945     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7946     if (ae == StrIntrinsicNode::LL) {
7947       scale = Address::times_1;
7948       stride = 16;
7949     } else {
7950       scale = Address::times_2;
7951       stride = 8;
7952     }
7953   } else {
7954     scale1 = Address::times_1;
7955     scale2 = Address::times_2;
7956     // scale not used
7957     stride = 8;
7958   }
7959 
7960   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7961     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
7962     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7963     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7964     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7965     Label COMPARE_TAIL_LONG;
7966     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7967 
7968     int pcmpmask = 0x19;
7969     if (ae == StrIntrinsicNode::LL) {
7970       pcmpmask &= ~0x01;
7971     }
7972 
7973     // Setup to compare 16-chars (32-bytes) vectors,
7974     // start from first character again because it has aligned address.
7975     if (ae == StrIntrinsicNode::LL) {
7976       stride2 = 32;
7977     } else {
7978       stride2 = 16;
7979     }
7980     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7981       adr_stride = stride << scale;
7982     } else {
7983       adr_stride1 = 8;  //stride << scale1;
7984       adr_stride2 = 16; //stride << scale2;
7985     }
7986 
7987     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7988     // rax and rdx are used by pcmpestri as elements counters
7989     movl(result, cnt2);
7990     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7991     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7992 
7993     // fast path : compare first 2 8-char vectors.
7994     bind(COMPARE_16_CHARS);
7995     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7996       movdqu(vec1, Address(str1, 0));
7997     } else {
7998       pmovzxbw(vec1, Address(str1, 0));
7999     }
8000     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8001     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8002 
8003     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8004       movdqu(vec1, Address(str1, adr_stride));
8005       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8006     } else {
8007       pmovzxbw(vec1, Address(str1, adr_stride1));
8008       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8009     }
8010     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8011     addl(cnt1, stride);
8012 
8013     // Compare the characters at index in cnt1
8014     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8015     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8016     subl(result, cnt2);
8017     jmp(POP_LABEL);
8018 
8019     // Setup the registers to start vector comparison loop
8020     bind(COMPARE_WIDE_VECTORS);
8021     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8022       lea(str1, Address(str1, result, scale));
8023       lea(str2, Address(str2, result, scale));
8024     } else {
8025       lea(str1, Address(str1, result, scale1));
8026       lea(str2, Address(str2, result, scale2));
8027     }
8028     subl(result, stride2);
8029     subl(cnt2, stride2);
8030     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8031     negptr(result);
8032 
8033     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8034     bind(COMPARE_WIDE_VECTORS_LOOP);
8035 
8036 #ifdef _LP64
8037     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8038       cmpl(cnt2, stride2x2);
8039       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8040       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8041       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8042 
8043       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8044       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8045         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8046         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8047       } else {
8048         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8049         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8050       }
8051       kortestql(k7, k7);
8052       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8053       addptr(result, stride2x2);  // update since we already compared at this addr
8054       subl(cnt2, stride2x2);      // and sub the size too
8055       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8056 
8057       vpxor(vec1, vec1);
8058       jmpb(COMPARE_WIDE_TAIL);
8059     }//if (VM_Version::supports_avx512vlbw())
8060 #endif // _LP64
8061 
8062 
8063     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8064     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8065       vmovdqu(vec1, Address(str1, result, scale));
8066       vpxor(vec1, Address(str2, result, scale));
8067     } else {
8068       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8069       vpxor(vec1, Address(str2, result, scale2));
8070     }
8071     vptest(vec1, vec1);
8072     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8073     addptr(result, stride2);
8074     subl(cnt2, stride2);
8075     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8076     // clean upper bits of YMM registers
8077     vpxor(vec1, vec1);
8078 
8079     // compare wide vectors tail
8080     bind(COMPARE_WIDE_TAIL);
8081     testptr(result, result);
8082     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8083 
8084     movl(result, stride2);
8085     movl(cnt2, result);
8086     negptr(result);
8087     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8088 
8089     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8090     bind(VECTOR_NOT_EQUAL);
8091     // clean upper bits of YMM registers
8092     vpxor(vec1, vec1);
8093     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8094       lea(str1, Address(str1, result, scale));
8095       lea(str2, Address(str2, result, scale));
8096     } else {
8097       lea(str1, Address(str1, result, scale1));
8098       lea(str2, Address(str2, result, scale2));
8099     }
8100     jmp(COMPARE_16_CHARS);
8101 
8102     // Compare tail chars, length between 1 to 15 chars
8103     bind(COMPARE_TAIL_LONG);
8104     movl(cnt2, result);
8105     cmpl(cnt2, stride);
8106     jccb(Assembler::less, COMPARE_SMALL_STR);
8107 
8108     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8109       movdqu(vec1, Address(str1, 0));
8110     } else {
8111       pmovzxbw(vec1, Address(str1, 0));
8112     }
8113     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8114     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8115     subptr(cnt2, stride);
8116     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8117     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8118       lea(str1, Address(str1, result, scale));
8119       lea(str2, Address(str2, result, scale));
8120     } else {
8121       lea(str1, Address(str1, result, scale1));
8122       lea(str2, Address(str2, result, scale2));
8123     }
8124     negptr(cnt2);
8125     jmpb(WHILE_HEAD_LABEL);
8126 
8127     bind(COMPARE_SMALL_STR);
8128   } else if (UseSSE42Intrinsics) {
8129     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8130     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8131     int pcmpmask = 0x19;
8132     // Setup to compare 8-char (16-byte) vectors,
8133     // start from first character again because it has aligned address.
8134     movl(result, cnt2);
8135     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8136     if (ae == StrIntrinsicNode::LL) {
8137       pcmpmask &= ~0x01;
8138     }
8139     jccb(Assembler::zero, COMPARE_TAIL);
8140     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8141       lea(str1, Address(str1, result, scale));
8142       lea(str2, Address(str2, result, scale));
8143     } else {
8144       lea(str1, Address(str1, result, scale1));
8145       lea(str2, Address(str2, result, scale2));
8146     }
8147     negptr(result);
8148 
8149     // pcmpestri
8150     //   inputs:
8151     //     vec1- substring
8152     //     rax - negative string length (elements count)
8153     //     mem - scanned string
8154     //     rdx - string length (elements count)
8155     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8156     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8157     //   outputs:
8158     //     rcx - first mismatched element index
8159     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8160 
8161     bind(COMPARE_WIDE_VECTORS);
8162     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8163       movdqu(vec1, Address(str1, result, scale));
8164       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8165     } else {
8166       pmovzxbw(vec1, Address(str1, result, scale1));
8167       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8168     }
8169     // After pcmpestri cnt1(rcx) contains mismatched element index
8170 
8171     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8172     addptr(result, stride);
8173     subptr(cnt2, stride);
8174     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8175 
8176     // compare wide vectors tail
8177     testptr(result, result);
8178     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
8179 
8180     movl(cnt2, stride);
8181     movl(result, stride);
8182     negptr(result);
8183     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8184       movdqu(vec1, Address(str1, result, scale));
8185       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8186     } else {
8187       pmovzxbw(vec1, Address(str1, result, scale1));
8188       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8189     }
8190     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8191 
8192     // Mismatched characters in the vectors
8193     bind(VECTOR_NOT_EQUAL);
8194     addptr(cnt1, result);
8195     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8196     subl(result, cnt2);
8197     jmpb(POP_LABEL);
8198 
8199     bind(COMPARE_TAIL); // limit is zero
8200     movl(cnt2, result);
8201     // Fallthru to tail compare
8202   }
8203   // Shift str2 and str1 to the end of the arrays, negate min
8204   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8205     lea(str1, Address(str1, cnt2, scale));
8206     lea(str2, Address(str2, cnt2, scale));
8207   } else {
8208     lea(str1, Address(str1, cnt2, scale1));
8209     lea(str2, Address(str2, cnt2, scale2));
8210   }
8211   decrementl(cnt2);  // first character was compared already
8212   negptr(cnt2);
8213 
8214   // Compare the rest of the elements
8215   bind(WHILE_HEAD_LABEL);
8216   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8217   subl(result, cnt1);
8218   jccb(Assembler::notZero, POP_LABEL);
8219   increment(cnt2);
8220   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8221 
8222   // Strings are equal up to min length.  Return the length difference.
8223   bind(LENGTH_DIFF_LABEL);
8224   pop(result);
8225   if (ae == StrIntrinsicNode::UU) {
8226     // Divide diff by 2 to get number of chars
8227     sarl(result, 1);
8228   }
8229   jmpb(DONE_LABEL);
8230 
8231 #ifdef _LP64
8232   if (VM_Version::supports_avx512vlbw()) {
8233 
8234     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8235 
8236     kmovql(cnt1, k7);
8237     notq(cnt1);
8238     bsfq(cnt2, cnt1);
8239     if (ae != StrIntrinsicNode::LL) {
8240       // Divide diff by 2 to get number of chars
8241       sarl(cnt2, 1);
8242     }
8243     addq(result, cnt2);
8244     if (ae == StrIntrinsicNode::LL) {
8245       load_unsigned_byte(cnt1, Address(str2, result));
8246       load_unsigned_byte(result, Address(str1, result));
8247     } else if (ae == StrIntrinsicNode::UU) {
8248       load_unsigned_short(cnt1, Address(str2, result, scale));
8249       load_unsigned_short(result, Address(str1, result, scale));
8250     } else {
8251       load_unsigned_short(cnt1, Address(str2, result, scale2));
8252       load_unsigned_byte(result, Address(str1, result, scale1));
8253     }
8254     subl(result, cnt1);
8255     jmpb(POP_LABEL);
8256   }//if (VM_Version::supports_avx512vlbw())
8257 #endif // _LP64
8258 
8259   // Discard the stored length difference
8260   bind(POP_LABEL);
8261   pop(cnt1);
8262 
8263   // That's it
8264   bind(DONE_LABEL);
8265   if(ae == StrIntrinsicNode::UL) {
8266     negl(result);
8267   }
8268 
8269 }
8270 
8271 // Search for Non-ASCII character (Negative byte value) in a byte array,
8272 // return true if it has any and false otherwise.
8273 void MacroAssembler::has_negatives(Register ary1, Register len,
8274                                    Register result, Register tmp1,
8275                                    XMMRegister vec1, XMMRegister vec2) {
8276 
8277   // rsi: byte array
8278   // rcx: len
8279   // rax: result
8280   ShortBranchVerifier sbv(this);
8281   assert_different_registers(ary1, len, result, tmp1);
8282   assert_different_registers(vec1, vec2);
8283   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8284 
8285   // len == 0
8286   testl(len, len);
8287   jcc(Assembler::zero, FALSE_LABEL);
8288 
8289   movl(result, len); // copy
8290 
8291   if (UseAVX >= 2 && UseSSE >= 2) {
8292     // With AVX2, use 32-byte vector compare
8293     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8294 
8295     // Compare 32-byte vectors
8296     andl(result, 0x0000001f);  //   tail count (in bytes)
8297     andl(len, 0xffffffe0);   // vector count (in bytes)
8298     jccb(Assembler::zero, COMPARE_TAIL);
8299 
8300     lea(ary1, Address(ary1, len, Address::times_1));
8301     negptr(len);
8302 
8303     movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8304     movdl(vec2, tmp1);
8305     vpbroadcastd(vec2, vec2);
8306 
8307     bind(COMPARE_WIDE_VECTORS);
8308     vmovdqu(vec1, Address(ary1, len, Address::times_1));
8309     vptest(vec1, vec2);
8310     jccb(Assembler::notZero, TRUE_LABEL);
8311     addptr(len, 32);
8312     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8313 
8314     testl(result, result);
8315     jccb(Assembler::zero, FALSE_LABEL);
8316 
8317     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8318     vptest(vec1, vec2);
8319     jccb(Assembler::notZero, TRUE_LABEL);
8320     jmpb(FALSE_LABEL);
8321 
8322     bind(COMPARE_TAIL); // len is zero
8323     movl(len, result);
8324     // Fallthru to tail compare
8325   } else if (UseSSE42Intrinsics) {
8326     assert(UseSSE >= 4, "SSE4 must be  for SSE4.2 intrinsics to be available");
8327     // With SSE4.2, use double quad vector compare
8328     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8329 
8330     // Compare 16-byte vectors
8331     andl(result, 0x0000000f);  //   tail count (in bytes)
8332     andl(len, 0xfffffff0);   // vector count (in bytes)
8333     jccb(Assembler::zero, COMPARE_TAIL);
8334 
8335     lea(ary1, Address(ary1, len, Address::times_1));
8336     negptr(len);
8337 
8338     movl(tmp1, 0x80808080);
8339     movdl(vec2, tmp1);
8340     pshufd(vec2, vec2, 0);
8341 
8342     bind(COMPARE_WIDE_VECTORS);
8343     movdqu(vec1, Address(ary1, len, Address::times_1));
8344     ptest(vec1, vec2);
8345     jccb(Assembler::notZero, TRUE_LABEL);
8346     addptr(len, 16);
8347     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8348 
8349     testl(result, result);
8350     jccb(Assembler::zero, FALSE_LABEL);
8351 
8352     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8353     ptest(vec1, vec2);
8354     jccb(Assembler::notZero, TRUE_LABEL);
8355     jmpb(FALSE_LABEL);
8356 
8357     bind(COMPARE_TAIL); // len is zero
8358     movl(len, result);
8359     // Fallthru to tail compare
8360   }
8361 
8362   // Compare 4-byte vectors
8363   andl(len, 0xfffffffc); // vector count (in bytes)
8364   jccb(Assembler::zero, COMPARE_CHAR);
8365 
8366   lea(ary1, Address(ary1, len, Address::times_1));
8367   negptr(len);
8368 
8369   bind(COMPARE_VECTORS);
8370   movl(tmp1, Address(ary1, len, Address::times_1));
8371   andl(tmp1, 0x80808080);
8372   jccb(Assembler::notZero, TRUE_LABEL);
8373   addptr(len, 4);
8374   jcc(Assembler::notZero, COMPARE_VECTORS);
8375 
8376   // Compare trailing char (final 2 bytes), if any
8377   bind(COMPARE_CHAR);
8378   testl(result, 0x2);   // tail  char
8379   jccb(Assembler::zero, COMPARE_BYTE);
8380   load_unsigned_short(tmp1, Address(ary1, 0));
8381   andl(tmp1, 0x00008080);
8382   jccb(Assembler::notZero, TRUE_LABEL);
8383   subptr(result, 2);
8384   lea(ary1, Address(ary1, 2));
8385 
8386   bind(COMPARE_BYTE);
8387   testl(result, 0x1);   // tail  byte
8388   jccb(Assembler::zero, FALSE_LABEL);
8389   load_unsigned_byte(tmp1, Address(ary1, 0));
8390   andl(tmp1, 0x00000080);
8391   jccb(Assembler::notEqual, TRUE_LABEL);
8392   jmpb(FALSE_LABEL);
8393 
8394   bind(TRUE_LABEL);
8395   movl(result, 1);   // return true
8396   jmpb(DONE);
8397 
8398   bind(FALSE_LABEL);
8399   xorl(result, result); // return false
8400 
8401   // That's it
8402   bind(DONE);
8403   if (UseAVX >= 2 && UseSSE >= 2) {
8404     // clean upper bits of YMM registers
8405     vpxor(vec1, vec1);
8406     vpxor(vec2, vec2);
8407   }
8408 }
8409 
8410 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8411 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8412                                    Register limit, Register result, Register chr,
8413                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8414   ShortBranchVerifier sbv(this);
8415   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8416 
8417   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8418   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8419 
8420   if (is_array_equ) {
8421     // Check the input args
8422     cmpptr(ary1, ary2);
8423     jcc(Assembler::equal, TRUE_LABEL);
8424 
8425     // Need additional checks for arrays_equals.
8426     testptr(ary1, ary1);
8427     jcc(Assembler::zero, FALSE_LABEL);
8428     testptr(ary2, ary2);
8429     jcc(Assembler::zero, FALSE_LABEL);
8430 
8431     // Check the lengths
8432     movl(limit, Address(ary1, length_offset));
8433     cmpl(limit, Address(ary2, length_offset));
8434     jcc(Assembler::notEqual, FALSE_LABEL);
8435   }
8436 
8437   // count == 0
8438   testl(limit, limit);
8439   jcc(Assembler::zero, TRUE_LABEL);
8440 
8441   if (is_array_equ) {
8442     // Load array address
8443     lea(ary1, Address(ary1, base_offset));
8444     lea(ary2, Address(ary2, base_offset));
8445   }
8446 
8447   if (is_array_equ && is_char) {
8448     // arrays_equals when used for char[].
8449     shll(limit, 1);      // byte count != 0
8450   }
8451   movl(result, limit); // copy
8452 
8453   if (UseAVX >= 2) {
8454     // With AVX2, use 32-byte vector compare
8455     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8456 
8457     // Compare 32-byte vectors
8458     andl(result, 0x0000001f);  //   tail count (in bytes)
8459     andl(limit, 0xffffffe0);   // vector count (in bytes)
8460     jcc(Assembler::zero, COMPARE_TAIL);
8461 
8462     lea(ary1, Address(ary1, limit, Address::times_1));
8463     lea(ary2, Address(ary2, limit, Address::times_1));
8464     negptr(limit);
8465 
8466     bind(COMPARE_WIDE_VECTORS);
8467 
8468 #ifdef _LP64
8469     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8470       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8471 
8472       cmpl(limit, -64);
8473       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8474 
8475       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8476 
8477       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8478       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8479       kortestql(k7, k7);
8480       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8481       addptr(limit, 64);  // update since we already compared at this addr
8482       cmpl(limit, -64);
8483       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8484 
8485       // At this point we may still need to compare -limit+result bytes.
8486       // We could execute the next two instruction and just continue via non-wide path:
8487       //  cmpl(limit, 0);
8488       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8489       // But since we stopped at the points ary{1,2}+limit which are
8490       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8491       // (|limit| <= 32 and result < 32),
8492       // we may just compare the last 64 bytes.
8493       //
8494       addptr(result, -64);   // it is safe, bc we just came from this area
8495       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8496       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8497       kortestql(k7, k7);
8498       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8499 
8500       jmp(TRUE_LABEL);
8501 
8502       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8503 
8504     }//if (VM_Version::supports_avx512vlbw())
8505 #endif //_LP64
8506 
8507     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8508     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8509     vpxor(vec1, vec2);
8510 
8511     vptest(vec1, vec1);
8512     jccb(Assembler::notZero, FALSE_LABEL);
8513     addptr(limit, 32);
8514     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8515 
8516     testl(result, result);
8517     jccb(Assembler::zero, TRUE_LABEL);
8518 
8519     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8520     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8521     vpxor(vec1, vec2);
8522 
8523     vptest(vec1, vec1);
8524     jccb(Assembler::notZero, FALSE_LABEL);
8525     jmpb(TRUE_LABEL);
8526 
8527     bind(COMPARE_TAIL); // limit is zero
8528     movl(limit, result);
8529     // Fallthru to tail compare
8530   } else if (UseSSE42Intrinsics) {
8531     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8532     // With SSE4.2, use double quad vector compare
8533     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8534 
8535     // Compare 16-byte vectors
8536     andl(result, 0x0000000f);  //   tail count (in bytes)
8537     andl(limit, 0xfffffff0);   // vector count (in bytes)
8538     jccb(Assembler::zero, COMPARE_TAIL);
8539 
8540     lea(ary1, Address(ary1, limit, Address::times_1));
8541     lea(ary2, Address(ary2, limit, Address::times_1));
8542     negptr(limit);
8543 
8544     bind(COMPARE_WIDE_VECTORS);
8545     movdqu(vec1, Address(ary1, limit, Address::times_1));
8546     movdqu(vec2, Address(ary2, limit, Address::times_1));
8547     pxor(vec1, vec2);
8548 
8549     ptest(vec1, vec1);
8550     jccb(Assembler::notZero, FALSE_LABEL);
8551     addptr(limit, 16);
8552     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8553 
8554     testl(result, result);
8555     jccb(Assembler::zero, TRUE_LABEL);
8556 
8557     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8558     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8559     pxor(vec1, vec2);
8560 
8561     ptest(vec1, vec1);
8562     jccb(Assembler::notZero, FALSE_LABEL);
8563     jmpb(TRUE_LABEL);
8564 
8565     bind(COMPARE_TAIL); // limit is zero
8566     movl(limit, result);
8567     // Fallthru to tail compare
8568   }
8569 
8570   // Compare 4-byte vectors
8571   andl(limit, 0xfffffffc); // vector count (in bytes)
8572   jccb(Assembler::zero, COMPARE_CHAR);
8573 
8574   lea(ary1, Address(ary1, limit, Address::times_1));
8575   lea(ary2, Address(ary2, limit, Address::times_1));
8576   negptr(limit);
8577 
8578   bind(COMPARE_VECTORS);
8579   movl(chr, Address(ary1, limit, Address::times_1));
8580   cmpl(chr, Address(ary2, limit, Address::times_1));
8581   jccb(Assembler::notEqual, FALSE_LABEL);
8582   addptr(limit, 4);
8583   jcc(Assembler::notZero, COMPARE_VECTORS);
8584 
8585   // Compare trailing char (final 2 bytes), if any
8586   bind(COMPARE_CHAR);
8587   testl(result, 0x2);   // tail  char
8588   jccb(Assembler::zero, COMPARE_BYTE);
8589   load_unsigned_short(chr, Address(ary1, 0));
8590   load_unsigned_short(limit, Address(ary2, 0));
8591   cmpl(chr, limit);
8592   jccb(Assembler::notEqual, FALSE_LABEL);
8593 
8594   if (is_array_equ && is_char) {
8595     bind(COMPARE_BYTE);
8596   } else {
8597     lea(ary1, Address(ary1, 2));
8598     lea(ary2, Address(ary2, 2));
8599 
8600     bind(COMPARE_BYTE);
8601     testl(result, 0x1);   // tail  byte
8602     jccb(Assembler::zero, TRUE_LABEL);
8603     load_unsigned_byte(chr, Address(ary1, 0));
8604     load_unsigned_byte(limit, Address(ary2, 0));
8605     cmpl(chr, limit);
8606     jccb(Assembler::notEqual, FALSE_LABEL);
8607   }
8608   bind(TRUE_LABEL);
8609   movl(result, 1);   // return true
8610   jmpb(DONE);
8611 
8612   bind(FALSE_LABEL);
8613   xorl(result, result); // return false
8614 
8615   // That's it
8616   bind(DONE);
8617   if (UseAVX >= 2) {
8618     // clean upper bits of YMM registers
8619     vpxor(vec1, vec1);
8620     vpxor(vec2, vec2);
8621   }
8622 }
8623 
8624 #endif
8625 
8626 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8627                                    Register to, Register value, Register count,
8628                                    Register rtmp, XMMRegister xtmp) {
8629   ShortBranchVerifier sbv(this);
8630   assert_different_registers(to, value, count, rtmp);
8631   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8632   Label L_fill_2_bytes, L_fill_4_bytes;
8633 
8634   int shift = -1;
8635   switch (t) {
8636     case T_BYTE:
8637       shift = 2;
8638       break;
8639     case T_SHORT:
8640       shift = 1;
8641       break;
8642     case T_INT:
8643       shift = 0;
8644       break;
8645     default: ShouldNotReachHere();
8646   }
8647 
8648   if (t == T_BYTE) {
8649     andl(value, 0xff);
8650     movl(rtmp, value);
8651     shll(rtmp, 8);
8652     orl(value, rtmp);
8653   }
8654   if (t == T_SHORT) {
8655     andl(value, 0xffff);
8656   }
8657   if (t == T_BYTE || t == T_SHORT) {
8658     movl(rtmp, value);
8659     shll(rtmp, 16);
8660     orl(value, rtmp);
8661   }
8662 
8663   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8664   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8665   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8666     // align source address at 4 bytes address boundary
8667     if (t == T_BYTE) {
8668       // One byte misalignment happens only for byte arrays
8669       testptr(to, 1);
8670       jccb(Assembler::zero, L_skip_align1);
8671       movb(Address(to, 0), value);
8672       increment(to);
8673       decrement(count);
8674       BIND(L_skip_align1);
8675     }
8676     // Two bytes misalignment happens only for byte and short (char) arrays
8677     testptr(to, 2);
8678     jccb(Assembler::zero, L_skip_align2);
8679     movw(Address(to, 0), value);
8680     addptr(to, 2);
8681     subl(count, 1<<(shift-1));
8682     BIND(L_skip_align2);
8683   }
8684   if (UseSSE < 2) {
8685     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8686     // Fill 32-byte chunks
8687     subl(count, 8 << shift);
8688     jcc(Assembler::less, L_check_fill_8_bytes);
8689     align(16);
8690 
8691     BIND(L_fill_32_bytes_loop);
8692 
8693     for (int i = 0; i < 32; i += 4) {
8694       movl(Address(to, i), value);
8695     }
8696 
8697     addptr(to, 32);
8698     subl(count, 8 << shift);
8699     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8700     BIND(L_check_fill_8_bytes);
8701     addl(count, 8 << shift);
8702     jccb(Assembler::zero, L_exit);
8703     jmpb(L_fill_8_bytes);
8704 
8705     //
8706     // length is too short, just fill qwords
8707     //
8708     BIND(L_fill_8_bytes_loop);
8709     movl(Address(to, 0), value);
8710     movl(Address(to, 4), value);
8711     addptr(to, 8);
8712     BIND(L_fill_8_bytes);
8713     subl(count, 1 << (shift + 1));
8714     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8715     // fall through to fill 4 bytes
8716   } else {
8717     Label L_fill_32_bytes;
8718     if (!UseUnalignedLoadStores) {
8719       // align to 8 bytes, we know we are 4 byte aligned to start
8720       testptr(to, 4);
8721       jccb(Assembler::zero, L_fill_32_bytes);
8722       movl(Address(to, 0), value);
8723       addptr(to, 4);
8724       subl(count, 1<<shift);
8725     }
8726     BIND(L_fill_32_bytes);
8727     {
8728       assert( UseSSE >= 2, "supported cpu only" );
8729       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8730       if (UseAVX > 2) {
8731         movl(rtmp, 0xffff);
8732         kmovwl(k1, rtmp);
8733       }
8734       movdl(xtmp, value);
8735       if (UseAVX > 2 && UseUnalignedLoadStores) {
8736         // Fill 64-byte chunks
8737         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8738         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8739 
8740         subl(count, 16 << shift);
8741         jcc(Assembler::less, L_check_fill_32_bytes);
8742         align(16);
8743 
8744         BIND(L_fill_64_bytes_loop);
8745         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8746         addptr(to, 64);
8747         subl(count, 16 << shift);
8748         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8749 
8750         BIND(L_check_fill_32_bytes);
8751         addl(count, 8 << shift);
8752         jccb(Assembler::less, L_check_fill_8_bytes);
8753         vmovdqu(Address(to, 0), xtmp);
8754         addptr(to, 32);
8755         subl(count, 8 << shift);
8756 
8757         BIND(L_check_fill_8_bytes);
8758       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8759         // Fill 64-byte chunks
8760         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8761         vpbroadcastd(xtmp, xtmp);
8762 
8763         subl(count, 16 << shift);
8764         jcc(Assembler::less, L_check_fill_32_bytes);
8765         align(16);
8766 
8767         BIND(L_fill_64_bytes_loop);
8768         vmovdqu(Address(to, 0), xtmp);
8769         vmovdqu(Address(to, 32), xtmp);
8770         addptr(to, 64);
8771         subl(count, 16 << shift);
8772         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8773 
8774         BIND(L_check_fill_32_bytes);
8775         addl(count, 8 << shift);
8776         jccb(Assembler::less, L_check_fill_8_bytes);
8777         vmovdqu(Address(to, 0), xtmp);
8778         addptr(to, 32);
8779         subl(count, 8 << shift);
8780 
8781         BIND(L_check_fill_8_bytes);
8782         // clean upper bits of YMM registers
8783         movdl(xtmp, value);
8784         pshufd(xtmp, xtmp, 0);
8785       } else {
8786         // Fill 32-byte chunks
8787         pshufd(xtmp, xtmp, 0);
8788 
8789         subl(count, 8 << shift);
8790         jcc(Assembler::less, L_check_fill_8_bytes);
8791         align(16);
8792 
8793         BIND(L_fill_32_bytes_loop);
8794 
8795         if (UseUnalignedLoadStores) {
8796           movdqu(Address(to, 0), xtmp);
8797           movdqu(Address(to, 16), xtmp);
8798         } else {
8799           movq(Address(to, 0), xtmp);
8800           movq(Address(to, 8), xtmp);
8801           movq(Address(to, 16), xtmp);
8802           movq(Address(to, 24), xtmp);
8803         }
8804 
8805         addptr(to, 32);
8806         subl(count, 8 << shift);
8807         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8808 
8809         BIND(L_check_fill_8_bytes);
8810       }
8811       addl(count, 8 << shift);
8812       jccb(Assembler::zero, L_exit);
8813       jmpb(L_fill_8_bytes);
8814 
8815       //
8816       // length is too short, just fill qwords
8817       //
8818       BIND(L_fill_8_bytes_loop);
8819       movq(Address(to, 0), xtmp);
8820       addptr(to, 8);
8821       BIND(L_fill_8_bytes);
8822       subl(count, 1 << (shift + 1));
8823       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8824     }
8825   }
8826   // fill trailing 4 bytes
8827   BIND(L_fill_4_bytes);
8828   testl(count, 1<<shift);
8829   jccb(Assembler::zero, L_fill_2_bytes);
8830   movl(Address(to, 0), value);
8831   if (t == T_BYTE || t == T_SHORT) {
8832     addptr(to, 4);
8833     BIND(L_fill_2_bytes);
8834     // fill trailing 2 bytes
8835     testl(count, 1<<(shift-1));
8836     jccb(Assembler::zero, L_fill_byte);
8837     movw(Address(to, 0), value);
8838     if (t == T_BYTE) {
8839       addptr(to, 2);
8840       BIND(L_fill_byte);
8841       // fill trailing byte
8842       testl(count, 1);
8843       jccb(Assembler::zero, L_exit);
8844       movb(Address(to, 0), value);
8845     } else {
8846       BIND(L_fill_byte);
8847     }
8848   } else {
8849     BIND(L_fill_2_bytes);
8850   }
8851   BIND(L_exit);
8852 }
8853 
8854 // encode char[] to byte[] in ISO_8859_1
8855 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8856                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8857                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8858                                       Register tmp5, Register result) {
8859   // rsi: src
8860   // rdi: dst
8861   // rdx: len
8862   // rcx: tmp5
8863   // rax: result
8864   ShortBranchVerifier sbv(this);
8865   assert_different_registers(src, dst, len, tmp5, result);
8866   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8867 
8868   // set result
8869   xorl(result, result);
8870   // check for zero length
8871   testl(len, len);
8872   jcc(Assembler::zero, L_done);
8873   movl(result, len);
8874 
8875   // Setup pointers
8876   lea(src, Address(src, len, Address::times_2)); // char[]
8877   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8878   negptr(len);
8879 
8880   if (UseSSE42Intrinsics || UseAVX >= 2) {
8881     assert(UseSSE42Intrinsics ? UseSSE >= 4 : true, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
8882     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8883     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8884 
8885     if (UseAVX >= 2) {
8886       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8887       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8888       movdl(tmp1Reg, tmp5);
8889       vpbroadcastd(tmp1Reg, tmp1Reg);
8890       jmpb(L_chars_32_check);
8891 
8892       bind(L_copy_32_chars);
8893       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8894       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8895       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8896       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8897       jccb(Assembler::notZero, L_copy_32_chars_exit);
8898       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8899       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8900       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8901 
8902       bind(L_chars_32_check);
8903       addptr(len, 32);
8904       jccb(Assembler::lessEqual, L_copy_32_chars);
8905 
8906       bind(L_copy_32_chars_exit);
8907       subptr(len, 16);
8908       jccb(Assembler::greater, L_copy_16_chars_exit);
8909 
8910     } else if (UseSSE42Intrinsics) {
8911       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8912       movdl(tmp1Reg, tmp5);
8913       pshufd(tmp1Reg, tmp1Reg, 0);
8914       jmpb(L_chars_16_check);
8915     }
8916 
8917     bind(L_copy_16_chars);
8918     if (UseAVX >= 2) {
8919       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8920       vptest(tmp2Reg, tmp1Reg);
8921       jccb(Assembler::notZero, L_copy_16_chars_exit);
8922       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8923       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8924     } else {
8925       if (UseAVX > 0) {
8926         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8927         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8928         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8929       } else {
8930         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8931         por(tmp2Reg, tmp3Reg);
8932         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8933         por(tmp2Reg, tmp4Reg);
8934       }
8935       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8936       jccb(Assembler::notZero, L_copy_16_chars_exit);
8937       packuswb(tmp3Reg, tmp4Reg);
8938     }
8939     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8940 
8941     bind(L_chars_16_check);
8942     addptr(len, 16);
8943     jccb(Assembler::lessEqual, L_copy_16_chars);
8944 
8945     bind(L_copy_16_chars_exit);
8946     if (UseAVX >= 2) {
8947       // clean upper bits of YMM registers
8948       vpxor(tmp2Reg, tmp2Reg);
8949       vpxor(tmp3Reg, tmp3Reg);
8950       vpxor(tmp4Reg, tmp4Reg);
8951       movdl(tmp1Reg, tmp5);
8952       pshufd(tmp1Reg, tmp1Reg, 0);
8953     }
8954     subptr(len, 8);
8955     jccb(Assembler::greater, L_copy_8_chars_exit);
8956 
8957     bind(L_copy_8_chars);
8958     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8959     ptest(tmp3Reg, tmp1Reg);
8960     jccb(Assembler::notZero, L_copy_8_chars_exit);
8961     packuswb(tmp3Reg, tmp1Reg);
8962     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8963     addptr(len, 8);
8964     jccb(Assembler::lessEqual, L_copy_8_chars);
8965 
8966     bind(L_copy_8_chars_exit);
8967     subptr(len, 8);
8968     jccb(Assembler::zero, L_done);
8969   }
8970 
8971   bind(L_copy_1_char);
8972   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8973   testl(tmp5, 0xff00);      // check if Unicode char
8974   jccb(Assembler::notZero, L_copy_1_char_exit);
8975   movb(Address(dst, len, Address::times_1, 0), tmp5);
8976   addptr(len, 1);
8977   jccb(Assembler::less, L_copy_1_char);
8978 
8979   bind(L_copy_1_char_exit);
8980   addptr(result, len); // len is negative count of not processed elements
8981   bind(L_done);
8982 }
8983 
8984 #ifdef _LP64
8985 /**
8986  * Helper for multiply_to_len().
8987  */
8988 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8989   addq(dest_lo, src1);
8990   adcq(dest_hi, 0);
8991   addq(dest_lo, src2);
8992   adcq(dest_hi, 0);
8993 }
8994 
8995 /**
8996  * Multiply 64 bit by 64 bit first loop.
8997  */
8998 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8999                                            Register y, Register y_idx, Register z,
9000                                            Register carry, Register product,
9001                                            Register idx, Register kdx) {
9002   //
9003   //  jlong carry, x[], y[], z[];
9004   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9005   //    huge_128 product = y[idx] * x[xstart] + carry;
9006   //    z[kdx] = (jlong)product;
9007   //    carry  = (jlong)(product >>> 64);
9008   //  }
9009   //  z[xstart] = carry;
9010   //
9011 
9012   Label L_first_loop, L_first_loop_exit;
9013   Label L_one_x, L_one_y, L_multiply;
9014 
9015   decrementl(xstart);
9016   jcc(Assembler::negative, L_one_x);
9017 
9018   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9019   rorq(x_xstart, 32); // convert big-endian to little-endian
9020 
9021   bind(L_first_loop);
9022   decrementl(idx);
9023   jcc(Assembler::negative, L_first_loop_exit);
9024   decrementl(idx);
9025   jcc(Assembler::negative, L_one_y);
9026   movq(y_idx, Address(y, idx, Address::times_4,  0));
9027   rorq(y_idx, 32); // convert big-endian to little-endian
9028   bind(L_multiply);
9029   movq(product, x_xstart);
9030   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9031   addq(product, carry);
9032   adcq(rdx, 0);
9033   subl(kdx, 2);
9034   movl(Address(z, kdx, Address::times_4,  4), product);
9035   shrq(product, 32);
9036   movl(Address(z, kdx, Address::times_4,  0), product);
9037   movq(carry, rdx);
9038   jmp(L_first_loop);
9039 
9040   bind(L_one_y);
9041   movl(y_idx, Address(y,  0));
9042   jmp(L_multiply);
9043 
9044   bind(L_one_x);
9045   movl(x_xstart, Address(x,  0));
9046   jmp(L_first_loop);
9047 
9048   bind(L_first_loop_exit);
9049 }
9050 
9051 /**
9052  * Multiply 64 bit by 64 bit and add 128 bit.
9053  */
9054 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9055                                             Register yz_idx, Register idx,
9056                                             Register carry, Register product, int offset) {
9057   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9058   //     z[kdx] = (jlong)product;
9059 
9060   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9061   rorq(yz_idx, 32); // convert big-endian to little-endian
9062   movq(product, x_xstart);
9063   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9064   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9065   rorq(yz_idx, 32); // convert big-endian to little-endian
9066 
9067   add2_with_carry(rdx, product, carry, yz_idx);
9068 
9069   movl(Address(z, idx, Address::times_4,  offset+4), product);
9070   shrq(product, 32);
9071   movl(Address(z, idx, Address::times_4,  offset), product);
9072 
9073 }
9074 
9075 /**
9076  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9077  */
9078 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9079                                              Register yz_idx, Register idx, Register jdx,
9080                                              Register carry, Register product,
9081                                              Register carry2) {
9082   //   jlong carry, x[], y[], z[];
9083   //   int kdx = ystart+1;
9084   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9085   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9086   //     z[kdx+idx+1] = (jlong)product;
9087   //     jlong carry2  = (jlong)(product >>> 64);
9088   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9089   //     z[kdx+idx] = (jlong)product;
9090   //     carry  = (jlong)(product >>> 64);
9091   //   }
9092   //   idx += 2;
9093   //   if (idx > 0) {
9094   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9095   //     z[kdx+idx] = (jlong)product;
9096   //     carry  = (jlong)(product >>> 64);
9097   //   }
9098   //
9099 
9100   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9101 
9102   movl(jdx, idx);
9103   andl(jdx, 0xFFFFFFFC);
9104   shrl(jdx, 2);
9105 
9106   bind(L_third_loop);
9107   subl(jdx, 1);
9108   jcc(Assembler::negative, L_third_loop_exit);
9109   subl(idx, 4);
9110 
9111   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9112   movq(carry2, rdx);
9113 
9114   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9115   movq(carry, rdx);
9116   jmp(L_third_loop);
9117 
9118   bind (L_third_loop_exit);
9119 
9120   andl (idx, 0x3);
9121   jcc(Assembler::zero, L_post_third_loop_done);
9122 
9123   Label L_check_1;
9124   subl(idx, 2);
9125   jcc(Assembler::negative, L_check_1);
9126 
9127   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9128   movq(carry, rdx);
9129 
9130   bind (L_check_1);
9131   addl (idx, 0x2);
9132   andl (idx, 0x1);
9133   subl(idx, 1);
9134   jcc(Assembler::negative, L_post_third_loop_done);
9135 
9136   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9137   movq(product, x_xstart);
9138   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9139   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9140 
9141   add2_with_carry(rdx, product, yz_idx, carry);
9142 
9143   movl(Address(z, idx, Address::times_4,  0), product);
9144   shrq(product, 32);
9145 
9146   shlq(rdx, 32);
9147   orq(product, rdx);
9148   movq(carry, product);
9149 
9150   bind(L_post_third_loop_done);
9151 }
9152 
9153 /**
9154  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9155  *
9156  */
9157 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9158                                                   Register carry, Register carry2,
9159                                                   Register idx, Register jdx,
9160                                                   Register yz_idx1, Register yz_idx2,
9161                                                   Register tmp, Register tmp3, Register tmp4) {
9162   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9163 
9164   //   jlong carry, x[], y[], z[];
9165   //   int kdx = ystart+1;
9166   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9167   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9168   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9169   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9170   //     carry  = (jlong)(tmp4 >>> 64);
9171   //     z[kdx+idx+1] = (jlong)tmp3;
9172   //     z[kdx+idx] = (jlong)tmp4;
9173   //   }
9174   //   idx += 2;
9175   //   if (idx > 0) {
9176   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9177   //     z[kdx+idx] = (jlong)yz_idx1;
9178   //     carry  = (jlong)(yz_idx1 >>> 64);
9179   //   }
9180   //
9181 
9182   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9183 
9184   movl(jdx, idx);
9185   andl(jdx, 0xFFFFFFFC);
9186   shrl(jdx, 2);
9187 
9188   bind(L_third_loop);
9189   subl(jdx, 1);
9190   jcc(Assembler::negative, L_third_loop_exit);
9191   subl(idx, 4);
9192 
9193   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9194   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9195   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9196   rorxq(yz_idx2, yz_idx2, 32);
9197 
9198   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9199   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9200 
9201   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9202   rorxq(yz_idx1, yz_idx1, 32);
9203   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9204   rorxq(yz_idx2, yz_idx2, 32);
9205 
9206   if (VM_Version::supports_adx()) {
9207     adcxq(tmp3, carry);
9208     adoxq(tmp3, yz_idx1);
9209 
9210     adcxq(tmp4, tmp);
9211     adoxq(tmp4, yz_idx2);
9212 
9213     movl(carry, 0); // does not affect flags
9214     adcxq(carry2, carry);
9215     adoxq(carry2, carry);
9216   } else {
9217     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9218     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9219   }
9220   movq(carry, carry2);
9221 
9222   movl(Address(z, idx, Address::times_4, 12), tmp3);
9223   shrq(tmp3, 32);
9224   movl(Address(z, idx, Address::times_4,  8), tmp3);
9225 
9226   movl(Address(z, idx, Address::times_4,  4), tmp4);
9227   shrq(tmp4, 32);
9228   movl(Address(z, idx, Address::times_4,  0), tmp4);
9229 
9230   jmp(L_third_loop);
9231 
9232   bind (L_third_loop_exit);
9233 
9234   andl (idx, 0x3);
9235   jcc(Assembler::zero, L_post_third_loop_done);
9236 
9237   Label L_check_1;
9238   subl(idx, 2);
9239   jcc(Assembler::negative, L_check_1);
9240 
9241   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9242   rorxq(yz_idx1, yz_idx1, 32);
9243   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9244   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9245   rorxq(yz_idx2, yz_idx2, 32);
9246 
9247   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9248 
9249   movl(Address(z, idx, Address::times_4,  4), tmp3);
9250   shrq(tmp3, 32);
9251   movl(Address(z, idx, Address::times_4,  0), tmp3);
9252   movq(carry, tmp4);
9253 
9254   bind (L_check_1);
9255   addl (idx, 0x2);
9256   andl (idx, 0x1);
9257   subl(idx, 1);
9258   jcc(Assembler::negative, L_post_third_loop_done);
9259   movl(tmp4, Address(y, idx, Address::times_4,  0));
9260   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9261   movl(tmp4, Address(z, idx, Address::times_4,  0));
9262 
9263   add2_with_carry(carry2, tmp3, tmp4, carry);
9264 
9265   movl(Address(z, idx, Address::times_4,  0), tmp3);
9266   shrq(tmp3, 32);
9267 
9268   shlq(carry2, 32);
9269   orq(tmp3, carry2);
9270   movq(carry, tmp3);
9271 
9272   bind(L_post_third_loop_done);
9273 }
9274 
9275 /**
9276  * Code for BigInteger::multiplyToLen() instrinsic.
9277  *
9278  * rdi: x
9279  * rax: xlen
9280  * rsi: y
9281  * rcx: ylen
9282  * r8:  z
9283  * r11: zlen
9284  * r12: tmp1
9285  * r13: tmp2
9286  * r14: tmp3
9287  * r15: tmp4
9288  * rbx: tmp5
9289  *
9290  */
9291 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9292                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9293   ShortBranchVerifier sbv(this);
9294   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9295 
9296   push(tmp1);
9297   push(tmp2);
9298   push(tmp3);
9299   push(tmp4);
9300   push(tmp5);
9301 
9302   push(xlen);
9303   push(zlen);
9304 
9305   const Register idx = tmp1;
9306   const Register kdx = tmp2;
9307   const Register xstart = tmp3;
9308 
9309   const Register y_idx = tmp4;
9310   const Register carry = tmp5;
9311   const Register product  = xlen;
9312   const Register x_xstart = zlen;  // reuse register
9313 
9314   // First Loop.
9315   //
9316   //  final static long LONG_MASK = 0xffffffffL;
9317   //  int xstart = xlen - 1;
9318   //  int ystart = ylen - 1;
9319   //  long carry = 0;
9320   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9321   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9322   //    z[kdx] = (int)product;
9323   //    carry = product >>> 32;
9324   //  }
9325   //  z[xstart] = (int)carry;
9326   //
9327 
9328   movl(idx, ylen);      // idx = ylen;
9329   movl(kdx, zlen);      // kdx = xlen+ylen;
9330   xorq(carry, carry);   // carry = 0;
9331 
9332   Label L_done;
9333 
9334   movl(xstart, xlen);
9335   decrementl(xstart);
9336   jcc(Assembler::negative, L_done);
9337 
9338   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9339 
9340   Label L_second_loop;
9341   testl(kdx, kdx);
9342   jcc(Assembler::zero, L_second_loop);
9343 
9344   Label L_carry;
9345   subl(kdx, 1);
9346   jcc(Assembler::zero, L_carry);
9347 
9348   movl(Address(z, kdx, Address::times_4,  0), carry);
9349   shrq(carry, 32);
9350   subl(kdx, 1);
9351 
9352   bind(L_carry);
9353   movl(Address(z, kdx, Address::times_4,  0), carry);
9354 
9355   // Second and third (nested) loops.
9356   //
9357   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9358   //   carry = 0;
9359   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9360   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9361   //                    (z[k] & LONG_MASK) + carry;
9362   //     z[k] = (int)product;
9363   //     carry = product >>> 32;
9364   //   }
9365   //   z[i] = (int)carry;
9366   // }
9367   //
9368   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9369 
9370   const Register jdx = tmp1;
9371 
9372   bind(L_second_loop);
9373   xorl(carry, carry);    // carry = 0;
9374   movl(jdx, ylen);       // j = ystart+1
9375 
9376   subl(xstart, 1);       // i = xstart-1;
9377   jcc(Assembler::negative, L_done);
9378 
9379   push (z);
9380 
9381   Label L_last_x;
9382   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9383   subl(xstart, 1);       // i = xstart-1;
9384   jcc(Assembler::negative, L_last_x);
9385 
9386   if (UseBMI2Instructions) {
9387     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9388     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9389   } else {
9390     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9391     rorq(x_xstart, 32);  // convert big-endian to little-endian
9392   }
9393 
9394   Label L_third_loop_prologue;
9395   bind(L_third_loop_prologue);
9396 
9397   push (x);
9398   push (xstart);
9399   push (ylen);
9400 
9401 
9402   if (UseBMI2Instructions) {
9403     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9404   } else { // !UseBMI2Instructions
9405     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9406   }
9407 
9408   pop(ylen);
9409   pop(xlen);
9410   pop(x);
9411   pop(z);
9412 
9413   movl(tmp3, xlen);
9414   addl(tmp3, 1);
9415   movl(Address(z, tmp3, Address::times_4,  0), carry);
9416   subl(tmp3, 1);
9417   jccb(Assembler::negative, L_done);
9418 
9419   shrq(carry, 32);
9420   movl(Address(z, tmp3, Address::times_4,  0), carry);
9421   jmp(L_second_loop);
9422 
9423   // Next infrequent code is moved outside loops.
9424   bind(L_last_x);
9425   if (UseBMI2Instructions) {
9426     movl(rdx, Address(x,  0));
9427   } else {
9428     movl(x_xstart, Address(x,  0));
9429   }
9430   jmp(L_third_loop_prologue);
9431 
9432   bind(L_done);
9433 
9434   pop(zlen);
9435   pop(xlen);
9436 
9437   pop(tmp5);
9438   pop(tmp4);
9439   pop(tmp3);
9440   pop(tmp2);
9441   pop(tmp1);
9442 }
9443 
9444 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9445   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9446   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9447   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9448   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9449   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9450   Label SAME_TILL_END, DONE;
9451   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9452 
9453   //scale is in rcx in both Win64 and Unix
9454   ShortBranchVerifier sbv(this);
9455 
9456   shlq(length);
9457   xorq(result, result);
9458 
9459   cmpq(length, 8);
9460   jcc(Assembler::equal, VECTOR8_LOOP);
9461   jcc(Assembler::less, VECTOR4_TAIL);
9462 
9463   if (UseAVX >= 2){
9464 
9465     cmpq(length, 16);
9466     jcc(Assembler::equal, VECTOR16_LOOP);
9467     jcc(Assembler::less, VECTOR8_LOOP);
9468 
9469     cmpq(length, 32);
9470     jccb(Assembler::less, VECTOR16_TAIL);
9471 
9472     subq(length, 32);
9473     bind(VECTOR32_LOOP);
9474     vmovdqu(rymm0, Address(obja, result));
9475     vmovdqu(rymm1, Address(objb, result));
9476     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9477     vptest(rymm2, rymm2);
9478     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9479     addq(result, 32);
9480     subq(length, 32);
9481     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9482     addq(length, 32);
9483     jcc(Assembler::equal, SAME_TILL_END);
9484     //falling through if less than 32 bytes left //close the branch here.
9485 
9486     bind(VECTOR16_TAIL);
9487     cmpq(length, 16);
9488     jccb(Assembler::less, VECTOR8_TAIL);
9489     bind(VECTOR16_LOOP);
9490     movdqu(rymm0, Address(obja, result));
9491     movdqu(rymm1, Address(objb, result));
9492     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9493     ptest(rymm2, rymm2);
9494     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9495     addq(result, 16);
9496     subq(length, 16);
9497     jcc(Assembler::equal, SAME_TILL_END);
9498     //falling through if less than 16 bytes left
9499   } else {//regular intrinsics
9500 
9501     cmpq(length, 16);
9502     jccb(Assembler::less, VECTOR8_TAIL);
9503 
9504     subq(length, 16);
9505     bind(VECTOR16_LOOP);
9506     movdqu(rymm0, Address(obja, result));
9507     movdqu(rymm1, Address(objb, result));
9508     pxor(rymm0, rymm1);
9509     ptest(rymm0, rymm0);
9510     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9511     addq(result, 16);
9512     subq(length, 16);
9513     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9514     addq(length, 16);
9515     jcc(Assembler::equal, SAME_TILL_END);
9516     //falling through if less than 16 bytes left
9517   }
9518 
9519   bind(VECTOR8_TAIL);
9520   cmpq(length, 8);
9521   jccb(Assembler::less, VECTOR4_TAIL);
9522   bind(VECTOR8_LOOP);
9523   movq(tmp1, Address(obja, result));
9524   movq(tmp2, Address(objb, result));
9525   xorq(tmp1, tmp2);
9526   testq(tmp1, tmp1);
9527   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9528   addq(result, 8);
9529   subq(length, 8);
9530   jcc(Assembler::equal, SAME_TILL_END);
9531   //falling through if less than 8 bytes left
9532 
9533   bind(VECTOR4_TAIL);
9534   cmpq(length, 4);
9535   jccb(Assembler::less, BYTES_TAIL);
9536   bind(VECTOR4_LOOP);
9537   movl(tmp1, Address(obja, result));
9538   xorl(tmp1, Address(objb, result));
9539   testl(tmp1, tmp1);
9540   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9541   addq(result, 4);
9542   subq(length, 4);
9543   jcc(Assembler::equal, SAME_TILL_END);
9544   //falling through if less than 4 bytes left
9545 
9546   bind(BYTES_TAIL);
9547   bind(BYTES_LOOP);
9548   load_unsigned_byte(tmp1, Address(obja, result));
9549   load_unsigned_byte(tmp2, Address(objb, result));
9550   xorl(tmp1, tmp2);
9551   testl(tmp1, tmp1);
9552   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9553   decq(length);
9554   jccb(Assembler::zero, SAME_TILL_END);
9555   incq(result);
9556   load_unsigned_byte(tmp1, Address(obja, result));
9557   load_unsigned_byte(tmp2, Address(objb, result));
9558   xorl(tmp1, tmp2);
9559   testl(tmp1, tmp1);
9560   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9561   decq(length);
9562   jccb(Assembler::zero, SAME_TILL_END);
9563   incq(result);
9564   load_unsigned_byte(tmp1, Address(obja, result));
9565   load_unsigned_byte(tmp2, Address(objb, result));
9566   xorl(tmp1, tmp2);
9567   testl(tmp1, tmp1);
9568   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9569   jmpb(SAME_TILL_END);
9570 
9571   if (UseAVX >= 2){
9572     bind(VECTOR32_NOT_EQUAL);
9573     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9574     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9575     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9576     vpmovmskb(tmp1, rymm0);
9577     bsfq(tmp1, tmp1);
9578     addq(result, tmp1);
9579     shrq(result);
9580     jmpb(DONE);
9581   }
9582 
9583   bind(VECTOR16_NOT_EQUAL);
9584   if (UseAVX >= 2){
9585     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9586     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9587     pxor(rymm0, rymm2);
9588   } else {
9589     pcmpeqb(rymm2, rymm2);
9590     pxor(rymm0, rymm1);
9591     pcmpeqb(rymm0, rymm1);
9592     pxor(rymm0, rymm2);
9593   }
9594   pmovmskb(tmp1, rymm0);
9595   bsfq(tmp1, tmp1);
9596   addq(result, tmp1);
9597   shrq(result);
9598   jmpb(DONE);
9599 
9600   bind(VECTOR8_NOT_EQUAL);
9601   bind(VECTOR4_NOT_EQUAL);
9602   bsfq(tmp1, tmp1);
9603   shrq(tmp1, 3);
9604   addq(result, tmp1);
9605   bind(BYTES_NOT_EQUAL);
9606   shrq(result);
9607   jmpb(DONE);
9608 
9609   bind(SAME_TILL_END);
9610   mov64(result, -1);
9611 
9612   bind(DONE);
9613 }
9614 
9615 
9616 //Helper functions for square_to_len()
9617 
9618 /**
9619  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9620  * Preserves x and z and modifies rest of the registers.
9621  */
9622 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9623   // Perform square and right shift by 1
9624   // Handle odd xlen case first, then for even xlen do the following
9625   // jlong carry = 0;
9626   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9627   //     huge_128 product = x[j:j+1] * x[j:j+1];
9628   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9629   //     z[i+2:i+3] = (jlong)(product >>> 1);
9630   //     carry = (jlong)product;
9631   // }
9632 
9633   xorq(tmp5, tmp5);     // carry
9634   xorq(rdxReg, rdxReg);
9635   xorl(tmp1, tmp1);     // index for x
9636   xorl(tmp4, tmp4);     // index for z
9637 
9638   Label L_first_loop, L_first_loop_exit;
9639 
9640   testl(xlen, 1);
9641   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9642 
9643   // Square and right shift by 1 the odd element using 32 bit multiply
9644   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9645   imulq(raxReg, raxReg);
9646   shrq(raxReg, 1);
9647   adcq(tmp5, 0);
9648   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9649   incrementl(tmp1);
9650   addl(tmp4, 2);
9651 
9652   // Square and  right shift by 1 the rest using 64 bit multiply
9653   bind(L_first_loop);
9654   cmpptr(tmp1, xlen);
9655   jccb(Assembler::equal, L_first_loop_exit);
9656 
9657   // Square
9658   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9659   rorq(raxReg, 32);    // convert big-endian to little-endian
9660   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9661 
9662   // Right shift by 1 and save carry
9663   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9664   rcrq(rdxReg, 1);
9665   rcrq(raxReg, 1);
9666   adcq(tmp5, 0);
9667 
9668   // Store result in z
9669   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9670   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9671 
9672   // Update indices for x and z
9673   addl(tmp1, 2);
9674   addl(tmp4, 4);
9675   jmp(L_first_loop);
9676 
9677   bind(L_first_loop_exit);
9678 }
9679 
9680 
9681 /**
9682  * Perform the following multiply add operation using BMI2 instructions
9683  * carry:sum = sum + op1*op2 + carry
9684  * op2 should be in rdx
9685  * op2 is preserved, all other registers are modified
9686  */
9687 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9688   // assert op2 is rdx
9689   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9690   addq(sum, carry);
9691   adcq(tmp2, 0);
9692   addq(sum, op1);
9693   adcq(tmp2, 0);
9694   movq(carry, tmp2);
9695 }
9696 
9697 /**
9698  * Perform the following multiply add operation:
9699  * carry:sum = sum + op1*op2 + carry
9700  * Preserves op1, op2 and modifies rest of registers
9701  */
9702 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9703   // rdx:rax = op1 * op2
9704   movq(raxReg, op2);
9705   mulq(op1);
9706 
9707   //  rdx:rax = sum + carry + rdx:rax
9708   addq(sum, carry);
9709   adcq(rdxReg, 0);
9710   addq(sum, raxReg);
9711   adcq(rdxReg, 0);
9712 
9713   // carry:sum = rdx:sum
9714   movq(carry, rdxReg);
9715 }
9716 
9717 /**
9718  * Add 64 bit long carry into z[] with carry propogation.
9719  * Preserves z and carry register values and modifies rest of registers.
9720  *
9721  */
9722 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9723   Label L_fourth_loop, L_fourth_loop_exit;
9724 
9725   movl(tmp1, 1);
9726   subl(zlen, 2);
9727   addq(Address(z, zlen, Address::times_4, 0), carry);
9728 
9729   bind(L_fourth_loop);
9730   jccb(Assembler::carryClear, L_fourth_loop_exit);
9731   subl(zlen, 2);
9732   jccb(Assembler::negative, L_fourth_loop_exit);
9733   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9734   jmp(L_fourth_loop);
9735   bind(L_fourth_loop_exit);
9736 }
9737 
9738 /**
9739  * Shift z[] left by 1 bit.
9740  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9741  *
9742  */
9743 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9744 
9745   Label L_fifth_loop, L_fifth_loop_exit;
9746 
9747   // Fifth loop
9748   // Perform primitiveLeftShift(z, zlen, 1)
9749 
9750   const Register prev_carry = tmp1;
9751   const Register new_carry = tmp4;
9752   const Register value = tmp2;
9753   const Register zidx = tmp3;
9754 
9755   // int zidx, carry;
9756   // long value;
9757   // carry = 0;
9758   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9759   //    (carry:value)  = (z[i] << 1) | carry ;
9760   //    z[i] = value;
9761   // }
9762 
9763   movl(zidx, zlen);
9764   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9765 
9766   bind(L_fifth_loop);
9767   decl(zidx);  // Use decl to preserve carry flag
9768   decl(zidx);
9769   jccb(Assembler::negative, L_fifth_loop_exit);
9770 
9771   if (UseBMI2Instructions) {
9772      movq(value, Address(z, zidx, Address::times_4, 0));
9773      rclq(value, 1);
9774      rorxq(value, value, 32);
9775      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9776   }
9777   else {
9778     // clear new_carry
9779     xorl(new_carry, new_carry);
9780 
9781     // Shift z[i] by 1, or in previous carry and save new carry
9782     movq(value, Address(z, zidx, Address::times_4, 0));
9783     shlq(value, 1);
9784     adcl(new_carry, 0);
9785 
9786     orq(value, prev_carry);
9787     rorq(value, 0x20);
9788     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9789 
9790     // Set previous carry = new carry
9791     movl(prev_carry, new_carry);
9792   }
9793   jmp(L_fifth_loop);
9794 
9795   bind(L_fifth_loop_exit);
9796 }
9797 
9798 
9799 /**
9800  * Code for BigInteger::squareToLen() intrinsic
9801  *
9802  * rdi: x
9803  * rsi: len
9804  * r8:  z
9805  * rcx: zlen
9806  * r12: tmp1
9807  * r13: tmp2
9808  * r14: tmp3
9809  * r15: tmp4
9810  * rbx: tmp5
9811  *
9812  */
9813 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) {
9814 
9815   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;
9816   push(tmp1);
9817   push(tmp2);
9818   push(tmp3);
9819   push(tmp4);
9820   push(tmp5);
9821 
9822   // First loop
9823   // Store the squares, right shifted one bit (i.e., divided by 2).
9824   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9825 
9826   // Add in off-diagonal sums.
9827   //
9828   // Second, third (nested) and fourth loops.
9829   // zlen +=2;
9830   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9831   //    carry = 0;
9832   //    long op2 = x[xidx:xidx+1];
9833   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9834   //       k -= 2;
9835   //       long op1 = x[j:j+1];
9836   //       long sum = z[k:k+1];
9837   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9838   //       z[k:k+1] = sum;
9839   //    }
9840   //    add_one_64(z, k, carry, tmp_regs);
9841   // }
9842 
9843   const Register carry = tmp5;
9844   const Register sum = tmp3;
9845   const Register op1 = tmp4;
9846   Register op2 = tmp2;
9847 
9848   push(zlen);
9849   push(len);
9850   addl(zlen,2);
9851   bind(L_second_loop);
9852   xorq(carry, carry);
9853   subl(zlen, 4);
9854   subl(len, 2);
9855   push(zlen);
9856   push(len);
9857   cmpl(len, 0);
9858   jccb(Assembler::lessEqual, L_second_loop_exit);
9859 
9860   // Multiply an array by one 64 bit long.
9861   if (UseBMI2Instructions) {
9862     op2 = rdxReg;
9863     movq(op2, Address(x, len, Address::times_4,  0));
9864     rorxq(op2, op2, 32);
9865   }
9866   else {
9867     movq(op2, Address(x, len, Address::times_4,  0));
9868     rorq(op2, 32);
9869   }
9870 
9871   bind(L_third_loop);
9872   decrementl(len);
9873   jccb(Assembler::negative, L_third_loop_exit);
9874   decrementl(len);
9875   jccb(Assembler::negative, L_last_x);
9876 
9877   movq(op1, Address(x, len, Address::times_4,  0));
9878   rorq(op1, 32);
9879 
9880   bind(L_multiply);
9881   subl(zlen, 2);
9882   movq(sum, Address(z, zlen, Address::times_4,  0));
9883 
9884   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9885   if (UseBMI2Instructions) {
9886     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9887   }
9888   else {
9889     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9890   }
9891 
9892   movq(Address(z, zlen, Address::times_4, 0), sum);
9893 
9894   jmp(L_third_loop);
9895   bind(L_third_loop_exit);
9896 
9897   // Fourth loop
9898   // Add 64 bit long carry into z with carry propogation.
9899   // Uses offsetted zlen.
9900   add_one_64(z, zlen, carry, tmp1);
9901 
9902   pop(len);
9903   pop(zlen);
9904   jmp(L_second_loop);
9905 
9906   // Next infrequent code is moved outside loops.
9907   bind(L_last_x);
9908   movl(op1, Address(x, 0));
9909   jmp(L_multiply);
9910 
9911   bind(L_second_loop_exit);
9912   pop(len);
9913   pop(zlen);
9914   pop(len);
9915   pop(zlen);
9916 
9917   // Fifth loop
9918   // Shift z left 1 bit.
9919   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9920 
9921   // z[zlen-1] |= x[len-1] & 1;
9922   movl(tmp3, Address(x, len, Address::times_4, -4));
9923   andl(tmp3, 1);
9924   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9925 
9926   pop(tmp5);
9927   pop(tmp4);
9928   pop(tmp3);
9929   pop(tmp2);
9930   pop(tmp1);
9931 }
9932 
9933 /**
9934  * Helper function for mul_add()
9935  * Multiply the in[] by int k and add to out[] starting at offset offs using
9936  * 128 bit by 32 bit multiply and return the carry in tmp5.
9937  * Only quad int aligned length of in[] is operated on in this function.
9938  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9939  * This function preserves out, in and k registers.
9940  * len and offset point to the appropriate index in "in" & "out" correspondingly
9941  * tmp5 has the carry.
9942  * other registers are temporary and are modified.
9943  *
9944  */
9945 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9946   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9947   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9948 
9949   Label L_first_loop, L_first_loop_exit;
9950 
9951   movl(tmp1, len);
9952   shrl(tmp1, 2);
9953 
9954   bind(L_first_loop);
9955   subl(tmp1, 1);
9956   jccb(Assembler::negative, L_first_loop_exit);
9957 
9958   subl(len, 4);
9959   subl(offset, 4);
9960 
9961   Register op2 = tmp2;
9962   const Register sum = tmp3;
9963   const Register op1 = tmp4;
9964   const Register carry = tmp5;
9965 
9966   if (UseBMI2Instructions) {
9967     op2 = rdxReg;
9968   }
9969 
9970   movq(op1, Address(in, len, Address::times_4,  8));
9971   rorq(op1, 32);
9972   movq(sum, Address(out, offset, Address::times_4,  8));
9973   rorq(sum, 32);
9974   if (UseBMI2Instructions) {
9975     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9976   }
9977   else {
9978     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9979   }
9980   // Store back in big endian from little endian
9981   rorq(sum, 0x20);
9982   movq(Address(out, offset, Address::times_4,  8), sum);
9983 
9984   movq(op1, Address(in, len, Address::times_4,  0));
9985   rorq(op1, 32);
9986   movq(sum, Address(out, offset, Address::times_4,  0));
9987   rorq(sum, 32);
9988   if (UseBMI2Instructions) {
9989     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9990   }
9991   else {
9992     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9993   }
9994   // Store back in big endian from little endian
9995   rorq(sum, 0x20);
9996   movq(Address(out, offset, Address::times_4,  0), sum);
9997 
9998   jmp(L_first_loop);
9999   bind(L_first_loop_exit);
10000 }
10001 
10002 /**
10003  * Code for BigInteger::mulAdd() intrinsic
10004  *
10005  * rdi: out
10006  * rsi: in
10007  * r11: offs (out.length - offset)
10008  * rcx: len
10009  * r8:  k
10010  * r12: tmp1
10011  * r13: tmp2
10012  * r14: tmp3
10013  * r15: tmp4
10014  * rbx: tmp5
10015  * Multiply the in[] by word k and add to out[], return the carry in rax
10016  */
10017 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10018    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10019    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10020 
10021   Label L_carry, L_last_in, L_done;
10022 
10023 // carry = 0;
10024 // for (int j=len-1; j >= 0; j--) {
10025 //    long product = (in[j] & LONG_MASK) * kLong +
10026 //                   (out[offs] & LONG_MASK) + carry;
10027 //    out[offs--] = (int)product;
10028 //    carry = product >>> 32;
10029 // }
10030 //
10031   push(tmp1);
10032   push(tmp2);
10033   push(tmp3);
10034   push(tmp4);
10035   push(tmp5);
10036 
10037   Register op2 = tmp2;
10038   const Register sum = tmp3;
10039   const Register op1 = tmp4;
10040   const Register carry =  tmp5;
10041 
10042   if (UseBMI2Instructions) {
10043     op2 = rdxReg;
10044     movl(op2, k);
10045   }
10046   else {
10047     movl(op2, k);
10048   }
10049 
10050   xorq(carry, carry);
10051 
10052   //First loop
10053 
10054   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10055   //The carry is in tmp5
10056   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10057 
10058   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10059   decrementl(len);
10060   jccb(Assembler::negative, L_carry);
10061   decrementl(len);
10062   jccb(Assembler::negative, L_last_in);
10063 
10064   movq(op1, Address(in, len, Address::times_4,  0));
10065   rorq(op1, 32);
10066 
10067   subl(offs, 2);
10068   movq(sum, Address(out, offs, Address::times_4,  0));
10069   rorq(sum, 32);
10070 
10071   if (UseBMI2Instructions) {
10072     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10073   }
10074   else {
10075     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10076   }
10077 
10078   // Store back in big endian from little endian
10079   rorq(sum, 0x20);
10080   movq(Address(out, offs, Address::times_4,  0), sum);
10081 
10082   testl(len, len);
10083   jccb(Assembler::zero, L_carry);
10084 
10085   //Multiply the last in[] entry, if any
10086   bind(L_last_in);
10087   movl(op1, Address(in, 0));
10088   movl(sum, Address(out, offs, Address::times_4,  -4));
10089 
10090   movl(raxReg, k);
10091   mull(op1); //tmp4 * eax -> edx:eax
10092   addl(sum, carry);
10093   adcl(rdxReg, 0);
10094   addl(sum, raxReg);
10095   adcl(rdxReg, 0);
10096   movl(carry, rdxReg);
10097 
10098   movl(Address(out, offs, Address::times_4,  -4), sum);
10099 
10100   bind(L_carry);
10101   //return tmp5/carry as carry in rax
10102   movl(rax, carry);
10103 
10104   bind(L_done);
10105   pop(tmp5);
10106   pop(tmp4);
10107   pop(tmp3);
10108   pop(tmp2);
10109   pop(tmp1);
10110 }
10111 #endif
10112 
10113 /**
10114  * Emits code to update CRC-32 with a byte value according to constants in table
10115  *
10116  * @param [in,out]crc   Register containing the crc.
10117  * @param [in]val       Register containing the byte to fold into the CRC.
10118  * @param [in]table     Register containing the table of crc constants.
10119  *
10120  * uint32_t crc;
10121  * val = crc_table[(val ^ crc) & 0xFF];
10122  * crc = val ^ (crc >> 8);
10123  *
10124  */
10125 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10126   xorl(val, crc);
10127   andl(val, 0xFF);
10128   shrl(crc, 8); // unsigned shift
10129   xorl(crc, Address(table, val, Address::times_4, 0));
10130 }
10131 
10132 /**
10133  * Fold 128-bit data chunk
10134  */
10135 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10136   if (UseAVX > 0) {
10137     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10138     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10139     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10140     pxor(xcrc, xtmp);
10141   } else {
10142     movdqa(xtmp, xcrc);
10143     pclmulhdq(xtmp, xK);   // [123:64]
10144     pclmulldq(xcrc, xK);   // [63:0]
10145     pxor(xcrc, xtmp);
10146     movdqu(xtmp, Address(buf, offset));
10147     pxor(xcrc, xtmp);
10148   }
10149 }
10150 
10151 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10152   if (UseAVX > 0) {
10153     vpclmulhdq(xtmp, xK, xcrc);
10154     vpclmulldq(xcrc, xK, xcrc);
10155     pxor(xcrc, xbuf);
10156     pxor(xcrc, xtmp);
10157   } else {
10158     movdqa(xtmp, xcrc);
10159     pclmulhdq(xtmp, xK);
10160     pclmulldq(xcrc, xK);
10161     pxor(xcrc, xbuf);
10162     pxor(xcrc, xtmp);
10163   }
10164 }
10165 
10166 /**
10167  * 8-bit folds to compute 32-bit CRC
10168  *
10169  * uint64_t xcrc;
10170  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10171  */
10172 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10173   movdl(tmp, xcrc);
10174   andl(tmp, 0xFF);
10175   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10176   psrldq(xcrc, 1); // unsigned shift one byte
10177   pxor(xcrc, xtmp);
10178 }
10179 
10180 /**
10181  * uint32_t crc;
10182  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10183  */
10184 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10185   movl(tmp, crc);
10186   andl(tmp, 0xFF);
10187   shrl(crc, 8);
10188   xorl(crc, Address(table, tmp, Address::times_4, 0));
10189 }
10190 
10191 /**
10192  * @param crc   register containing existing CRC (32-bit)
10193  * @param buf   register pointing to input byte buffer (byte*)
10194  * @param len   register containing number of bytes
10195  * @param table register that will contain address of CRC table
10196  * @param tmp   scratch register
10197  */
10198 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10199   assert_different_registers(crc, buf, len, table, tmp, rax);
10200 
10201   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10202   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10203 
10204   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10205   // context for the registers used, where all instructions below are using 128-bit mode
10206   // On EVEX without VL and BW, these instructions will all be AVX.
10207   if (VM_Version::supports_avx512vlbw()) {
10208     movl(tmp, 0xffff);
10209     kmovwl(k1, tmp);
10210   }
10211 
10212   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10213   notl(crc); // ~crc
10214   cmpl(len, 16);
10215   jcc(Assembler::less, L_tail);
10216 
10217   // Align buffer to 16 bytes
10218   movl(tmp, buf);
10219   andl(tmp, 0xF);
10220   jccb(Assembler::zero, L_aligned);
10221   subl(tmp,  16);
10222   addl(len, tmp);
10223 
10224   align(4);
10225   BIND(L_align_loop);
10226   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10227   update_byte_crc32(crc, rax, table);
10228   increment(buf);
10229   incrementl(tmp);
10230   jccb(Assembler::less, L_align_loop);
10231 
10232   BIND(L_aligned);
10233   movl(tmp, len); // save
10234   shrl(len, 4);
10235   jcc(Assembler::zero, L_tail_restore);
10236 
10237   // Fold crc into first bytes of vector
10238   movdqa(xmm1, Address(buf, 0));
10239   movdl(rax, xmm1);
10240   xorl(crc, rax);
10241   pinsrd(xmm1, crc, 0);
10242   addptr(buf, 16);
10243   subl(len, 4); // len > 0
10244   jcc(Assembler::less, L_fold_tail);
10245 
10246   movdqa(xmm2, Address(buf,  0));
10247   movdqa(xmm3, Address(buf, 16));
10248   movdqa(xmm4, Address(buf, 32));
10249   addptr(buf, 48);
10250   subl(len, 3);
10251   jcc(Assembler::lessEqual, L_fold_512b);
10252 
10253   // Fold total 512 bits of polynomial on each iteration,
10254   // 128 bits per each of 4 parallel streams.
10255   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10256 
10257   align(32);
10258   BIND(L_fold_512b_loop);
10259   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10260   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10261   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10262   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10263   addptr(buf, 64);
10264   subl(len, 4);
10265   jcc(Assembler::greater, L_fold_512b_loop);
10266 
10267   // Fold 512 bits to 128 bits.
10268   BIND(L_fold_512b);
10269   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10270   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10271   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10272   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10273 
10274   // Fold the rest of 128 bits data chunks
10275   BIND(L_fold_tail);
10276   addl(len, 3);
10277   jccb(Assembler::lessEqual, L_fold_128b);
10278   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10279 
10280   BIND(L_fold_tail_loop);
10281   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10282   addptr(buf, 16);
10283   decrementl(len);
10284   jccb(Assembler::greater, L_fold_tail_loop);
10285 
10286   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10287   BIND(L_fold_128b);
10288   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10289   if (UseAVX > 0) {
10290     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10291     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10292     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10293   } else {
10294     movdqa(xmm2, xmm0);
10295     pclmulqdq(xmm2, xmm1, 0x1);
10296     movdqa(xmm3, xmm0);
10297     pand(xmm3, xmm2);
10298     pclmulqdq(xmm0, xmm3, 0x1);
10299   }
10300   psrldq(xmm1, 8);
10301   psrldq(xmm2, 4);
10302   pxor(xmm0, xmm1);
10303   pxor(xmm0, xmm2);
10304 
10305   // 8 8-bit folds to compute 32-bit CRC.
10306   for (int j = 0; j < 4; j++) {
10307     fold_8bit_crc32(xmm0, table, xmm1, rax);
10308   }
10309   movdl(crc, xmm0); // mov 32 bits to general register
10310   for (int j = 0; j < 4; j++) {
10311     fold_8bit_crc32(crc, table, rax);
10312   }
10313 
10314   BIND(L_tail_restore);
10315   movl(len, tmp); // restore
10316   BIND(L_tail);
10317   andl(len, 0xf);
10318   jccb(Assembler::zero, L_exit);
10319 
10320   // Fold the rest of bytes
10321   align(4);
10322   BIND(L_tail_loop);
10323   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10324   update_byte_crc32(crc, rax, table);
10325   increment(buf);
10326   decrementl(len);
10327   jccb(Assembler::greater, L_tail_loop);
10328 
10329   BIND(L_exit);
10330   notl(crc); // ~c
10331 }
10332 
10333 #ifdef _LP64
10334 // S. Gueron / Information Processing Letters 112 (2012) 184
10335 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10336 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10337 // Output: the 64-bit carry-less product of B * CONST
10338 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10339                                      Register tmp1, Register tmp2, Register tmp3) {
10340   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10341   if (n > 0) {
10342     addq(tmp3, n * 256 * 8);
10343   }
10344   //    Q1 = TABLEExt[n][B & 0xFF];
10345   movl(tmp1, in);
10346   andl(tmp1, 0x000000FF);
10347   shll(tmp1, 3);
10348   addq(tmp1, tmp3);
10349   movq(tmp1, Address(tmp1, 0));
10350 
10351   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10352   movl(tmp2, in);
10353   shrl(tmp2, 8);
10354   andl(tmp2, 0x000000FF);
10355   shll(tmp2, 3);
10356   addq(tmp2, tmp3);
10357   movq(tmp2, Address(tmp2, 0));
10358 
10359   shlq(tmp2, 8);
10360   xorq(tmp1, tmp2);
10361 
10362   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10363   movl(tmp2, in);
10364   shrl(tmp2, 16);
10365   andl(tmp2, 0x000000FF);
10366   shll(tmp2, 3);
10367   addq(tmp2, tmp3);
10368   movq(tmp2, Address(tmp2, 0));
10369 
10370   shlq(tmp2, 16);
10371   xorq(tmp1, tmp2);
10372 
10373   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10374   shrl(in, 24);
10375   andl(in, 0x000000FF);
10376   shll(in, 3);
10377   addq(in, tmp3);
10378   movq(in, Address(in, 0));
10379 
10380   shlq(in, 24);
10381   xorq(in, tmp1);
10382   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10383 }
10384 
10385 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10386                                       Register in_out,
10387                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10388                                       XMMRegister w_xtmp2,
10389                                       Register tmp1,
10390                                       Register n_tmp2, Register n_tmp3) {
10391   if (is_pclmulqdq_supported) {
10392     movdl(w_xtmp1, in_out); // modified blindly
10393 
10394     movl(tmp1, const_or_pre_comp_const_index);
10395     movdl(w_xtmp2, tmp1);
10396     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10397 
10398     movdq(in_out, w_xtmp1);
10399   } else {
10400     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10401   }
10402 }
10403 
10404 // Recombination Alternative 2: No bit-reflections
10405 // T1 = (CRC_A * U1) << 1
10406 // T2 = (CRC_B * U2) << 1
10407 // C1 = T1 >> 32
10408 // C2 = T2 >> 32
10409 // T1 = T1 & 0xFFFFFFFF
10410 // T2 = T2 & 0xFFFFFFFF
10411 // T1 = CRC32(0, T1)
10412 // T2 = CRC32(0, T2)
10413 // C1 = C1 ^ T1
10414 // C2 = C2 ^ T2
10415 // CRC = C1 ^ C2 ^ CRC_C
10416 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,
10417                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10418                                      Register tmp1, Register tmp2,
10419                                      Register n_tmp3) {
10420   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10421   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10422   shlq(in_out, 1);
10423   movl(tmp1, in_out);
10424   shrq(in_out, 32);
10425   xorl(tmp2, tmp2);
10426   crc32(tmp2, tmp1, 4);
10427   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10428   shlq(in1, 1);
10429   movl(tmp1, in1);
10430   shrq(in1, 32);
10431   xorl(tmp2, tmp2);
10432   crc32(tmp2, tmp1, 4);
10433   xorl(in1, tmp2);
10434   xorl(in_out, in1);
10435   xorl(in_out, in2);
10436 }
10437 
10438 // Set N to predefined value
10439 // Subtract from a lenght of a buffer
10440 // execute in a loop:
10441 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10442 // for i = 1 to N do
10443 //  CRC_A = CRC32(CRC_A, A[i])
10444 //  CRC_B = CRC32(CRC_B, B[i])
10445 //  CRC_C = CRC32(CRC_C, C[i])
10446 // end for
10447 // Recombine
10448 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,
10449                                        Register in_out1, Register in_out2, Register in_out3,
10450                                        Register tmp1, Register tmp2, Register tmp3,
10451                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10452                                        Register tmp4, Register tmp5,
10453                                        Register n_tmp6) {
10454   Label L_processPartitions;
10455   Label L_processPartition;
10456   Label L_exit;
10457 
10458   bind(L_processPartitions);
10459   cmpl(in_out1, 3 * size);
10460   jcc(Assembler::less, L_exit);
10461     xorl(tmp1, tmp1);
10462     xorl(tmp2, tmp2);
10463     movq(tmp3, in_out2);
10464     addq(tmp3, size);
10465 
10466     bind(L_processPartition);
10467       crc32(in_out3, Address(in_out2, 0), 8);
10468       crc32(tmp1, Address(in_out2, size), 8);
10469       crc32(tmp2, Address(in_out2, size * 2), 8);
10470       addq(in_out2, 8);
10471       cmpq(in_out2, tmp3);
10472       jcc(Assembler::less, L_processPartition);
10473     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10474             w_xtmp1, w_xtmp2, w_xtmp3,
10475             tmp4, tmp5,
10476             n_tmp6);
10477     addq(in_out2, 2 * size);
10478     subl(in_out1, 3 * size);
10479     jmp(L_processPartitions);
10480 
10481   bind(L_exit);
10482 }
10483 #else
10484 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10485                                      Register tmp1, Register tmp2, Register tmp3,
10486                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10487   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10488   if (n > 0) {
10489     addl(tmp3, n * 256 * 8);
10490   }
10491   //    Q1 = TABLEExt[n][B & 0xFF];
10492   movl(tmp1, in_out);
10493   andl(tmp1, 0x000000FF);
10494   shll(tmp1, 3);
10495   addl(tmp1, tmp3);
10496   movq(xtmp1, Address(tmp1, 0));
10497 
10498   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10499   movl(tmp2, in_out);
10500   shrl(tmp2, 8);
10501   andl(tmp2, 0x000000FF);
10502   shll(tmp2, 3);
10503   addl(tmp2, tmp3);
10504   movq(xtmp2, Address(tmp2, 0));
10505 
10506   psllq(xtmp2, 8);
10507   pxor(xtmp1, xtmp2);
10508 
10509   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10510   movl(tmp2, in_out);
10511   shrl(tmp2, 16);
10512   andl(tmp2, 0x000000FF);
10513   shll(tmp2, 3);
10514   addl(tmp2, tmp3);
10515   movq(xtmp2, Address(tmp2, 0));
10516 
10517   psllq(xtmp2, 16);
10518   pxor(xtmp1, xtmp2);
10519 
10520   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10521   shrl(in_out, 24);
10522   andl(in_out, 0x000000FF);
10523   shll(in_out, 3);
10524   addl(in_out, tmp3);
10525   movq(xtmp2, Address(in_out, 0));
10526 
10527   psllq(xtmp2, 24);
10528   pxor(xtmp1, xtmp2); // Result in CXMM
10529   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10530 }
10531 
10532 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10533                                       Register in_out,
10534                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10535                                       XMMRegister w_xtmp2,
10536                                       Register tmp1,
10537                                       Register n_tmp2, Register n_tmp3) {
10538   if (is_pclmulqdq_supported) {
10539     movdl(w_xtmp1, in_out);
10540 
10541     movl(tmp1, const_or_pre_comp_const_index);
10542     movdl(w_xtmp2, tmp1);
10543     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10544     // Keep result in XMM since GPR is 32 bit in length
10545   } else {
10546     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10547   }
10548 }
10549 
10550 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,
10551                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10552                                      Register tmp1, Register tmp2,
10553                                      Register n_tmp3) {
10554   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10555   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10556 
10557   psllq(w_xtmp1, 1);
10558   movdl(tmp1, w_xtmp1);
10559   psrlq(w_xtmp1, 32);
10560   movdl(in_out, w_xtmp1);
10561 
10562   xorl(tmp2, tmp2);
10563   crc32(tmp2, tmp1, 4);
10564   xorl(in_out, tmp2);
10565 
10566   psllq(w_xtmp2, 1);
10567   movdl(tmp1, w_xtmp2);
10568   psrlq(w_xtmp2, 32);
10569   movdl(in1, w_xtmp2);
10570 
10571   xorl(tmp2, tmp2);
10572   crc32(tmp2, tmp1, 4);
10573   xorl(in1, tmp2);
10574   xorl(in_out, in1);
10575   xorl(in_out, in2);
10576 }
10577 
10578 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,
10579                                        Register in_out1, Register in_out2, Register in_out3,
10580                                        Register tmp1, Register tmp2, Register tmp3,
10581                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10582                                        Register tmp4, Register tmp5,
10583                                        Register n_tmp6) {
10584   Label L_processPartitions;
10585   Label L_processPartition;
10586   Label L_exit;
10587 
10588   bind(L_processPartitions);
10589   cmpl(in_out1, 3 * size);
10590   jcc(Assembler::less, L_exit);
10591     xorl(tmp1, tmp1);
10592     xorl(tmp2, tmp2);
10593     movl(tmp3, in_out2);
10594     addl(tmp3, size);
10595 
10596     bind(L_processPartition);
10597       crc32(in_out3, Address(in_out2, 0), 4);
10598       crc32(tmp1, Address(in_out2, size), 4);
10599       crc32(tmp2, Address(in_out2, size*2), 4);
10600       crc32(in_out3, Address(in_out2, 0+4), 4);
10601       crc32(tmp1, Address(in_out2, size+4), 4);
10602       crc32(tmp2, Address(in_out2, size*2+4), 4);
10603       addl(in_out2, 8);
10604       cmpl(in_out2, tmp3);
10605       jcc(Assembler::less, L_processPartition);
10606 
10607         push(tmp3);
10608         push(in_out1);
10609         push(in_out2);
10610         tmp4 = tmp3;
10611         tmp5 = in_out1;
10612         n_tmp6 = in_out2;
10613 
10614       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10615             w_xtmp1, w_xtmp2, w_xtmp3,
10616             tmp4, tmp5,
10617             n_tmp6);
10618 
10619         pop(in_out2);
10620         pop(in_out1);
10621         pop(tmp3);
10622 
10623     addl(in_out2, 2 * size);
10624     subl(in_out1, 3 * size);
10625     jmp(L_processPartitions);
10626 
10627   bind(L_exit);
10628 }
10629 #endif //LP64
10630 
10631 #ifdef _LP64
10632 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10633 // Input: A buffer I of L bytes.
10634 // Output: the CRC32C value of the buffer.
10635 // Notations:
10636 // Write L = 24N + r, with N = floor (L/24).
10637 // r = L mod 24 (0 <= r < 24).
10638 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10639 // N quadwords, and R consists of r bytes.
10640 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10641 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10642 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10643 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10644 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10645                                           Register tmp1, Register tmp2, Register tmp3,
10646                                           Register tmp4, Register tmp5, Register tmp6,
10647                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10648                                           bool is_pclmulqdq_supported) {
10649   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10650   Label L_wordByWord;
10651   Label L_byteByByteProlog;
10652   Label L_byteByByte;
10653   Label L_exit;
10654 
10655   if (is_pclmulqdq_supported ) {
10656     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10657     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10658 
10659     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10660     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10661 
10662     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10663     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10664     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10665   } else {
10666     const_or_pre_comp_const_index[0] = 1;
10667     const_or_pre_comp_const_index[1] = 0;
10668 
10669     const_or_pre_comp_const_index[2] = 3;
10670     const_or_pre_comp_const_index[3] = 2;
10671 
10672     const_or_pre_comp_const_index[4] = 5;
10673     const_or_pre_comp_const_index[5] = 4;
10674    }
10675   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10676                     in2, in1, in_out,
10677                     tmp1, tmp2, tmp3,
10678                     w_xtmp1, w_xtmp2, w_xtmp3,
10679                     tmp4, tmp5,
10680                     tmp6);
10681   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10682                     in2, in1, in_out,
10683                     tmp1, tmp2, tmp3,
10684                     w_xtmp1, w_xtmp2, w_xtmp3,
10685                     tmp4, tmp5,
10686                     tmp6);
10687   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10688                     in2, in1, in_out,
10689                     tmp1, tmp2, tmp3,
10690                     w_xtmp1, w_xtmp2, w_xtmp3,
10691                     tmp4, tmp5,
10692                     tmp6);
10693   movl(tmp1, in2);
10694   andl(tmp1, 0x00000007);
10695   negl(tmp1);
10696   addl(tmp1, in2);
10697   addq(tmp1, in1);
10698 
10699   BIND(L_wordByWord);
10700   cmpq(in1, tmp1);
10701   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10702     crc32(in_out, Address(in1, 0), 4);
10703     addq(in1, 4);
10704     jmp(L_wordByWord);
10705 
10706   BIND(L_byteByByteProlog);
10707   andl(in2, 0x00000007);
10708   movl(tmp2, 1);
10709 
10710   BIND(L_byteByByte);
10711   cmpl(tmp2, in2);
10712   jccb(Assembler::greater, L_exit);
10713     crc32(in_out, Address(in1, 0), 1);
10714     incq(in1);
10715     incl(tmp2);
10716     jmp(L_byteByByte);
10717 
10718   BIND(L_exit);
10719 }
10720 #else
10721 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10722                                           Register tmp1, Register  tmp2, Register tmp3,
10723                                           Register tmp4, Register  tmp5, Register tmp6,
10724                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10725                                           bool is_pclmulqdq_supported) {
10726   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10727   Label L_wordByWord;
10728   Label L_byteByByteProlog;
10729   Label L_byteByByte;
10730   Label L_exit;
10731 
10732   if (is_pclmulqdq_supported) {
10733     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10734     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10735 
10736     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10737     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10738 
10739     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10740     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10741   } else {
10742     const_or_pre_comp_const_index[0] = 1;
10743     const_or_pre_comp_const_index[1] = 0;
10744 
10745     const_or_pre_comp_const_index[2] = 3;
10746     const_or_pre_comp_const_index[3] = 2;
10747 
10748     const_or_pre_comp_const_index[4] = 5;
10749     const_or_pre_comp_const_index[5] = 4;
10750   }
10751   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10752                     in2, in1, in_out,
10753                     tmp1, tmp2, tmp3,
10754                     w_xtmp1, w_xtmp2, w_xtmp3,
10755                     tmp4, tmp5,
10756                     tmp6);
10757   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10758                     in2, in1, in_out,
10759                     tmp1, tmp2, tmp3,
10760                     w_xtmp1, w_xtmp2, w_xtmp3,
10761                     tmp4, tmp5,
10762                     tmp6);
10763   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10764                     in2, in1, in_out,
10765                     tmp1, tmp2, tmp3,
10766                     w_xtmp1, w_xtmp2, w_xtmp3,
10767                     tmp4, tmp5,
10768                     tmp6);
10769   movl(tmp1, in2);
10770   andl(tmp1, 0x00000007);
10771   negl(tmp1);
10772   addl(tmp1, in2);
10773   addl(tmp1, in1);
10774 
10775   BIND(L_wordByWord);
10776   cmpl(in1, tmp1);
10777   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10778     crc32(in_out, Address(in1,0), 4);
10779     addl(in1, 4);
10780     jmp(L_wordByWord);
10781 
10782   BIND(L_byteByByteProlog);
10783   andl(in2, 0x00000007);
10784   movl(tmp2, 1);
10785 
10786   BIND(L_byteByByte);
10787   cmpl(tmp2, in2);
10788   jccb(Assembler::greater, L_exit);
10789     movb(tmp1, Address(in1, 0));
10790     crc32(in_out, tmp1, 1);
10791     incl(in1);
10792     incl(tmp2);
10793     jmp(L_byteByByte);
10794 
10795   BIND(L_exit);
10796 }
10797 #endif // LP64
10798 #undef BIND
10799 #undef BLOCK_COMMENT
10800 
10801 
10802 // Compress char[] array to byte[].
10803 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10804                                          XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10805                                          XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10806                                          Register tmp5, Register result) {
10807   Label copy_chars_loop, return_length, return_zero, done;
10808 
10809   // rsi: src
10810   // rdi: dst
10811   // rdx: len
10812   // rcx: tmp5
10813   // rax: result
10814 
10815   // rsi holds start addr of source char[] to be compressed
10816   // rdi holds start addr of destination byte[]
10817   // rdx holds length
10818 
10819   assert(len != result, "");
10820 
10821   // save length for return
10822   push(len);
10823 
10824   if (UseSSE42Intrinsics) {
10825     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10826     Label copy_32_loop, copy_16, copy_tail;
10827 
10828     movl(result, len);
10829     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10830 
10831     // vectored compression
10832     andl(len, 0xfffffff0);    // vector count (in chars)
10833     andl(result, 0x0000000f);    // tail count (in chars)
10834     testl(len, len);
10835     jccb(Assembler::zero, copy_16);
10836 
10837     // compress 16 chars per iter
10838     movdl(tmp1Reg, tmp5);
10839     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10840     pxor(tmp4Reg, tmp4Reg);
10841 
10842     lea(src, Address(src, len, Address::times_2));
10843     lea(dst, Address(dst, len, Address::times_1));
10844     negptr(len);
10845 
10846     bind(copy_32_loop);
10847     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10848     por(tmp4Reg, tmp2Reg);
10849     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10850     por(tmp4Reg, tmp3Reg);
10851     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10852     jcc(Assembler::notZero, return_zero);
10853     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10854     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10855     addptr(len, 16);
10856     jcc(Assembler::notZero, copy_32_loop);
10857 
10858     // compress next vector of 8 chars (if any)
10859     bind(copy_16);
10860     movl(len, result);
10861     andl(len, 0xfffffff8);    // vector count (in chars)
10862     andl(result, 0x00000007);    // tail count (in chars)
10863     testl(len, len);
10864     jccb(Assembler::zero, copy_tail);
10865 
10866     movdl(tmp1Reg, tmp5);
10867     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10868     pxor(tmp3Reg, tmp3Reg);
10869 
10870     movdqu(tmp2Reg, Address(src, 0));
10871     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10872     jccb(Assembler::notZero, return_zero);
10873     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10874     movq(Address(dst, 0), tmp2Reg);
10875     addptr(src, 16);
10876     addptr(dst, 8);
10877 
10878     bind(copy_tail);
10879     movl(len, result);
10880   }
10881   // compress 1 char per iter
10882   testl(len, len);
10883   jccb(Assembler::zero, return_length);
10884   lea(src, Address(src, len, Address::times_2));
10885   lea(dst, Address(dst, len, Address::times_1));
10886   negptr(len);
10887 
10888   bind(copy_chars_loop);
10889   load_unsigned_short(result, Address(src, len, Address::times_2));
10890   testl(result, 0xff00);      // check if Unicode char
10891   jccb(Assembler::notZero, return_zero);
10892   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10893   increment(len);
10894   jcc(Assembler::notZero, copy_chars_loop);
10895 
10896   // if compression succeeded, return length
10897   bind(return_length);
10898   pop(result);
10899   jmpb(done);
10900 
10901   // if compression failed, return 0
10902   bind(return_zero);
10903   xorl(result, result);
10904   addptr(rsp, wordSize);
10905 
10906   bind(done);
10907 }
10908 
10909 // Inflate byte[] array to char[].
10910 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10911                                         XMMRegister tmp1, Register tmp2) {
10912   Label copy_chars_loop, done;
10913 
10914   // rsi: src
10915   // rdi: dst
10916   // rdx: len
10917   // rcx: tmp2
10918 
10919   // rsi holds start addr of source byte[] to be inflated
10920   // rdi holds start addr of destination char[]
10921   // rdx holds length
10922   assert_different_registers(src, dst, len, tmp2);
10923 
10924   if (UseSSE42Intrinsics) {
10925     assert(UseSSE >= 4, "SSE4 must be enabled for SSE4.2 intrinsics to be available");
10926     Label copy_8_loop, copy_bytes, copy_tail;
10927 
10928     movl(tmp2, len);
10929     andl(tmp2, 0x00000007);   // tail count (in chars)
10930     andl(len, 0xfffffff8);    // vector count (in chars)
10931     jccb(Assembler::zero, copy_tail);
10932 
10933     // vectored inflation
10934     lea(src, Address(src, len, Address::times_1));
10935     lea(dst, Address(dst, len, Address::times_2));
10936     negptr(len);
10937 
10938     // inflate 8 chars per iter
10939     bind(copy_8_loop);
10940     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10941     movdqu(Address(dst, len, Address::times_2), tmp1);
10942     addptr(len, 8);
10943     jcc(Assembler::notZero, copy_8_loop);
10944 
10945     bind(copy_tail);
10946     movl(len, tmp2);
10947 
10948     cmpl(len, 4);
10949     jccb(Assembler::less, copy_bytes);
10950 
10951     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10952     pmovzxbw(tmp1, tmp1);
10953     movq(Address(dst, 0), tmp1);
10954     subptr(len, 4);
10955     addptr(src, 4);
10956     addptr(dst, 8);
10957 
10958     bind(copy_bytes);
10959   }
10960   testl(len, len);
10961   jccb(Assembler::zero, done);
10962   lea(src, Address(src, len, Address::times_1));
10963   lea(dst, Address(dst, len, Address::times_2));
10964   negptr(len);
10965 
10966   // inflate 1 char per iter
10967   bind(copy_chars_loop);
10968   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10969   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10970   increment(len);
10971   jcc(Assembler::notZero, copy_chars_loop);
10972 
10973   bind(done);
10974 }
10975 
10976 
10977 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10978   switch (cond) {
10979     // Note some conditions are synonyms for others
10980     case Assembler::zero:         return Assembler::notZero;
10981     case Assembler::notZero:      return Assembler::zero;
10982     case Assembler::less:         return Assembler::greaterEqual;
10983     case Assembler::lessEqual:    return Assembler::greater;
10984     case Assembler::greater:      return Assembler::lessEqual;
10985     case Assembler::greaterEqual: return Assembler::less;
10986     case Assembler::below:        return Assembler::aboveEqual;
10987     case Assembler::belowEqual:   return Assembler::above;
10988     case Assembler::above:        return Assembler::belowEqual;
10989     case Assembler::aboveEqual:   return Assembler::below;
10990     case Assembler::overflow:     return Assembler::noOverflow;
10991     case Assembler::noOverflow:   return Assembler::overflow;
10992     case Assembler::negative:     return Assembler::positive;
10993     case Assembler::positive:     return Assembler::negative;
10994     case Assembler::parity:       return Assembler::noParity;
10995     case Assembler::noParity:     return Assembler::parity;
10996   }
10997   ShouldNotReachHere(); return Assembler::overflow;
10998 }
10999 
11000 SkipIfEqual::SkipIfEqual(
11001     MacroAssembler* masm, const bool* flag_addr, bool value) {
11002   _masm = masm;
11003   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11004   _masm->jcc(Assembler::equal, _label);
11005 }
11006 
11007 SkipIfEqual::~SkipIfEqual() {
11008   _masm->bind(_label);
11009 }
11010 
11011 // 32-bit Windows has its own fast-path implementation
11012 // of get_thread
11013 #if !defined(WIN32) || defined(_LP64)
11014 
11015 // This is simply a call to Thread::current()
11016 void MacroAssembler::get_thread(Register thread) {
11017   if (thread != rax) {
11018     push(rax);
11019   }
11020   LP64_ONLY(push(rdi);)
11021   LP64_ONLY(push(rsi);)
11022   push(rdx);
11023   push(rcx);
11024 #ifdef _LP64
11025   push(r8);
11026   push(r9);
11027   push(r10);
11028   push(r11);
11029 #endif
11030 
11031   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11032 
11033 #ifdef _LP64
11034   pop(r11);
11035   pop(r10);
11036   pop(r9);
11037   pop(r8);
11038 #endif
11039   pop(rcx);
11040   pop(rdx);
11041   LP64_ONLY(pop(rsi);)
11042   LP64_ONLY(pop(rdi);)
11043   if (thread != rax) {
11044     mov(thread, rax);
11045     pop(rax);
11046   }
11047 }
11048 
11049 #endif