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