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