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