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_flattened_array_oop(Register oop, Register temp_reg,
3458                                               Label&is_flattened_array) {
3459   load_storage_props(temp_reg, oop);
3460   testb(temp_reg, ArrayStorageProperties::flattened_value);
3461   jcc(Assembler::notZero, is_flattened_array);
3462 }
3463 
3464 void MacroAssembler::test_null_free_array_oop(Register oop, Register temp_reg, Label&is_null_free_array) {
3465   load_storage_props(temp_reg, oop);
3466   testb(temp_reg, ArrayStorageProperties::null_free_value);
3467   jcc(Assembler::notZero, is_null_free_array);
3468 }
3469 
3470 void MacroAssembler::os_breakpoint() {
3471   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3472   // (e.g., MSVC can't call ps() otherwise)
3473   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3474 }
3475 
3476 void MacroAssembler::unimplemented(const char* what) {
3477   const char* buf = NULL;
3478   {
3479     ResourceMark rm;
3480     stringStream ss;
3481     ss.print("unimplemented: %s", what);
3482     buf = code_string(ss.as_string());
3483   }
3484   stop(buf);
3485 }
3486 
3487 #ifdef _LP64
3488 #define XSTATE_BV 0x200
3489 #endif
3490 
3491 void MacroAssembler::pop_CPU_state() {
3492   pop_FPU_state();
3493   pop_IU_state();
3494 }
3495 
3496 void MacroAssembler::pop_FPU_state() {
3497 #ifndef _LP64
3498   frstor(Address(rsp, 0));
3499 #else
3500   fxrstor(Address(rsp, 0));
3501 #endif
3502   addptr(rsp, FPUStateSizeInWords * wordSize);
3503 }
3504 
3505 void MacroAssembler::pop_IU_state() {
3506   popa();
3507   LP64_ONLY(addq(rsp, 8));
3508   popf();
3509 }
3510 
3511 // Save Integer and Float state
3512 // Warning: Stack must be 16 byte aligned (64bit)
3513 void MacroAssembler::push_CPU_state() {
3514   push_IU_state();
3515   push_FPU_state();
3516 }
3517 
3518 void MacroAssembler::push_FPU_state() {
3519   subptr(rsp, FPUStateSizeInWords * wordSize);
3520 #ifndef _LP64
3521   fnsave(Address(rsp, 0));
3522   fwait();
3523 #else
3524   fxsave(Address(rsp, 0));
3525 #endif // LP64
3526 }
3527 
3528 void MacroAssembler::push_IU_state() {
3529   // Push flags first because pusha kills them
3530   pushf();
3531   // Make sure rsp stays 16-byte aligned
3532   LP64_ONLY(subq(rsp, 8));
3533   pusha();
3534 }
3535 
3536 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3537   if (!java_thread->is_valid()) {
3538     java_thread = rdi;
3539     get_thread(java_thread);
3540   }
3541   // we must set sp to zero to clear frame
3542   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3543   if (clear_fp) {
3544     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3545   }
3546 
3547   // Always clear the pc because it could have been set by make_walkable()
3548   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3549 
3550   vzeroupper();
3551 }
3552 
3553 void MacroAssembler::restore_rax(Register tmp) {
3554   if (tmp == noreg) pop(rax);
3555   else if (tmp != rax) mov(rax, tmp);
3556 }
3557 
3558 void MacroAssembler::round_to(Register reg, int modulus) {
3559   addptr(reg, modulus - 1);
3560   andptr(reg, -modulus);
3561 }
3562 
3563 void MacroAssembler::save_rax(Register tmp) {
3564   if (tmp == noreg) push(rax);
3565   else if (tmp != rax) mov(tmp, rax);
3566 }
3567 
3568 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3569   if (SafepointMechanism::uses_thread_local_poll()) {
3570 #ifdef _LP64
3571     assert(thread_reg == r15_thread, "should be");
3572 #else
3573     if (thread_reg == noreg) {
3574       thread_reg = temp_reg;
3575       get_thread(thread_reg);
3576     }
3577 #endif
3578     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3579     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3580   } else {
3581     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3582         SafepointSynchronize::_not_synchronized);
3583     jcc(Assembler::notEqual, slow_path);
3584   }
3585 }
3586 
3587 // Calls to C land
3588 //
3589 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3590 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3591 // has to be reset to 0. This is required to allow proper stack traversal.
3592 void MacroAssembler::set_last_Java_frame(Register java_thread,
3593                                          Register last_java_sp,
3594                                          Register last_java_fp,
3595                                          address  last_java_pc) {
3596   vzeroupper();
3597   // determine java_thread register
3598   if (!java_thread->is_valid()) {
3599     java_thread = rdi;
3600     get_thread(java_thread);
3601   }
3602   // determine last_java_sp register
3603   if (!last_java_sp->is_valid()) {
3604     last_java_sp = rsp;
3605   }
3606 
3607   // last_java_fp is optional
3608 
3609   if (last_java_fp->is_valid()) {
3610     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3611   }
3612 
3613   // last_java_pc is optional
3614 
3615   if (last_java_pc != NULL) {
3616     lea(Address(java_thread,
3617                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3618         InternalAddress(last_java_pc));
3619 
3620   }
3621   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3622 }
3623 
3624 void MacroAssembler::shlptr(Register dst, int imm8) {
3625   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3626 }
3627 
3628 void MacroAssembler::shrptr(Register dst, int imm8) {
3629   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3630 }
3631 
3632 void MacroAssembler::sign_extend_byte(Register reg) {
3633   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3634     movsbl(reg, reg); // movsxb
3635   } else {
3636     shll(reg, 24);
3637     sarl(reg, 24);
3638   }
3639 }
3640 
3641 void MacroAssembler::sign_extend_short(Register reg) {
3642   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3643     movswl(reg, reg); // movsxw
3644   } else {
3645     shll(reg, 16);
3646     sarl(reg, 16);
3647   }
3648 }
3649 
3650 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3651   assert(reachable(src), "Address should be reachable");
3652   testl(dst, as_Address(src));
3653 }
3654 
3655 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3656   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3657   Assembler::pcmpeqb(dst, src);
3658 }
3659 
3660 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3661   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3662   Assembler::pcmpeqw(dst, src);
3663 }
3664 
3665 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3666   assert((dst->encoding() < 16),"XMM register should be 0-15");
3667   Assembler::pcmpestri(dst, src, imm8);
3668 }
3669 
3670 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3671   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3672   Assembler::pcmpestri(dst, src, imm8);
3673 }
3674 
3675 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3676   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3677   Assembler::pmovzxbw(dst, src);
3678 }
3679 
3680 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3681   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3682   Assembler::pmovzxbw(dst, src);
3683 }
3684 
3685 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3686   assert((src->encoding() < 16),"XMM register should be 0-15");
3687   Assembler::pmovmskb(dst, src);
3688 }
3689 
3690 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3691   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3692   Assembler::ptest(dst, src);
3693 }
3694 
3695 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3696   if (reachable(src)) {
3697     Assembler::sqrtsd(dst, as_Address(src));
3698   } else {
3699     lea(rscratch1, src);
3700     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3701   }
3702 }
3703 
3704 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3705   if (reachable(src)) {
3706     Assembler::sqrtss(dst, as_Address(src));
3707   } else {
3708     lea(rscratch1, src);
3709     Assembler::sqrtss(dst, Address(rscratch1, 0));
3710   }
3711 }
3712 
3713 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3714   if (reachable(src)) {
3715     Assembler::subsd(dst, as_Address(src));
3716   } else {
3717     lea(rscratch1, src);
3718     Assembler::subsd(dst, Address(rscratch1, 0));
3719   }
3720 }
3721 
3722 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3723   if (reachable(src)) {
3724     Assembler::subss(dst, as_Address(src));
3725   } else {
3726     lea(rscratch1, src);
3727     Assembler::subss(dst, Address(rscratch1, 0));
3728   }
3729 }
3730 
3731 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
3732   if (reachable(src)) {
3733     Assembler::ucomisd(dst, as_Address(src));
3734   } else {
3735     lea(rscratch1, src);
3736     Assembler::ucomisd(dst, Address(rscratch1, 0));
3737   }
3738 }
3739 
3740 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
3741   if (reachable(src)) {
3742     Assembler::ucomiss(dst, as_Address(src));
3743   } else {
3744     lea(rscratch1, src);
3745     Assembler::ucomiss(dst, Address(rscratch1, 0));
3746   }
3747 }
3748 
3749 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
3750   // Used in sign-bit flipping with aligned address.
3751   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3752   if (reachable(src)) {
3753     Assembler::xorpd(dst, as_Address(src));
3754   } else {
3755     lea(rscratch1, src);
3756     Assembler::xorpd(dst, Address(rscratch1, 0));
3757   }
3758 }
3759 
3760 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
3761   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3762     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3763   }
3764   else {
3765     Assembler::xorpd(dst, src);
3766   }
3767 }
3768 
3769 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
3770   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
3771     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
3772   } else {
3773     Assembler::xorps(dst, src);
3774   }
3775 }
3776 
3777 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
3778   // Used in sign-bit flipping with aligned address.
3779   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
3780   if (reachable(src)) {
3781     Assembler::xorps(dst, as_Address(src));
3782   } else {
3783     lea(rscratch1, src);
3784     Assembler::xorps(dst, Address(rscratch1, 0));
3785   }
3786 }
3787 
3788 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
3789   // Used in sign-bit flipping with aligned address.
3790   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
3791   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
3792   if (reachable(src)) {
3793     Assembler::pshufb(dst, as_Address(src));
3794   } else {
3795     lea(rscratch1, src);
3796     Assembler::pshufb(dst, Address(rscratch1, 0));
3797   }
3798 }
3799 
3800 // AVX 3-operands instructions
3801 
3802 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3803   if (reachable(src)) {
3804     vaddsd(dst, nds, as_Address(src));
3805   } else {
3806     lea(rscratch1, src);
3807     vaddsd(dst, nds, Address(rscratch1, 0));
3808   }
3809 }
3810 
3811 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3812   if (reachable(src)) {
3813     vaddss(dst, nds, as_Address(src));
3814   } else {
3815     lea(rscratch1, src);
3816     vaddss(dst, nds, Address(rscratch1, 0));
3817   }
3818 }
3819 
3820 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3821   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3822   vandps(dst, nds, negate_field, vector_len);
3823 }
3824 
3825 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
3826   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
3827   vandpd(dst, nds, negate_field, vector_len);
3828 }
3829 
3830 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3831   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3832   Assembler::vpaddb(dst, nds, src, vector_len);
3833 }
3834 
3835 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3836   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3837   Assembler::vpaddb(dst, nds, src, vector_len);
3838 }
3839 
3840 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3841   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3842   Assembler::vpaddw(dst, nds, src, vector_len);
3843 }
3844 
3845 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3846   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3847   Assembler::vpaddw(dst, nds, src, vector_len);
3848 }
3849 
3850 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3851   if (reachable(src)) {
3852     Assembler::vpand(dst, nds, as_Address(src), vector_len);
3853   } else {
3854     lea(rscratch1, src);
3855     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
3856   }
3857 }
3858 
3859 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src, int vector_len) {
3860   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3861   Assembler::vpbroadcastw(dst, src, vector_len);
3862 }
3863 
3864 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3865   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3866   Assembler::vpcmpeqb(dst, nds, src, vector_len);
3867 }
3868 
3869 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3870   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3871   Assembler::vpcmpeqw(dst, nds, src, vector_len);
3872 }
3873 
3874 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
3875   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3876   Assembler::vpmovzxbw(dst, src, vector_len);
3877 }
3878 
3879 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
3880   assert((src->encoding() < 16),"XMM register should be 0-15");
3881   Assembler::vpmovmskb(dst, src);
3882 }
3883 
3884 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3885   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3886   Assembler::vpmullw(dst, nds, src, vector_len);
3887 }
3888 
3889 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3890   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3891   Assembler::vpmullw(dst, nds, src, vector_len);
3892 }
3893 
3894 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3895   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3896   Assembler::vpsubb(dst, nds, src, vector_len);
3897 }
3898 
3899 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3900   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3901   Assembler::vpsubb(dst, nds, src, vector_len);
3902 }
3903 
3904 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
3905   assert(((dst->encoding() < 16 && src->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3906   Assembler::vpsubw(dst, nds, src, vector_len);
3907 }
3908 
3909 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
3910   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3911   Assembler::vpsubw(dst, nds, src, vector_len);
3912 }
3913 
3914 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3915   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3916   Assembler::vpsraw(dst, nds, shift, vector_len);
3917 }
3918 
3919 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3920   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3921   Assembler::vpsraw(dst, nds, shift, vector_len);
3922 }
3923 
3924 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3925   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3926   Assembler::vpsrlw(dst, nds, shift, vector_len);
3927 }
3928 
3929 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3930   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3931   Assembler::vpsrlw(dst, nds, shift, vector_len);
3932 }
3933 
3934 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
3935   assert(((dst->encoding() < 16 && shift->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3936   Assembler::vpsllw(dst, nds, shift, vector_len);
3937 }
3938 
3939 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
3940   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3941   Assembler::vpsllw(dst, nds, shift, vector_len);
3942 }
3943 
3944 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
3945   assert((dst->encoding() < 16 && src->encoding() < 16),"XMM register should be 0-15");
3946   Assembler::vptest(dst, src);
3947 }
3948 
3949 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
3950   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3951   Assembler::punpcklbw(dst, src);
3952 }
3953 
3954 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
3955   assert(((dst->encoding() < 16) || VM_Version::supports_avx512vl()),"XMM register should be 0-15");
3956   Assembler::pshufd(dst, src, mode);
3957 }
3958 
3959 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
3960   assert(((dst->encoding() < 16 && src->encoding() < 16) || VM_Version::supports_avx512vlbw()),"XMM register should be 0-15");
3961   Assembler::pshuflw(dst, src, mode);
3962 }
3963 
3964 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3965   if (reachable(src)) {
3966     vandpd(dst, nds, as_Address(src), vector_len);
3967   } else {
3968     lea(rscratch1, src);
3969     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
3970   }
3971 }
3972 
3973 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
3974   if (reachable(src)) {
3975     vandps(dst, nds, as_Address(src), vector_len);
3976   } else {
3977     lea(rscratch1, src);
3978     vandps(dst, nds, Address(rscratch1, 0), vector_len);
3979   }
3980 }
3981 
3982 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3983   if (reachable(src)) {
3984     vdivsd(dst, nds, as_Address(src));
3985   } else {
3986     lea(rscratch1, src);
3987     vdivsd(dst, nds, Address(rscratch1, 0));
3988   }
3989 }
3990 
3991 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
3992   if (reachable(src)) {
3993     vdivss(dst, nds, as_Address(src));
3994   } else {
3995     lea(rscratch1, src);
3996     vdivss(dst, nds, Address(rscratch1, 0));
3997   }
3998 }
3999 
4000 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4001   if (reachable(src)) {
4002     vmulsd(dst, nds, as_Address(src));
4003   } else {
4004     lea(rscratch1, src);
4005     vmulsd(dst, nds, Address(rscratch1, 0));
4006   }
4007 }
4008 
4009 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4010   if (reachable(src)) {
4011     vmulss(dst, nds, as_Address(src));
4012   } else {
4013     lea(rscratch1, src);
4014     vmulss(dst, nds, Address(rscratch1, 0));
4015   }
4016 }
4017 
4018 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4019   if (reachable(src)) {
4020     vsubsd(dst, nds, as_Address(src));
4021   } else {
4022     lea(rscratch1, src);
4023     vsubsd(dst, nds, Address(rscratch1, 0));
4024   }
4025 }
4026 
4027 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4028   if (reachable(src)) {
4029     vsubss(dst, nds, as_Address(src));
4030   } else {
4031     lea(rscratch1, src);
4032     vsubss(dst, nds, Address(rscratch1, 0));
4033   }
4034 }
4035 
4036 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4037   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
4038   vxorps(dst, nds, src, Assembler::AVX_128bit);
4039 }
4040 
4041 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4042   assert(((dst->encoding() < 16 && nds->encoding() < 16) || VM_Version::supports_avx512vldq()),"XMM register should be 0-15");
4043   vxorpd(dst, nds, src, Assembler::AVX_128bit);
4044 }
4045 
4046 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4047   if (reachable(src)) {
4048     vxorpd(dst, nds, as_Address(src), vector_len);
4049   } else {
4050     lea(rscratch1, src);
4051     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
4052   }
4053 }
4054 
4055 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4056   if (reachable(src)) {
4057     vxorps(dst, nds, as_Address(src), vector_len);
4058   } else {
4059     lea(rscratch1, src);
4060     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
4061   }
4062 }
4063 
4064 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
4065   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
4066   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
4067   // The inverted mask is sign-extended
4068   andptr(possibly_jweak, inverted_jweak_mask);
4069 }
4070 
4071 void MacroAssembler::resolve_jobject(Register value,
4072                                      Register thread,
4073                                      Register tmp) {
4074   assert_different_registers(value, thread, tmp);
4075   Label done, not_weak;
4076   testptr(value, value);
4077   jcc(Assembler::zero, done);                // Use NULL as-is.
4078   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
4079   jcc(Assembler::zero, not_weak);
4080   // Resolve jweak.
4081   access_load_at(T_OBJECT, IN_NATIVE | ON_PHANTOM_OOP_REF,
4082                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
4083   verify_oop(value);
4084   jmp(done);
4085   bind(not_weak);
4086   // Resolve (untagged) jobject.
4087   access_load_at(T_OBJECT, IN_NATIVE, value, Address(value, 0), tmp, thread);
4088   verify_oop(value);
4089   bind(done);
4090 }
4091 
4092 void MacroAssembler::subptr(Register dst, int32_t imm32) {
4093   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
4094 }
4095 
4096 // Force generation of a 4 byte immediate value even if it fits into 8bit
4097 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
4098   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
4099 }
4100 
4101 void MacroAssembler::subptr(Register dst, Register src) {
4102   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
4103 }
4104 
4105 // C++ bool manipulation
4106 void MacroAssembler::testbool(Register dst) {
4107   if(sizeof(bool) == 1)
4108     testb(dst, 0xff);
4109   else if(sizeof(bool) == 2) {
4110     // testw implementation needed for two byte bools
4111     ShouldNotReachHere();
4112   } else if(sizeof(bool) == 4)
4113     testl(dst, dst);
4114   else
4115     // unsupported
4116     ShouldNotReachHere();
4117 }
4118 
4119 void MacroAssembler::testptr(Register dst, Register src) {
4120   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
4121 }
4122 
4123 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
4124 void MacroAssembler::tlab_allocate(Register thread, Register obj,
4125                                    Register var_size_in_bytes,
4126                                    int con_size_in_bytes,
4127                                    Register t1,
4128                                    Register t2,
4129                                    Label& slow_case) {
4130   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4131   bs->tlab_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, t2, slow_case);
4132 }
4133 
4134 // Defines obj, preserves var_size_in_bytes
4135 void MacroAssembler::eden_allocate(Register thread, Register obj,
4136                                    Register var_size_in_bytes,
4137                                    int con_size_in_bytes,
4138                                    Register t1,
4139                                    Label& slow_case) {
4140   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
4141   bs->eden_allocate(this, thread, obj, var_size_in_bytes, con_size_in_bytes, t1, slow_case);
4142 }
4143 
4144 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
4145 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
4146   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
4147   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
4148   Label done;
4149 
4150   testptr(length_in_bytes, length_in_bytes);
4151   jcc(Assembler::zero, done);
4152 
4153   // initialize topmost word, divide index by 2, check if odd and test if zero
4154   // note: for the remaining code to work, index must be a multiple of BytesPerWord
4155 #ifdef ASSERT
4156   {
4157     Label L;
4158     testptr(length_in_bytes, BytesPerWord - 1);
4159     jcc(Assembler::zero, L);
4160     stop("length must be a multiple of BytesPerWord");
4161     bind(L);
4162   }
4163 #endif
4164   Register index = length_in_bytes;
4165   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
4166   if (UseIncDec) {
4167     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
4168   } else {
4169     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
4170     shrptr(index, 1);
4171   }
4172 #ifndef _LP64
4173   // index could have not been a multiple of 8 (i.e., bit 2 was set)
4174   {
4175     Label even;
4176     // note: if index was a multiple of 8, then it cannot
4177     //       be 0 now otherwise it must have been 0 before
4178     //       => if it is even, we don't need to check for 0 again
4179     jcc(Assembler::carryClear, even);
4180     // clear topmost word (no jump would be needed if conditional assignment worked here)
4181     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
4182     // index could be 0 now, must check again
4183     jcc(Assembler::zero, done);
4184     bind(even);
4185   }
4186 #endif // !_LP64
4187   // initialize remaining object fields: index is a multiple of 2 now
4188   {
4189     Label loop;
4190     bind(loop);
4191     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
4192     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
4193     decrement(index);
4194     jcc(Assembler::notZero, loop);
4195   }
4196 
4197   bind(done);
4198 }
4199 
4200 // Look up the method for a megamorphic invokeinterface call.
4201 // The target method is determined by <intf_klass, itable_index>.
4202 // The receiver klass is in recv_klass.
4203 // On success, the result will be in method_result, and execution falls through.
4204 // On failure, execution transfers to the given label.
4205 void MacroAssembler::lookup_interface_method(Register recv_klass,
4206                                              Register intf_klass,
4207                                              RegisterOrConstant itable_index,
4208                                              Register method_result,
4209                                              Register scan_temp,
4210                                              Label& L_no_such_interface,
4211                                              bool return_method) {
4212   assert_different_registers(recv_klass, intf_klass, scan_temp);
4213   assert_different_registers(method_result, intf_klass, scan_temp);
4214   assert(recv_klass != method_result || !return_method,
4215          "recv_klass can be destroyed when method isn't needed");
4216 
4217   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
4218          "caller must use same register for non-constant itable index as for method");
4219 
4220   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
4221   int vtable_base = in_bytes(Klass::vtable_start_offset());
4222   int itentry_off = itableMethodEntry::method_offset_in_bytes();
4223   int scan_step   = itableOffsetEntry::size() * wordSize;
4224   int vte_size    = vtableEntry::size_in_bytes();
4225   Address::ScaleFactor times_vte_scale = Address::times_ptr;
4226   assert(vte_size == wordSize, "else adjust times_vte_scale");
4227 
4228   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
4229 
4230   // %%% Could store the aligned, prescaled offset in the klassoop.
4231   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
4232 
4233   if (return_method) {
4234     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
4235     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
4236     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
4237   }
4238 
4239   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
4240   //   if (scan->interface() == intf) {
4241   //     result = (klass + scan->offset() + itable_index);
4242   //   }
4243   // }
4244   Label search, found_method;
4245 
4246   for (int peel = 1; peel >= 0; peel--) {
4247     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
4248     cmpptr(intf_klass, method_result);
4249 
4250     if (peel) {
4251       jccb(Assembler::equal, found_method);
4252     } else {
4253       jccb(Assembler::notEqual, search);
4254       // (invert the test to fall through to found_method...)
4255     }
4256 
4257     if (!peel)  break;
4258 
4259     bind(search);
4260 
4261     // Check that the previous entry is non-null.  A null entry means that
4262     // the receiver class doesn't implement the interface, and wasn't the
4263     // same as when the caller was compiled.
4264     testptr(method_result, method_result);
4265     jcc(Assembler::zero, L_no_such_interface);
4266     addptr(scan_temp, scan_step);
4267   }
4268 
4269   bind(found_method);
4270 
4271   if (return_method) {
4272     // Got a hit.
4273     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
4274     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
4275   }
4276 }
4277 
4278 
4279 // virtual method calling
4280 void MacroAssembler::lookup_virtual_method(Register recv_klass,
4281                                            RegisterOrConstant vtable_index,
4282                                            Register method_result) {
4283   const int base = in_bytes(Klass::vtable_start_offset());
4284   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
4285   Address vtable_entry_addr(recv_klass,
4286                             vtable_index, Address::times_ptr,
4287                             base + vtableEntry::method_offset_in_bytes());
4288   movptr(method_result, vtable_entry_addr);
4289 }
4290 
4291 
4292 void MacroAssembler::check_klass_subtype(Register sub_klass,
4293                            Register super_klass,
4294                            Register temp_reg,
4295                            Label& L_success) {
4296   Label L_failure;
4297   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
4298   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
4299   bind(L_failure);
4300 }
4301 
4302 
4303 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
4304                                                    Register super_klass,
4305                                                    Register temp_reg,
4306                                                    Label* L_success,
4307                                                    Label* L_failure,
4308                                                    Label* L_slow_path,
4309                                         RegisterOrConstant super_check_offset) {
4310   assert_different_registers(sub_klass, super_klass, temp_reg);
4311   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
4312   if (super_check_offset.is_register()) {
4313     assert_different_registers(sub_klass, super_klass,
4314                                super_check_offset.as_register());
4315   } else if (must_load_sco) {
4316     assert(temp_reg != noreg, "supply either a temp or a register offset");
4317   }
4318 
4319   Label L_fallthrough;
4320   int label_nulls = 0;
4321   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4322   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4323   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
4324   assert(label_nulls <= 1, "at most one NULL in the batch");
4325 
4326   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4327   int sco_offset = in_bytes(Klass::super_check_offset_offset());
4328   Address super_check_offset_addr(super_klass, sco_offset);
4329 
4330   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
4331   // range of a jccb.  If this routine grows larger, reconsider at
4332   // least some of these.
4333 #define local_jcc(assembler_cond, label)                                \
4334   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
4335   else                             jcc( assembler_cond, label) /*omit semi*/
4336 
4337   // Hacked jmp, which may only be used just before L_fallthrough.
4338 #define final_jmp(label)                                                \
4339   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
4340   else                            jmp(label)                /*omit semi*/
4341 
4342   // If the pointers are equal, we are done (e.g., String[] elements).
4343   // This self-check enables sharing of secondary supertype arrays among
4344   // non-primary types such as array-of-interface.  Otherwise, each such
4345   // type would need its own customized SSA.
4346   // We move this check to the front of the fast path because many
4347   // type checks are in fact trivially successful in this manner,
4348   // so we get a nicely predicted branch right at the start of the check.
4349   cmpptr(sub_klass, super_klass);
4350   local_jcc(Assembler::equal, *L_success);
4351 
4352   // Check the supertype display:
4353   if (must_load_sco) {
4354     // Positive movl does right thing on LP64.
4355     movl(temp_reg, super_check_offset_addr);
4356     super_check_offset = RegisterOrConstant(temp_reg);
4357   }
4358   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
4359   cmpptr(super_klass, super_check_addr); // load displayed supertype
4360 
4361   // This check has worked decisively for primary supers.
4362   // Secondary supers are sought in the super_cache ('super_cache_addr').
4363   // (Secondary supers are interfaces and very deeply nested subtypes.)
4364   // This works in the same check above because of a tricky aliasing
4365   // between the super_cache and the primary super display elements.
4366   // (The 'super_check_addr' can address either, as the case requires.)
4367   // Note that the cache is updated below if it does not help us find
4368   // what we need immediately.
4369   // So if it was a primary super, we can just fail immediately.
4370   // Otherwise, it's the slow path for us (no success at this point).
4371 
4372   if (super_check_offset.is_register()) {
4373     local_jcc(Assembler::equal, *L_success);
4374     cmpl(super_check_offset.as_register(), sc_offset);
4375     if (L_failure == &L_fallthrough) {
4376       local_jcc(Assembler::equal, *L_slow_path);
4377     } else {
4378       local_jcc(Assembler::notEqual, *L_failure);
4379       final_jmp(*L_slow_path);
4380     }
4381   } else if (super_check_offset.as_constant() == sc_offset) {
4382     // Need a slow path; fast failure is impossible.
4383     if (L_slow_path == &L_fallthrough) {
4384       local_jcc(Assembler::equal, *L_success);
4385     } else {
4386       local_jcc(Assembler::notEqual, *L_slow_path);
4387       final_jmp(*L_success);
4388     }
4389   } else {
4390     // No slow path; it's a fast decision.
4391     if (L_failure == &L_fallthrough) {
4392       local_jcc(Assembler::equal, *L_success);
4393     } else {
4394       local_jcc(Assembler::notEqual, *L_failure);
4395       final_jmp(*L_success);
4396     }
4397   }
4398 
4399   bind(L_fallthrough);
4400 
4401 #undef local_jcc
4402 #undef final_jmp
4403 }
4404 
4405 
4406 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
4407                                                    Register super_klass,
4408                                                    Register temp_reg,
4409                                                    Register temp2_reg,
4410                                                    Label* L_success,
4411                                                    Label* L_failure,
4412                                                    bool set_cond_codes) {
4413   assert_different_registers(sub_klass, super_klass, temp_reg);
4414   if (temp2_reg != noreg)
4415     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
4416 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
4417 
4418   Label L_fallthrough;
4419   int label_nulls = 0;
4420   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
4421   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
4422   assert(label_nulls <= 1, "at most one NULL in the batch");
4423 
4424   // a couple of useful fields in sub_klass:
4425   int ss_offset = in_bytes(Klass::secondary_supers_offset());
4426   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
4427   Address secondary_supers_addr(sub_klass, ss_offset);
4428   Address super_cache_addr(     sub_klass, sc_offset);
4429 
4430   // Do a linear scan of the secondary super-klass chain.
4431   // This code is rarely used, so simplicity is a virtue here.
4432   // The repne_scan instruction uses fixed registers, which we must spill.
4433   // Don't worry too much about pre-existing connections with the input regs.
4434 
4435   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
4436   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
4437 
4438   // Get super_klass value into rax (even if it was in rdi or rcx).
4439   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
4440   if (super_klass != rax || UseCompressedOops) {
4441     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
4442     mov(rax, super_klass);
4443   }
4444   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
4445   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
4446 
4447 #ifndef PRODUCT
4448   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
4449   ExternalAddress pst_counter_addr((address) pst_counter);
4450   NOT_LP64(  incrementl(pst_counter_addr) );
4451   LP64_ONLY( lea(rcx, pst_counter_addr) );
4452   LP64_ONLY( incrementl(Address(rcx, 0)) );
4453 #endif //PRODUCT
4454 
4455   // We will consult the secondary-super array.
4456   movptr(rdi, secondary_supers_addr);
4457   // Load the array length.  (Positive movl does right thing on LP64.)
4458   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
4459   // Skip to start of data.
4460   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
4461 
4462   // Scan RCX words at [RDI] for an occurrence of RAX.
4463   // Set NZ/Z based on last compare.
4464   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
4465   // not change flags (only scas instruction which is repeated sets flags).
4466   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
4467 
4468     testptr(rax,rax); // Set Z = 0
4469     repne_scan();
4470 
4471   // Unspill the temp. registers:
4472   if (pushed_rdi)  pop(rdi);
4473   if (pushed_rcx)  pop(rcx);
4474   if (pushed_rax)  pop(rax);
4475 
4476   if (set_cond_codes) {
4477     // Special hack for the AD files:  rdi is guaranteed non-zero.
4478     assert(!pushed_rdi, "rdi must be left non-NULL");
4479     // Also, the condition codes are properly set Z/NZ on succeed/failure.
4480   }
4481 
4482   if (L_failure == &L_fallthrough)
4483         jccb(Assembler::notEqual, *L_failure);
4484   else  jcc(Assembler::notEqual, *L_failure);
4485 
4486   // Success.  Cache the super we found and proceed in triumph.
4487   movptr(super_cache_addr, super_klass);
4488 
4489   if (L_success != &L_fallthrough) {
4490     jmp(*L_success);
4491   }
4492 
4493 #undef IS_A_TEMP
4494 
4495   bind(L_fallthrough);
4496 }
4497 
4498 
4499 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
4500   if (VM_Version::supports_cmov()) {
4501     cmovl(cc, dst, src);
4502   } else {
4503     Label L;
4504     jccb(negate_condition(cc), L);
4505     movl(dst, src);
4506     bind(L);
4507   }
4508 }
4509 
4510 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
4511   if (VM_Version::supports_cmov()) {
4512     cmovl(cc, dst, src);
4513   } else {
4514     Label L;
4515     jccb(negate_condition(cc), L);
4516     movl(dst, src);
4517     bind(L);
4518   }
4519 }
4520 
4521 void MacroAssembler::verify_oop(Register reg, const char* s) {
4522   if (!VerifyOops || VerifyAdapterSharing) {
4523     // Below address of the code string confuses VerifyAdapterSharing
4524     // because it may differ between otherwise equivalent adapters.
4525     return;
4526   }
4527 
4528   // Pass register number to verify_oop_subroutine
4529   const char* b = NULL;
4530   {
4531     ResourceMark rm;
4532     stringStream ss;
4533     ss.print("verify_oop: %s: %s", reg->name(), s);
4534     b = code_string(ss.as_string());
4535   }
4536   BLOCK_COMMENT("verify_oop {");
4537 #ifdef _LP64
4538   push(rscratch1);                    // save r10, trashed by movptr()
4539 #endif
4540   push(rax);                          // save rax,
4541   push(reg);                          // pass register argument
4542   ExternalAddress buffer((address) b);
4543   // avoid using pushptr, as it modifies scratch registers
4544   // and our contract is not to modify anything
4545   movptr(rax, buffer.addr());
4546   push(rax);
4547   // call indirectly to solve generation ordering problem
4548   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4549   call(rax);
4550   // Caller pops the arguments (oop, message) and restores rax, r10
4551   BLOCK_COMMENT("} verify_oop");
4552 }
4553 
4554 
4555 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
4556                                                       Register tmp,
4557                                                       int offset) {
4558   intptr_t value = *delayed_value_addr;
4559   if (value != 0)
4560     return RegisterOrConstant(value + offset);
4561 
4562   // load indirectly to solve generation ordering problem
4563   movptr(tmp, ExternalAddress((address) delayed_value_addr));
4564 
4565 #ifdef ASSERT
4566   { Label L;
4567     testptr(tmp, tmp);
4568     if (WizardMode) {
4569       const char* buf = NULL;
4570       {
4571         ResourceMark rm;
4572         stringStream ss;
4573         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
4574         buf = code_string(ss.as_string());
4575       }
4576       jcc(Assembler::notZero, L);
4577       STOP(buf);
4578     } else {
4579       jccb(Assembler::notZero, L);
4580       hlt();
4581     }
4582     bind(L);
4583   }
4584 #endif
4585 
4586   if (offset != 0)
4587     addptr(tmp, offset);
4588 
4589   return RegisterOrConstant(tmp);
4590 }
4591 
4592 
4593 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
4594                                          int extra_slot_offset) {
4595   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
4596   int stackElementSize = Interpreter::stackElementSize;
4597   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
4598 #ifdef ASSERT
4599   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
4600   assert(offset1 - offset == stackElementSize, "correct arithmetic");
4601 #endif
4602   Register             scale_reg    = noreg;
4603   Address::ScaleFactor scale_factor = Address::no_scale;
4604   if (arg_slot.is_constant()) {
4605     offset += arg_slot.as_constant() * stackElementSize;
4606   } else {
4607     scale_reg    = arg_slot.as_register();
4608     scale_factor = Address::times(stackElementSize);
4609   }
4610   offset += wordSize;           // return PC is on stack
4611   return Address(rsp, scale_reg, scale_factor, offset);
4612 }
4613 
4614 
4615 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
4616   if (!VerifyOops || VerifyAdapterSharing) {
4617     // Below address of the code string confuses VerifyAdapterSharing
4618     // because it may differ between otherwise equivalent adapters.
4619     return;
4620   }
4621 
4622   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
4623   // Pass register number to verify_oop_subroutine
4624   const char* b = NULL;
4625   {
4626     ResourceMark rm;
4627     stringStream ss;
4628     ss.print("verify_oop_addr: %s", s);
4629     b = code_string(ss.as_string());
4630   }
4631 #ifdef _LP64
4632   push(rscratch1);                    // save r10, trashed by movptr()
4633 #endif
4634   push(rax);                          // save rax,
4635   // addr may contain rsp so we will have to adjust it based on the push
4636   // we just did (and on 64 bit we do two pushes)
4637   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
4638   // stores rax into addr which is backwards of what was intended.
4639   if (addr.uses(rsp)) {
4640     lea(rax, addr);
4641     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
4642   } else {
4643     pushptr(addr);
4644   }
4645 
4646   ExternalAddress buffer((address) b);
4647   // pass msg argument
4648   // avoid using pushptr, as it modifies scratch registers
4649   // and our contract is not to modify anything
4650   movptr(rax, buffer.addr());
4651   push(rax);
4652 
4653   // call indirectly to solve generation ordering problem
4654   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
4655   call(rax);
4656   // Caller pops the arguments (addr, message) and restores rax, r10.
4657 }
4658 
4659 void MacroAssembler::verify_tlab() {
4660 #ifdef ASSERT
4661   if (UseTLAB && VerifyOops) {
4662     Label next, ok;
4663     Register t1 = rsi;
4664     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
4665 
4666     push(t1);
4667     NOT_LP64(push(thread_reg));
4668     NOT_LP64(get_thread(thread_reg));
4669 
4670     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4671     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
4672     jcc(Assembler::aboveEqual, next);
4673     STOP("assert(top >= start)");
4674     should_not_reach_here();
4675 
4676     bind(next);
4677     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
4678     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
4679     jcc(Assembler::aboveEqual, ok);
4680     STOP("assert(top <= end)");
4681     should_not_reach_here();
4682 
4683     bind(ok);
4684     NOT_LP64(pop(thread_reg));
4685     pop(t1);
4686   }
4687 #endif
4688 }
4689 
4690 class ControlWord {
4691  public:
4692   int32_t _value;
4693 
4694   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
4695   int  precision_control() const       { return  (_value >>  8) & 3      ; }
4696   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4697   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4698   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4699   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4700   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4701   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4702 
4703   void print() const {
4704     // rounding control
4705     const char* rc;
4706     switch (rounding_control()) {
4707       case 0: rc = "round near"; break;
4708       case 1: rc = "round down"; break;
4709       case 2: rc = "round up  "; break;
4710       case 3: rc = "chop      "; break;
4711     };
4712     // precision control
4713     const char* pc;
4714     switch (precision_control()) {
4715       case 0: pc = "24 bits "; break;
4716       case 1: pc = "reserved"; break;
4717       case 2: pc = "53 bits "; break;
4718       case 3: pc = "64 bits "; break;
4719     };
4720     // flags
4721     char f[9];
4722     f[0] = ' ';
4723     f[1] = ' ';
4724     f[2] = (precision   ()) ? 'P' : 'p';
4725     f[3] = (underflow   ()) ? 'U' : 'u';
4726     f[4] = (overflow    ()) ? 'O' : 'o';
4727     f[5] = (zero_divide ()) ? 'Z' : 'z';
4728     f[6] = (denormalized()) ? 'D' : 'd';
4729     f[7] = (invalid     ()) ? 'I' : 'i';
4730     f[8] = '\x0';
4731     // output
4732     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
4733   }
4734 
4735 };
4736 
4737 class StatusWord {
4738  public:
4739   int32_t _value;
4740 
4741   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
4742   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
4743   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
4744   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
4745   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
4746   int  top() const                     { return  (_value >> 11) & 7      ; }
4747   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
4748   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
4749   bool precision() const               { return ((_value >>  5) & 1) != 0; }
4750   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
4751   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
4752   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
4753   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
4754   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
4755 
4756   void print() const {
4757     // condition codes
4758     char c[5];
4759     c[0] = (C3()) ? '3' : '-';
4760     c[1] = (C2()) ? '2' : '-';
4761     c[2] = (C1()) ? '1' : '-';
4762     c[3] = (C0()) ? '0' : '-';
4763     c[4] = '\x0';
4764     // flags
4765     char f[9];
4766     f[0] = (error_status()) ? 'E' : '-';
4767     f[1] = (stack_fault ()) ? 'S' : '-';
4768     f[2] = (precision   ()) ? 'P' : '-';
4769     f[3] = (underflow   ()) ? 'U' : '-';
4770     f[4] = (overflow    ()) ? 'O' : '-';
4771     f[5] = (zero_divide ()) ? 'Z' : '-';
4772     f[6] = (denormalized()) ? 'D' : '-';
4773     f[7] = (invalid     ()) ? 'I' : '-';
4774     f[8] = '\x0';
4775     // output
4776     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
4777   }
4778 
4779 };
4780 
4781 class TagWord {
4782  public:
4783   int32_t _value;
4784 
4785   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
4786 
4787   void print() const {
4788     printf("%04x", _value & 0xFFFF);
4789   }
4790 
4791 };
4792 
4793 class FPU_Register {
4794  public:
4795   int32_t _m0;
4796   int32_t _m1;
4797   int16_t _ex;
4798 
4799   bool is_indefinite() const           {
4800     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
4801   }
4802 
4803   void print() const {
4804     char  sign = (_ex < 0) ? '-' : '+';
4805     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
4806     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
4807   };
4808 
4809 };
4810 
4811 class FPU_State {
4812  public:
4813   enum {
4814     register_size       = 10,
4815     number_of_registers =  8,
4816     register_mask       =  7
4817   };
4818 
4819   ControlWord  _control_word;
4820   StatusWord   _status_word;
4821   TagWord      _tag_word;
4822   int32_t      _error_offset;
4823   int32_t      _error_selector;
4824   int32_t      _data_offset;
4825   int32_t      _data_selector;
4826   int8_t       _register[register_size * number_of_registers];
4827 
4828   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
4829   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
4830 
4831   const char* tag_as_string(int tag) const {
4832     switch (tag) {
4833       case 0: return "valid";
4834       case 1: return "zero";
4835       case 2: return "special";
4836       case 3: return "empty";
4837     }
4838     ShouldNotReachHere();
4839     return NULL;
4840   }
4841 
4842   void print() const {
4843     // print computation registers
4844     { int t = _status_word.top();
4845       for (int i = 0; i < number_of_registers; i++) {
4846         int j = (i - t) & register_mask;
4847         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
4848         st(j)->print();
4849         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
4850       }
4851     }
4852     printf("\n");
4853     // print control registers
4854     printf("ctrl = "); _control_word.print(); printf("\n");
4855     printf("stat = "); _status_word .print(); printf("\n");
4856     printf("tags = "); _tag_word    .print(); printf("\n");
4857   }
4858 
4859 };
4860 
4861 class Flag_Register {
4862  public:
4863   int32_t _value;
4864 
4865   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
4866   bool direction() const               { return ((_value >> 10) & 1) != 0; }
4867   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
4868   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
4869   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
4870   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
4871   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
4872 
4873   void print() const {
4874     // flags
4875     char f[8];
4876     f[0] = (overflow       ()) ? 'O' : '-';
4877     f[1] = (direction      ()) ? 'D' : '-';
4878     f[2] = (sign           ()) ? 'S' : '-';
4879     f[3] = (zero           ()) ? 'Z' : '-';
4880     f[4] = (auxiliary_carry()) ? 'A' : '-';
4881     f[5] = (parity         ()) ? 'P' : '-';
4882     f[6] = (carry          ()) ? 'C' : '-';
4883     f[7] = '\x0';
4884     // output
4885     printf("%08x  flags = %s", _value, f);
4886   }
4887 
4888 };
4889 
4890 class IU_Register {
4891  public:
4892   int32_t _value;
4893 
4894   void print() const {
4895     printf("%08x  %11d", _value, _value);
4896   }
4897 
4898 };
4899 
4900 class IU_State {
4901  public:
4902   Flag_Register _eflags;
4903   IU_Register   _rdi;
4904   IU_Register   _rsi;
4905   IU_Register   _rbp;
4906   IU_Register   _rsp;
4907   IU_Register   _rbx;
4908   IU_Register   _rdx;
4909   IU_Register   _rcx;
4910   IU_Register   _rax;
4911 
4912   void print() const {
4913     // computation registers
4914     printf("rax,  = "); _rax.print(); printf("\n");
4915     printf("rbx,  = "); _rbx.print(); printf("\n");
4916     printf("rcx  = "); _rcx.print(); printf("\n");
4917     printf("rdx  = "); _rdx.print(); printf("\n");
4918     printf("rdi  = "); _rdi.print(); printf("\n");
4919     printf("rsi  = "); _rsi.print(); printf("\n");
4920     printf("rbp,  = "); _rbp.print(); printf("\n");
4921     printf("rsp  = "); _rsp.print(); printf("\n");
4922     printf("\n");
4923     // control registers
4924     printf("flgs = "); _eflags.print(); printf("\n");
4925   }
4926 };
4927 
4928 
4929 class CPU_State {
4930  public:
4931   FPU_State _fpu_state;
4932   IU_State  _iu_state;
4933 
4934   void print() const {
4935     printf("--------------------------------------------------\n");
4936     _iu_state .print();
4937     printf("\n");
4938     _fpu_state.print();
4939     printf("--------------------------------------------------\n");
4940   }
4941 
4942 };
4943 
4944 
4945 static void _print_CPU_state(CPU_State* state) {
4946   state->print();
4947 };
4948 
4949 
4950 void MacroAssembler::print_CPU_state() {
4951   push_CPU_state();
4952   push(rsp);                // pass CPU state
4953   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
4954   addptr(rsp, wordSize);       // discard argument
4955   pop_CPU_state();
4956 }
4957 
4958 
4959 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
4960   static int counter = 0;
4961   FPU_State* fs = &state->_fpu_state;
4962   counter++;
4963   // For leaf calls, only verify that the top few elements remain empty.
4964   // We only need 1 empty at the top for C2 code.
4965   if( stack_depth < 0 ) {
4966     if( fs->tag_for_st(7) != 3 ) {
4967       printf("FPR7 not empty\n");
4968       state->print();
4969       assert(false, "error");
4970       return false;
4971     }
4972     return true;                // All other stack states do not matter
4973   }
4974 
4975   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
4976          "bad FPU control word");
4977 
4978   // compute stack depth
4979   int i = 0;
4980   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
4981   int d = i;
4982   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
4983   // verify findings
4984   if (i != FPU_State::number_of_registers) {
4985     // stack not contiguous
4986     printf("%s: stack not contiguous at ST%d\n", s, i);
4987     state->print();
4988     assert(false, "error");
4989     return false;
4990   }
4991   // check if computed stack depth corresponds to expected stack depth
4992   if (stack_depth < 0) {
4993     // expected stack depth is -stack_depth or less
4994     if (d > -stack_depth) {
4995       // too many elements on the stack
4996       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
4997       state->print();
4998       assert(false, "error");
4999       return false;
5000     }
5001   } else {
5002     // expected stack depth is stack_depth
5003     if (d != stack_depth) {
5004       // wrong stack depth
5005       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
5006       state->print();
5007       assert(false, "error");
5008       return false;
5009     }
5010   }
5011   // everything is cool
5012   return true;
5013 }
5014 
5015 
5016 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
5017   if (!VerifyFPU) return;
5018   push_CPU_state();
5019   push(rsp);                // pass CPU state
5020   ExternalAddress msg((address) s);
5021   // pass message string s
5022   pushptr(msg.addr());
5023   push(stack_depth);        // pass stack depth
5024   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
5025   addptr(rsp, 3 * wordSize);   // discard arguments
5026   // check for error
5027   { Label L;
5028     testl(rax, rax);
5029     jcc(Assembler::notZero, L);
5030     int3();                  // break if error condition
5031     bind(L);
5032   }
5033   pop_CPU_state();
5034 }
5035 
5036 void MacroAssembler::restore_cpu_control_state_after_jni() {
5037   // Either restore the MXCSR register after returning from the JNI Call
5038   // or verify that it wasn't changed (with -Xcheck:jni flag).
5039   if (VM_Version::supports_sse()) {
5040     if (RestoreMXCSROnJNICalls) {
5041       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
5042     } else if (CheckJNICalls) {
5043       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
5044     }
5045   }
5046   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
5047   vzeroupper();
5048   // Reset k1 to 0xffff.
5049 
5050 #ifdef COMPILER2
5051   if (PostLoopMultiversioning && VM_Version::supports_evex()) {
5052     push(rcx);
5053     movl(rcx, 0xffff);
5054     kmovwl(k1, rcx);
5055     pop(rcx);
5056   }
5057 #endif // COMPILER2
5058 
5059 #ifndef _LP64
5060   // Either restore the x87 floating pointer control word after returning
5061   // from the JNI call or verify that it wasn't changed.
5062   if (CheckJNICalls) {
5063     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
5064   }
5065 #endif // _LP64
5066 }
5067 
5068 // ((OopHandle)result).resolve();
5069 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
5070   assert_different_registers(result, tmp);
5071 
5072   // Only 64 bit platforms support GCs that require a tmp register
5073   // Only IN_HEAP loads require a thread_tmp register
5074   // OopHandle::resolve is an indirection like jobject.
5075   access_load_at(T_OBJECT, IN_NATIVE,
5076                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
5077 }
5078 
5079 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
5080   // get mirror
5081   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
5082   movptr(mirror, Address(method, Method::const_offset()));
5083   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
5084   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
5085   movptr(mirror, Address(mirror, mirror_offset));
5086   resolve_oop_handle(mirror, tmp);
5087 }
5088 
5089 void MacroAssembler::load_metadata(Register dst, Register src) {
5090   if (UseCompressedClassPointers) {
5091     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5092   } else {
5093     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
5094   }
5095 }
5096 
5097 void MacroAssembler::load_storage_props(Register dst, Register src) {
5098   load_metadata(dst, src);
5099   if (UseCompressedClassPointers) {
5100     shrl(dst, oopDesc::narrow_storage_props_shift);
5101   } else {
5102     shrq(dst, oopDesc::wide_storage_props_shift);
5103   }
5104 }
5105 
5106 void MacroAssembler::load_klass(Register dst, Register src) {
5107   load_metadata(dst, src);
5108 #ifdef _LP64
5109   if (UseCompressedClassPointers) {
5110     andl(dst, oopDesc::compressed_klass_mask());
5111     decode_klass_not_null(dst);
5112   } else
5113 #endif
5114   {
5115 #ifdef _LP64
5116     shlq(dst, oopDesc::storage_props_nof_bits);
5117     shrq(dst, oopDesc::storage_props_nof_bits);
5118 #else
5119     andl(dst, oopDesc::wide_klass_mask());
5120 #endif
5121   }
5122 }
5123 
5124 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5125   load_klass(dst, src);
5126   movptr(dst, Address(dst, Klass::prototype_header_offset()));
5127 }
5128 
5129 void MacroAssembler::store_klass(Register dst, Register src) {
5130 #ifdef _LP64
5131   if (UseCompressedClassPointers) {
5132     encode_klass_not_null(src);
5133     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5134   } else
5135 #endif
5136     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5137 }
5138 
5139 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
5140                                     Register tmp1, Register thread_tmp) {
5141   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5142   decorators = AccessInternal::decorator_fixup(decorators);
5143   bool as_raw = (decorators & AS_RAW) != 0;
5144   if (as_raw) {
5145     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5146   } else {
5147     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5148   }
5149 }
5150 
5151 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
5152                                      Register tmp1, Register tmp2) {
5153   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5154   decorators = AccessInternal::decorator_fixup(decorators);
5155   bool as_raw = (decorators & AS_RAW) != 0;
5156   if (as_raw) {
5157     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
5158   } else {
5159     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
5160   }
5161 }
5162 
5163 void MacroAssembler::resolve(DecoratorSet decorators, Register obj) {
5164   // Use stronger ACCESS_WRITE|ACCESS_READ by default.
5165   if ((decorators & (ACCESS_READ | ACCESS_WRITE)) == 0) {
5166     decorators |= ACCESS_READ | ACCESS_WRITE;
5167   }
5168   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5169   return bs->resolve(this, decorators, obj);
5170 }
5171 
5172 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5173                                    Register thread_tmp, DecoratorSet decorators) {
5174   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
5175 }
5176 
5177 // Doesn't do verfication, generates fixed size code
5178 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5179                                             Register thread_tmp, DecoratorSet decorators) {
5180   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
5181 }
5182 
5183 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
5184                                     Register tmp2, DecoratorSet decorators) {
5185   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
5186 }
5187 
5188 // Used for storing NULLs.
5189 void MacroAssembler::store_heap_oop_null(Address dst) {
5190   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
5191 }
5192 
5193 #ifdef _LP64
5194 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5195   if (UseCompressedClassPointers) {
5196     // Store to klass gap in destination
5197     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
5198   }
5199 }
5200 
5201 #ifdef ASSERT
5202 void MacroAssembler::verify_heapbase(const char* msg) {
5203   assert (UseCompressedOops, "should be compressed");
5204   assert (Universe::heap() != NULL, "java heap should be initialized");
5205   if (CheckCompressedOops) {
5206     Label ok;
5207     push(rscratch1); // cmpptr trashes rscratch1
5208     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5209     jcc(Assembler::equal, ok);
5210     STOP(msg);
5211     bind(ok);
5212     pop(rscratch1);
5213   }
5214 }
5215 #endif
5216 
5217 // Algorithm must match oop.inline.hpp encode_heap_oop.
5218 void MacroAssembler::encode_heap_oop(Register r) {
5219 #ifdef ASSERT
5220   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5221 #endif
5222   verify_oop(r, "broken oop in encode_heap_oop");
5223   if (Universe::narrow_oop_base() == NULL) {
5224     if (Universe::narrow_oop_shift() != 0) {
5225       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5226       shrq(r, LogMinObjAlignmentInBytes);
5227     }
5228     return;
5229   }
5230   testq(r, r);
5231   cmovq(Assembler::equal, r, r12_heapbase);
5232   subq(r, r12_heapbase);
5233   shrq(r, LogMinObjAlignmentInBytes);
5234 }
5235 
5236 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5237 #ifdef ASSERT
5238   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5239   if (CheckCompressedOops) {
5240     Label ok;
5241     testq(r, r);
5242     jcc(Assembler::notEqual, ok);
5243     STOP("null oop passed to encode_heap_oop_not_null");
5244     bind(ok);
5245   }
5246 #endif
5247   verify_oop(r, "broken oop in encode_heap_oop_not_null");
5248   if (Universe::narrow_oop_base() != NULL) {
5249     subq(r, r12_heapbase);
5250   }
5251   if (Universe::narrow_oop_shift() != 0) {
5252     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5253     shrq(r, LogMinObjAlignmentInBytes);
5254   }
5255 }
5256 
5257 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5258 #ifdef ASSERT
5259   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5260   if (CheckCompressedOops) {
5261     Label ok;
5262     testq(src, src);
5263     jcc(Assembler::notEqual, ok);
5264     STOP("null oop passed to encode_heap_oop_not_null2");
5265     bind(ok);
5266   }
5267 #endif
5268   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
5269   if (dst != src) {
5270     movq(dst, src);
5271   }
5272   if (Universe::narrow_oop_base() != NULL) {
5273     subq(dst, r12_heapbase);
5274   }
5275   if (Universe::narrow_oop_shift() != 0) {
5276     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5277     shrq(dst, LogMinObjAlignmentInBytes);
5278   }
5279 }
5280 
5281 void  MacroAssembler::decode_heap_oop(Register r) {
5282 #ifdef ASSERT
5283   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5284 #endif
5285   if (Universe::narrow_oop_base() == NULL) {
5286     if (Universe::narrow_oop_shift() != 0) {
5287       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5288       shlq(r, LogMinObjAlignmentInBytes);
5289     }
5290   } else {
5291     Label done;
5292     shlq(r, LogMinObjAlignmentInBytes);
5293     jccb(Assembler::equal, done);
5294     addq(r, r12_heapbase);
5295     bind(done);
5296   }
5297   verify_oop(r, "broken oop in decode_heap_oop");
5298 }
5299 
5300 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5301   // Note: it will change flags
5302   assert (UseCompressedOops, "should only be used for compressed headers");
5303   assert (Universe::heap() != NULL, "java heap should be initialized");
5304   // Cannot assert, unverified entry point counts instructions (see .ad file)
5305   // vtableStubs also counts instructions in pd_code_size_limit.
5306   // Also do not verify_oop as this is called by verify_oop.
5307   if (Universe::narrow_oop_shift() != 0) {
5308     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5309     shlq(r, LogMinObjAlignmentInBytes);
5310     if (Universe::narrow_oop_base() != NULL) {
5311       addq(r, r12_heapbase);
5312     }
5313   } else {
5314     assert (Universe::narrow_oop_base() == NULL, "sanity");
5315   }
5316 }
5317 
5318 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5319   // Note: it will change flags
5320   assert (UseCompressedOops, "should only be used for compressed headers");
5321   assert (Universe::heap() != NULL, "java heap should be initialized");
5322   // Cannot assert, unverified entry point counts instructions (see .ad file)
5323   // vtableStubs also counts instructions in pd_code_size_limit.
5324   // Also do not verify_oop as this is called by verify_oop.
5325   if (Universe::narrow_oop_shift() != 0) {
5326     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5327     if (LogMinObjAlignmentInBytes == Address::times_8) {
5328       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
5329     } else {
5330       if (dst != src) {
5331         movq(dst, src);
5332       }
5333       shlq(dst, LogMinObjAlignmentInBytes);
5334       if (Universe::narrow_oop_base() != NULL) {
5335         addq(dst, r12_heapbase);
5336       }
5337     }
5338   } else {
5339     assert (Universe::narrow_oop_base() == NULL, "sanity");
5340     if (dst != src) {
5341       movq(dst, src);
5342     }
5343   }
5344 }
5345 
5346 void MacroAssembler::encode_klass_not_null(Register r) {
5347   if (Universe::narrow_klass_base() != NULL) {
5348     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5349     assert(r != r12_heapbase, "Encoding a klass in r12");
5350     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
5351     subq(r, r12_heapbase);
5352   }
5353   if (Universe::narrow_klass_shift() != 0) {
5354     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5355     shrq(r, LogKlassAlignmentInBytes);
5356   }
5357   if (Universe::narrow_klass_base() != NULL) {
5358     reinit_heapbase();
5359   }
5360 }
5361 
5362 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5363   if (dst == src) {
5364     encode_klass_not_null(src);
5365   } else {
5366     if (Universe::narrow_klass_base() != NULL) {
5367       mov64(dst, (int64_t)Universe::narrow_klass_base());
5368       negq(dst);
5369       addq(dst, src);
5370     } else {
5371       movptr(dst, src);
5372     }
5373     if (Universe::narrow_klass_shift() != 0) {
5374       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5375       shrq(dst, LogKlassAlignmentInBytes);
5376     }
5377   }
5378 }
5379 
5380 // Function instr_size_for_decode_klass_not_null() counts the instructions
5381 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
5382 // when (Universe::heap() != NULL).  Hence, if the instructions they
5383 // generate change, then this method needs to be updated.
5384 int MacroAssembler::instr_size_for_decode_klass_not_null() {
5385   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
5386   if (Universe::narrow_klass_base() != NULL) {
5387     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
5388     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
5389   } else {
5390     // longest load decode klass function, mov64, leaq
5391     return 16;
5392   }
5393 }
5394 
5395 // !!! If the instructions that get generated here change then function
5396 // instr_size_for_decode_klass_not_null() needs to get updated.
5397 void  MacroAssembler::decode_klass_not_null(Register r) {
5398   // Note: it will change flags
5399   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5400   assert(r != r12_heapbase, "Decoding a klass in r12");
5401   // Cannot assert, unverified entry point counts instructions (see .ad file)
5402   // vtableStubs also counts instructions in pd_code_size_limit.
5403   // Also do not verify_oop as this is called by verify_oop.
5404   if (Universe::narrow_klass_shift() != 0) {
5405     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5406     shlq(r, LogKlassAlignmentInBytes);
5407   }
5408   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5409   if (Universe::narrow_klass_base() != NULL) {
5410     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
5411     addq(r, r12_heapbase);
5412     reinit_heapbase();
5413   }
5414 }
5415 
5416 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
5417   // Note: it will change flags
5418   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5419   if (dst == src) {
5420     decode_klass_not_null(dst);
5421   } else {
5422     // Cannot assert, unverified entry point counts instructions (see .ad file)
5423     // vtableStubs also counts instructions in pd_code_size_limit.
5424     // Also do not verify_oop as this is called by verify_oop.
5425     mov64(dst, (int64_t)Universe::narrow_klass_base());
5426     if (Universe::narrow_klass_shift() != 0) {
5427       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5428       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
5429       leaq(dst, Address(dst, src, Address::times_8, 0));
5430     } else {
5431       addq(dst, src);
5432     }
5433   }
5434 }
5435 
5436 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5437   assert (UseCompressedOops, "should only be used for compressed headers");
5438   assert (Universe::heap() != NULL, "java heap should be initialized");
5439   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5440   int oop_index = oop_recorder()->find_index(obj);
5441   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5442   mov_narrow_oop(dst, oop_index, rspec);
5443 }
5444 
5445 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
5446   assert (UseCompressedOops, "should only be used for compressed headers");
5447   assert (Universe::heap() != NULL, "java heap should be initialized");
5448   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5449   int oop_index = oop_recorder()->find_index(obj);
5450   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5451   mov_narrow_oop(dst, oop_index, rspec);
5452 }
5453 
5454 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5455   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5456   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5457   int klass_index = oop_recorder()->find_index(k);
5458   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5459   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
5460 }
5461 
5462 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
5463   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5464   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5465   int klass_index = oop_recorder()->find_index(k);
5466   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5467   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
5468 }
5469 
5470 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
5471   assert (UseCompressedOops, "should only be used for compressed headers");
5472   assert (Universe::heap() != NULL, "java heap should be initialized");
5473   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5474   int oop_index = oop_recorder()->find_index(obj);
5475   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5476   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5477 }
5478 
5479 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
5480   assert (UseCompressedOops, "should only be used for compressed headers");
5481   assert (Universe::heap() != NULL, "java heap should be initialized");
5482   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5483   int oop_index = oop_recorder()->find_index(obj);
5484   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5485   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5486 }
5487 
5488 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
5489   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5490   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5491   int klass_index = oop_recorder()->find_index(k);
5492   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5493   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
5494 }
5495 
5496 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
5497   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5498   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5499   int klass_index = oop_recorder()->find_index(k);
5500   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5501   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
5502 }
5503 
5504 void MacroAssembler::reinit_heapbase() {
5505   if (UseCompressedOops || UseCompressedClassPointers) {
5506     if (Universe::heap() != NULL) {
5507       if (Universe::narrow_oop_base() == NULL) {
5508         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
5509       } else {
5510         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
5511       }
5512     } else {
5513       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5514     }
5515   }
5516 }
5517 
5518 #endif // _LP64
5519 
5520 // C2 compiled method's prolog code.
5521 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
5522   int framesize = C->frame_size_in_bytes();
5523   int bangsize = C->bang_size_in_bytes();
5524   bool fp_mode_24b = C->in_24_bit_fp_mode();
5525   int stack_bang_size = C->need_stack_bang(bangsize) ? bangsize : 0;
5526   bool is_stub = C->stub_function() != NULL;
5527 
5528   // WARNING: Initial instruction MUST be 5 bytes or longer so that
5529   // NativeJump::patch_verified_entry will be able to patch out the entry
5530   // code safely. The push to verify stack depth is ok at 5 bytes,
5531   // the frame allocation can be either 3 or 6 bytes. So if we don't do
5532   // stack bang then we must use the 6 byte frame allocation even if
5533   // we have no frame. :-(
5534   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
5535 
5536   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5537   // Remove word for return addr
5538   framesize -= wordSize;
5539   stack_bang_size -= wordSize;
5540 
5541   // Calls to C2R adapters often do not accept exceptional returns.
5542   // We require that their callers must bang for them.  But be careful, because
5543   // some VM calls (such as call site linkage) can use several kilobytes of
5544   // stack.  But the stack safety zone should account for that.
5545   // See bugs 4446381, 4468289, 4497237.
5546   if (stack_bang_size > 0) {
5547     generate_stack_overflow_check(stack_bang_size);
5548 
5549     // We always push rbp, so that on return to interpreter rbp, will be
5550     // restored correctly and we can correct the stack.
5551     push(rbp);
5552     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5553     if (PreserveFramePointer) {
5554       mov(rbp, rsp);
5555     }
5556     // Remove word for ebp
5557     framesize -= wordSize;
5558 
5559     // Create frame
5560     if (framesize) {
5561       subptr(rsp, framesize);
5562     }
5563   } else {
5564     // Create frame (force generation of a 4 byte immediate value)
5565     subptr_imm32(rsp, framesize);
5566 
5567     // Save RBP register now.
5568     framesize -= wordSize;
5569     movptr(Address(rsp, framesize), rbp);
5570     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5571     if (PreserveFramePointer) {
5572       movptr(rbp, rsp);
5573       if (framesize > 0) {
5574         addptr(rbp, framesize);
5575       }
5576     }
5577   }
5578 
5579   if (C->needs_stack_repair()) {
5580     // Save stack increment (also account for fixed framesize and rbp)
5581     assert((sp_inc & (StackAlignmentInBytes-1)) == 0, "stack increment not aligned");
5582     movptr(Address(rsp, C->sp_inc_offset()), sp_inc + framesize + wordSize);
5583   }
5584 
5585   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
5586     framesize -= wordSize;
5587     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
5588   }
5589 
5590 #ifndef _LP64
5591   // If method sets FPU control word do it now
5592   if (fp_mode_24b) {
5593     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
5594   }
5595   if (UseSSE >= 2 && VerifyFPU) {
5596     verify_FPU(0, "FPU stack must be clean on entry");
5597   }
5598 #endif
5599 
5600 #ifdef ASSERT
5601   if (VerifyStackAtCalls) {
5602     Label L;
5603     push(rax);
5604     mov(rax, rsp);
5605     andptr(rax, StackAlignmentInBytes-1);
5606     cmpptr(rax, StackAlignmentInBytes-wordSize);
5607     pop(rax);
5608     jcc(Assembler::equal, L);
5609     STOP("Stack is not properly aligned!");
5610     bind(L);
5611   }
5612 #endif
5613 
5614   if (!is_stub) {
5615     BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5616     bs->nmethod_entry_barrier(this);
5617   }
5618 }
5619 
5620 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM registers
5621 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, Register val, XMMRegister xtmp) {
5622   // cnt - number of qwords (8-byte words).
5623   // base - start address, qword aligned.
5624   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
5625   movdq(xtmp, val);
5626   if (UseAVX >= 2) {
5627     punpcklqdq(xtmp, xtmp);
5628     vinserti128_high(xtmp, xtmp);
5629   } else {
5630     punpcklqdq(xtmp, xtmp);
5631   }
5632   jmp(L_zero_64_bytes);
5633 
5634   BIND(L_loop);
5635   if (UseAVX >= 2) {
5636     vmovdqu(Address(base,  0), xtmp);
5637     vmovdqu(Address(base, 32), xtmp);
5638   } else {
5639     movdqu(Address(base,  0), xtmp);
5640     movdqu(Address(base, 16), xtmp);
5641     movdqu(Address(base, 32), xtmp);
5642     movdqu(Address(base, 48), xtmp);
5643   }
5644   addptr(base, 64);
5645 
5646   BIND(L_zero_64_bytes);
5647   subptr(cnt, 8);
5648   jccb(Assembler::greaterEqual, L_loop);
5649   addptr(cnt, 4);
5650   jccb(Assembler::less, L_tail);
5651   // Copy trailing 32 bytes
5652   if (UseAVX >= 2) {
5653     vmovdqu(Address(base, 0), xtmp);
5654   } else {
5655     movdqu(Address(base,  0), xtmp);
5656     movdqu(Address(base, 16), xtmp);
5657   }
5658   addptr(base, 32);
5659   subptr(cnt, 4);
5660 
5661   BIND(L_tail);
5662   addptr(cnt, 4);
5663   jccb(Assembler::lessEqual, L_end);
5664   decrement(cnt);
5665 
5666   BIND(L_sloop);
5667   movq(Address(base, 0), xtmp);
5668   addptr(base, 8);
5669   decrement(cnt);
5670   jccb(Assembler::greaterEqual, L_sloop);
5671   BIND(L_end);
5672 }
5673 
5674 // Move a value between registers/stack slots and update the reg_state
5675 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[], int ret_off) {
5676   if (reg_state[to->value()] == reg_written) {
5677     return true; // Already written
5678   }
5679   if (from != to && bt != T_VOID) {
5680     if (reg_state[to->value()] == reg_readonly) {
5681       return false; // Not yet writable
5682     }
5683     if (from->is_reg()) {
5684       if (to->is_reg()) {
5685         if (from->is_XMMRegister()) {
5686           if (bt == T_DOUBLE) {
5687             movdbl(to->as_XMMRegister(), from->as_XMMRegister());
5688           } else {
5689             assert(bt == T_FLOAT, "must be float");
5690             movflt(to->as_XMMRegister(), from->as_XMMRegister());
5691           }
5692         } else {
5693           movq(to->as_Register(), from->as_Register());
5694         }
5695       } else {
5696         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + wordSize;
5697         assert(st_off != ret_off, "overwriting return address at %d", st_off);
5698         Address to_addr = Address(rsp, st_off);
5699         if (from->is_XMMRegister()) {
5700           if (bt == T_DOUBLE) {
5701             movdbl(to_addr, from->as_XMMRegister());
5702           } else {
5703             assert(bt == T_FLOAT, "must be float");
5704             movflt(to_addr, from->as_XMMRegister());
5705           }
5706         } else {
5707           movq(to_addr, from->as_Register());
5708         }
5709       }
5710     } else {
5711       Address from_addr = Address(rsp, from->reg2stack() * VMRegImpl::stack_slot_size + wordSize);
5712       if (to->is_reg()) {
5713         if (to->is_XMMRegister()) {
5714           if (bt == T_DOUBLE) {
5715             movdbl(to->as_XMMRegister(), from_addr);
5716           } else {
5717             assert(bt == T_FLOAT, "must be float");
5718             movflt(to->as_XMMRegister(), from_addr);
5719           }
5720         } else {
5721           movq(to->as_Register(), from_addr);
5722         }
5723       } else {
5724         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + wordSize;
5725         assert(st_off != ret_off, "overwriting return address at %d", st_off);
5726         movq(r13, from_addr);
5727         movq(Address(rsp, st_off), r13);
5728       }
5729     }
5730   }
5731   // Update register states
5732   reg_state[from->value()] = reg_writable;
5733   reg_state[to->value()] = reg_written;
5734   return true;
5735 }
5736 
5737 // Read all fields from a value type oop and store the values in registers/stack slots
5738 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) {
5739   Register fromReg = from->is_reg() ? from->as_Register() : noreg;
5740   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
5741 
5742   int vt = 1;
5743   bool done = true;
5744   bool mark_done = true;
5745   do {
5746     sig_index--;
5747     BasicType bt = sig->at(sig_index)._bt;
5748     if (bt == T_VALUETYPE) {
5749       vt--;
5750     } else if (bt == T_VOID &&
5751                sig->at(sig_index-1)._bt != T_LONG &&
5752                sig->at(sig_index-1)._bt != T_DOUBLE) {
5753       vt++;
5754     } else if (SigEntry::is_reserved_entry(sig, sig_index)) {
5755       to_index--; // Ignore this
5756     } else {
5757       assert(to_index >= 0, "invalid to_index");
5758       VMRegPair pair_to = regs_to[to_index--];
5759       VMReg to = pair_to.first();
5760 
5761       if (bt == T_VOID) continue;
5762 
5763       int idx = (int)to->value();
5764       if (reg_state[idx] == reg_readonly) {
5765          if (idx != from->value()) {
5766            mark_done = false;
5767          }
5768          done = false;
5769          continue;
5770       } else if (reg_state[idx] == reg_written) {
5771         continue;
5772       } else {
5773         assert(reg_state[idx] == reg_writable, "must be writable");
5774         reg_state[idx] = reg_written;
5775        }
5776 
5777       if (fromReg == noreg) {
5778         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size + wordSize;
5779         movq(r10, Address(rsp, st_off));
5780         fromReg = r10;
5781       }
5782 
5783       int off = sig->at(sig_index)._offset;
5784       assert(off > 0, "offset in object should be positive");
5785       bool is_oop = (bt == T_OBJECT || bt == T_ARRAY);
5786 
5787       Address fromAddr = Address(fromReg, off);
5788       bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
5789       if (!to->is_XMMRegister()) {
5790         Register dst = to->is_stack() ? r13 : to->as_Register();
5791         if (is_oop) {
5792           load_heap_oop(dst, fromAddr);
5793         } else {
5794           load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
5795         }
5796         if (to->is_stack()) {
5797           int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + wordSize;
5798           assert(st_off != ret_off, "overwriting return address at %d", st_off);
5799           movq(Address(rsp, st_off), dst);
5800         }
5801       } else {
5802         if (bt == T_DOUBLE) {
5803           movdbl(to->as_XMMRegister(), fromAddr);
5804         } else {
5805           assert(bt == T_FLOAT, "must be float");
5806           movflt(to->as_XMMRegister(), fromAddr);
5807         }
5808       }
5809     }
5810   } while (vt != 0);
5811   if (mark_done && reg_state[from->value()] != reg_written) {
5812     // This is okay because no one else will write to that slot
5813     reg_state[from->value()] = reg_writable;
5814   }
5815   return done;
5816 }
5817 
5818 // Unpack all value type arguments passed as oops
5819 void MacroAssembler::unpack_value_args(Compile* C, bool receiver_only) {
5820   assert(C->has_scalarized_args(), "value type argument scalarization is disabled");
5821   Method* method = C->method()->get_Method();
5822   const GrowableArray<SigEntry>* sig_cc = method->adapter()->get_sig_cc();
5823   assert(sig_cc != NULL, "must have scalarized signature");
5824 
5825   // Get unscalarized calling convention
5826   BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sig_cc->length());
5827   int args_passed = 0;
5828   if (!method->is_static()) {
5829     sig_bt[args_passed++] = T_OBJECT;
5830   }
5831   if (!receiver_only) {
5832     for (SignatureStream ss(method->signature()); !ss.at_return_type(); ss.next()) {
5833       BasicType bt = ss.type();
5834       sig_bt[args_passed++] = bt;
5835       if (type2size[bt] == 2) {
5836         sig_bt[args_passed++] = T_VOID;
5837       }
5838     }
5839   } else {
5840     // Only unpack the receiver, all other arguments are already scalarized
5841     InstanceKlass* holder = method->method_holder();
5842     int rec_len = holder->is_value() ? ValueKlass::cast(holder)->extended_sig()->length() : 1;
5843     // Copy scalarized signature but skip receiver, value type delimiters and reserved entries
5844     for (int i = 0; i < sig_cc->length(); i++) {
5845       if (!SigEntry::is_reserved_entry(sig_cc, i)) {
5846         if (SigEntry::skip_value_delimiters(sig_cc, i) && rec_len <= 0) {
5847           sig_bt[args_passed++] = sig_cc->at(i)._bt;
5848         }
5849         rec_len--;
5850       }
5851     }
5852   }
5853   VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, args_passed);
5854   int args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, args_passed, false);
5855 
5856   // Get scalarized calling convention
5857   int args_passed_cc = SigEntry::fill_sig_bt(sig_cc, sig_bt);
5858   VMRegPair* regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, sig_cc->length());
5859   int args_on_stack_cc = SharedRuntime::java_calling_convention(sig_bt, regs_cc, args_passed_cc, false);
5860 
5861   // Check if we need to extend the stack for unpacking
5862   int sp_inc = (args_on_stack_cc - args_on_stack) * VMRegImpl::stack_slot_size;
5863   if (sp_inc > 0) {
5864     // Save the return address, adjust the stack (make sure it is properly
5865     // 16-byte aligned) and copy the return address to the new top of the stack.
5866     pop(r13);
5867     sp_inc = align_up(sp_inc, StackAlignmentInBytes);
5868     subptr(rsp, sp_inc);
5869     push(r13);
5870   } else {
5871     // The scalarized calling convention needs less stack space than the unscalarized one.
5872     // No need to extend the stack, the caller will take care of these adjustments.
5873     sp_inc = 0;
5874   }
5875 
5876   // Initialize register/stack slot states (make all writable)
5877   int max_stack = MAX2(args_on_stack + sp_inc/VMRegImpl::stack_slot_size, args_on_stack_cc);
5878   int max_reg = VMRegImpl::stack2reg(max_stack)->value();
5879   RegState* reg_state = NEW_RESOURCE_ARRAY(RegState, max_reg);
5880   for (int i = 0; i < max_reg; ++i) {
5881     reg_state[i] = reg_writable;
5882   }
5883   // Set all source registers/stack slots to readonly to prevent accidental overwriting
5884   for (int i = 0; i < args_passed; ++i) {
5885     VMReg reg = regs[i].first();
5886     if (!reg->is_valid()) continue;
5887     if (reg->is_stack()) {
5888       // Update source stack location by adding stack increment
5889       reg = VMRegImpl::stack2reg(reg->reg2stack() + sp_inc/VMRegImpl::stack_slot_size);
5890       regs[i] = reg;
5891     }
5892     assert(reg->value() >= 0 && reg->value() < max_reg, "reg value out of bounds");
5893     reg_state[reg->value()] = reg_readonly;
5894   }
5895 
5896   // Emit code for unpacking value type arguments
5897   // We try multiple times and eventually start spilling to resolve (circular) dependencies
5898   bool done = false;
5899   for (int i = 0; i < 2*args_passed_cc && !done; ++i) {
5900     done = true;
5901     bool spill = (i > args_passed_cc); // Start spilling?
5902     // Iterate over all arguments (in reverse)
5903     for (int from_index = args_passed-1, to_index = args_passed_cc-1, sig_index = sig_cc->length()-1; sig_index >= 0; sig_index--) {
5904       if (SigEntry::is_reserved_entry(sig_cc, sig_index)) {
5905         to_index--; // Skip reserved entry
5906       } else {
5907         assert(from_index >= 0, "index out of bounds");
5908         VMReg reg = regs[from_index].first();
5909         if (spill && reg->is_valid() && reg_state[reg->value()] == reg_readonly) {
5910           // Spill argument to be able to write the source and resolve circular dependencies
5911           VMReg spill_reg = reg->is_XMMRegister() ? xmm8->as_VMReg() : r14->as_VMReg();
5912           bool res = move_helper(reg, spill_reg, T_DOUBLE, reg_state, sp_inc);
5913           assert(res, "Spilling should not fail");
5914           // Set spill_reg as new source and update state
5915           reg = spill_reg;
5916           regs[from_index].set1(reg);
5917           reg_state[reg->value()] = reg_readonly;
5918           spill = false; // Do not spill again in this round
5919         }
5920         BasicType bt = sig_cc->at(sig_index)._bt;
5921         if (SigEntry::skip_value_delimiters(sig_cc, sig_index)) {
5922           assert(to_index >= 0, "index out of bounds");
5923           done &= move_helper(reg, regs_cc[to_index].first(), bt, reg_state, sp_inc);
5924           to_index--;
5925         } else if (!receiver_only || (from_index == 0 && bt == T_VOID)) {
5926           done &= unpack_value_helper(sig_cc, sig_index, reg, regs_cc, to_index, reg_state, sp_inc);
5927         } else {
5928           continue;
5929         }
5930         from_index--;
5931       }
5932     }
5933   }
5934   guarantee(done, "Could not resolve circular dependency when unpacking value type arguments");
5935 
5936   // Emit code for verified entry and save increment for stack repair on return
5937   verified_entry(C, sp_inc);
5938 }
5939 
5940 // Restores the stack on return
5941 void MacroAssembler::restore_stack(Compile* C) {
5942   int framesize = C->frame_size_in_bytes();
5943   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5944   // Remove word for return addr already pushed and RBP
5945   framesize -= 2*wordSize;
5946 
5947   if (C->needs_stack_repair()) {
5948     // Restore rbp and repair rsp by adding the stack increment
5949     movq(rbp, Address(rsp, framesize));
5950     addq(rsp, Address(rsp, C->sp_inc_offset()));
5951   } else {
5952     if (framesize > 0) {
5953       addq(rsp, framesize);
5954     }
5955     pop(rbp);
5956   }
5957 }
5958 
5959 void MacroAssembler::clear_mem(Register base, Register cnt, Register val, XMMRegister xtmp, bool is_large, bool word_copy_only) {
5960   // cnt - number of qwords (8-byte words).
5961   // base - start address, qword aligned.
5962   // is_large - if optimizers know cnt is larger than InitArrayShortSize
5963   assert(base==rdi, "base register must be edi for rep stos");
5964   assert(val==rax,   "tmp register must be eax for rep stos");
5965   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
5966   assert(InitArrayShortSize % BytesPerLong == 0,
5967     "InitArrayShortSize should be the multiple of BytesPerLong");
5968 
5969   Label DONE;
5970 
5971   if (!is_large) {
5972     Label LOOP, LONG;
5973     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
5974     jccb(Assembler::greater, LONG);
5975 
5976     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
5977 
5978     decrement(cnt);
5979     jccb(Assembler::negative, DONE); // Zero length
5980 
5981     // Use individual pointer-sized stores for small counts:
5982     BIND(LOOP);
5983     movptr(Address(base, cnt, Address::times_ptr), val);
5984     decrement(cnt);
5985     jccb(Assembler::greaterEqual, LOOP);
5986     jmpb(DONE);
5987 
5988     BIND(LONG);
5989   }
5990 
5991   // Use longer rep-prefixed ops for non-small counts:
5992   if (UseFastStosb && !word_copy_only) {
5993     shlptr(cnt, 3); // convert to number of bytes
5994     rep_stosb();
5995   } else if (UseXMMForObjInit) {
5996     xmm_clear_mem(base, cnt, val, xtmp);
5997   } else {
5998     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
5999     rep_stos();
6000   }
6001 
6002   BIND(DONE);
6003 }
6004 
6005 #ifdef COMPILER2
6006 
6007 // IndexOf for constant substrings with size >= 8 chars
6008 // which don't need to be loaded through stack.
6009 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6010                                       Register cnt1, Register cnt2,
6011                                       int int_cnt2,  Register result,
6012                                       XMMRegister vec, Register tmp,
6013                                       int ae) {
6014   ShortBranchVerifier sbv(this);
6015   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6016   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6017 
6018   // This method uses the pcmpestri instruction with bound registers
6019   //   inputs:
6020   //     xmm - substring
6021   //     rax - substring length (elements count)
6022   //     mem - scanned string
6023   //     rdx - string length (elements count)
6024   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6025   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6026   //   outputs:
6027   //     rcx - matched index in string
6028   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6029   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6030   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6031   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6032   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6033 
6034   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6035         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6036         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6037 
6038   // Note, inline_string_indexOf() generates checks:
6039   // if (substr.count > string.count) return -1;
6040   // if (substr.count == 0) return 0;
6041   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6042 
6043   // Load substring.
6044   if (ae == StrIntrinsicNode::UL) {
6045     pmovzxbw(vec, Address(str2, 0));
6046   } else {
6047     movdqu(vec, Address(str2, 0));
6048   }
6049   movl(cnt2, int_cnt2);
6050   movptr(result, str1); // string addr
6051 
6052   if (int_cnt2 > stride) {
6053     jmpb(SCAN_TO_SUBSTR);
6054 
6055     // Reload substr for rescan, this code
6056     // is executed only for large substrings (> 8 chars)
6057     bind(RELOAD_SUBSTR);
6058     if (ae == StrIntrinsicNode::UL) {
6059       pmovzxbw(vec, Address(str2, 0));
6060     } else {
6061       movdqu(vec, Address(str2, 0));
6062     }
6063     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6064 
6065     bind(RELOAD_STR);
6066     // We came here after the beginning of the substring was
6067     // matched but the rest of it was not so we need to search
6068     // again. Start from the next element after the previous match.
6069 
6070     // cnt2 is number of substring reminding elements and
6071     // cnt1 is number of string reminding elements when cmp failed.
6072     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6073     subl(cnt1, cnt2);
6074     addl(cnt1, int_cnt2);
6075     movl(cnt2, int_cnt2); // Now restore cnt2
6076 
6077     decrementl(cnt1);     // Shift to next element
6078     cmpl(cnt1, cnt2);
6079     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6080 
6081     addptr(result, (1<<scale1));
6082 
6083   } // (int_cnt2 > 8)
6084 
6085   // Scan string for start of substr in 16-byte vectors
6086   bind(SCAN_TO_SUBSTR);
6087   pcmpestri(vec, Address(result, 0), mode);
6088   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6089   subl(cnt1, stride);
6090   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6091   cmpl(cnt1, cnt2);
6092   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6093   addptr(result, 16);
6094   jmpb(SCAN_TO_SUBSTR);
6095 
6096   // Found a potential substr
6097   bind(FOUND_CANDIDATE);
6098   // Matched whole vector if first element matched (tmp(rcx) == 0).
6099   if (int_cnt2 == stride) {
6100     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6101   } else { // int_cnt2 > 8
6102     jccb(Assembler::overflow, FOUND_SUBSTR);
6103   }
6104   // After pcmpestri tmp(rcx) contains matched element index
6105   // Compute start addr of substr
6106   lea(result, Address(result, tmp, scale1));
6107 
6108   // Make sure string is still long enough
6109   subl(cnt1, tmp);
6110   cmpl(cnt1, cnt2);
6111   if (int_cnt2 == stride) {
6112     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6113   } else { // int_cnt2 > 8
6114     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6115   }
6116   // Left less then substring.
6117 
6118   bind(RET_NOT_FOUND);
6119   movl(result, -1);
6120   jmp(EXIT);
6121 
6122   if (int_cnt2 > stride) {
6123     // This code is optimized for the case when whole substring
6124     // is matched if its head is matched.
6125     bind(MATCH_SUBSTR_HEAD);
6126     pcmpestri(vec, Address(result, 0), mode);
6127     // Reload only string if does not match
6128     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6129 
6130     Label CONT_SCAN_SUBSTR;
6131     // Compare the rest of substring (> 8 chars).
6132     bind(FOUND_SUBSTR);
6133     // First 8 chars are already matched.
6134     negptr(cnt2);
6135     addptr(cnt2, stride);
6136 
6137     bind(SCAN_SUBSTR);
6138     subl(cnt1, stride);
6139     cmpl(cnt2, -stride); // Do not read beyond substring
6140     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6141     // Back-up strings to avoid reading beyond substring:
6142     // cnt1 = cnt1 - cnt2 + 8
6143     addl(cnt1, cnt2); // cnt2 is negative
6144     addl(cnt1, stride);
6145     movl(cnt2, stride); negptr(cnt2);
6146     bind(CONT_SCAN_SUBSTR);
6147     if (int_cnt2 < (int)G) {
6148       int tail_off1 = int_cnt2<<scale1;
6149       int tail_off2 = int_cnt2<<scale2;
6150       if (ae == StrIntrinsicNode::UL) {
6151         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6152       } else {
6153         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6154       }
6155       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6156     } else {
6157       // calculate index in register to avoid integer overflow (int_cnt2*2)
6158       movl(tmp, int_cnt2);
6159       addptr(tmp, cnt2);
6160       if (ae == StrIntrinsicNode::UL) {
6161         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6162       } else {
6163         movdqu(vec, Address(str2, tmp, scale2, 0));
6164       }
6165       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6166     }
6167     // Need to reload strings pointers if not matched whole vector
6168     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6169     addptr(cnt2, stride);
6170     jcc(Assembler::negative, SCAN_SUBSTR);
6171     // Fall through if found full substring
6172 
6173   } // (int_cnt2 > 8)
6174 
6175   bind(RET_FOUND);
6176   // Found result if we matched full small substring.
6177   // Compute substr offset
6178   subptr(result, str1);
6179   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6180     shrl(result, 1); // index
6181   }
6182   bind(EXIT);
6183 
6184 } // string_indexofC8
6185 
6186 // Small strings are loaded through stack if they cross page boundary.
6187 void MacroAssembler::string_indexof(Register str1, Register str2,
6188                                     Register cnt1, Register cnt2,
6189                                     int int_cnt2,  Register result,
6190                                     XMMRegister vec, Register tmp,
6191                                     int ae) {
6192   ShortBranchVerifier sbv(this);
6193   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6194   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6195 
6196   //
6197   // int_cnt2 is length of small (< 8 chars) constant substring
6198   // or (-1) for non constant substring in which case its length
6199   // is in cnt2 register.
6200   //
6201   // Note, inline_string_indexOf() generates checks:
6202   // if (substr.count > string.count) return -1;
6203   // if (substr.count == 0) return 0;
6204   //
6205   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6206   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
6207   // This method uses the pcmpestri instruction with bound registers
6208   //   inputs:
6209   //     xmm - substring
6210   //     rax - substring length (elements count)
6211   //     mem - scanned string
6212   //     rdx - string length (elements count)
6213   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6214   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6215   //   outputs:
6216   //     rcx - matched index in string
6217   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6218   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6219   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6220   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6221 
6222   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
6223         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
6224         FOUND_CANDIDATE;
6225 
6226   { //========================================================
6227     // We don't know where these strings are located
6228     // and we can't read beyond them. Load them through stack.
6229     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
6230 
6231     movptr(tmp, rsp); // save old SP
6232 
6233     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
6234       if (int_cnt2 == (1>>scale2)) { // One byte
6235         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
6236         load_unsigned_byte(result, Address(str2, 0));
6237         movdl(vec, result); // move 32 bits
6238       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
6239         // Not enough header space in 32-bit VM: 12+3 = 15.
6240         movl(result, Address(str2, -1));
6241         shrl(result, 8);
6242         movdl(vec, result); // move 32 bits
6243       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
6244         load_unsigned_short(result, Address(str2, 0));
6245         movdl(vec, result); // move 32 bits
6246       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
6247         movdl(vec, Address(str2, 0)); // move 32 bits
6248       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
6249         movq(vec, Address(str2, 0));  // move 64 bits
6250       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
6251         // Array header size is 12 bytes in 32-bit VM
6252         // + 6 bytes for 3 chars == 18 bytes,
6253         // enough space to load vec and shift.
6254         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
6255         if (ae == StrIntrinsicNode::UL) {
6256           int tail_off = int_cnt2-8;
6257           pmovzxbw(vec, Address(str2, tail_off));
6258           psrldq(vec, -2*tail_off);
6259         }
6260         else {
6261           int tail_off = int_cnt2*(1<<scale2);
6262           movdqu(vec, Address(str2, tail_off-16));
6263           psrldq(vec, 16-tail_off);
6264         }
6265       }
6266     } else { // not constant substring
6267       cmpl(cnt2, stride);
6268       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
6269 
6270       // We can read beyond string if srt+16 does not cross page boundary
6271       // since heaps are aligned and mapped by pages.
6272       assert(os::vm_page_size() < (int)G, "default page should be small");
6273       movl(result, str2); // We need only low 32 bits
6274       andl(result, (os::vm_page_size()-1));
6275       cmpl(result, (os::vm_page_size()-16));
6276       jccb(Assembler::belowEqual, CHECK_STR);
6277 
6278       // Move small strings to stack to allow load 16 bytes into vec.
6279       subptr(rsp, 16);
6280       int stk_offset = wordSize-(1<<scale2);
6281       push(cnt2);
6282 
6283       bind(COPY_SUBSTR);
6284       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
6285         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
6286         movb(Address(rsp, cnt2, scale2, stk_offset), result);
6287       } else if (ae == StrIntrinsicNode::UU) {
6288         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
6289         movw(Address(rsp, cnt2, scale2, stk_offset), result);
6290       }
6291       decrement(cnt2);
6292       jccb(Assembler::notZero, COPY_SUBSTR);
6293 
6294       pop(cnt2);
6295       movptr(str2, rsp);  // New substring address
6296     } // non constant
6297 
6298     bind(CHECK_STR);
6299     cmpl(cnt1, stride);
6300     jccb(Assembler::aboveEqual, BIG_STRINGS);
6301 
6302     // Check cross page boundary.
6303     movl(result, str1); // We need only low 32 bits
6304     andl(result, (os::vm_page_size()-1));
6305     cmpl(result, (os::vm_page_size()-16));
6306     jccb(Assembler::belowEqual, BIG_STRINGS);
6307 
6308     subptr(rsp, 16);
6309     int stk_offset = -(1<<scale1);
6310     if (int_cnt2 < 0) { // not constant
6311       push(cnt2);
6312       stk_offset += wordSize;
6313     }
6314     movl(cnt2, cnt1);
6315 
6316     bind(COPY_STR);
6317     if (ae == StrIntrinsicNode::LL) {
6318       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
6319       movb(Address(rsp, cnt2, scale1, stk_offset), result);
6320     } else {
6321       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
6322       movw(Address(rsp, cnt2, scale1, stk_offset), result);
6323     }
6324     decrement(cnt2);
6325     jccb(Assembler::notZero, COPY_STR);
6326 
6327     if (int_cnt2 < 0) { // not constant
6328       pop(cnt2);
6329     }
6330     movptr(str1, rsp);  // New string address
6331 
6332     bind(BIG_STRINGS);
6333     // Load substring.
6334     if (int_cnt2 < 0) { // -1
6335       if (ae == StrIntrinsicNode::UL) {
6336         pmovzxbw(vec, Address(str2, 0));
6337       } else {
6338         movdqu(vec, Address(str2, 0));
6339       }
6340       push(cnt2);       // substr count
6341       push(str2);       // substr addr
6342       push(str1);       // string addr
6343     } else {
6344       // Small (< 8 chars) constant substrings are loaded already.
6345       movl(cnt2, int_cnt2);
6346     }
6347     push(tmp);  // original SP
6348 
6349   } // Finished loading
6350 
6351   //========================================================
6352   // Start search
6353   //
6354 
6355   movptr(result, str1); // string addr
6356 
6357   if (int_cnt2  < 0) {  // Only for non constant substring
6358     jmpb(SCAN_TO_SUBSTR);
6359 
6360     // SP saved at sp+0
6361     // String saved at sp+1*wordSize
6362     // Substr saved at sp+2*wordSize
6363     // Substr count saved at sp+3*wordSize
6364 
6365     // Reload substr for rescan, this code
6366     // is executed only for large substrings (> 8 chars)
6367     bind(RELOAD_SUBSTR);
6368     movptr(str2, Address(rsp, 2*wordSize));
6369     movl(cnt2, Address(rsp, 3*wordSize));
6370     if (ae == StrIntrinsicNode::UL) {
6371       pmovzxbw(vec, Address(str2, 0));
6372     } else {
6373       movdqu(vec, Address(str2, 0));
6374     }
6375     // We came here after the beginning of the substring was
6376     // matched but the rest of it was not so we need to search
6377     // again. Start from the next element after the previous match.
6378     subptr(str1, result); // Restore counter
6379     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6380       shrl(str1, 1);
6381     }
6382     addl(cnt1, str1);
6383     decrementl(cnt1);   // Shift to next element
6384     cmpl(cnt1, cnt2);
6385     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6386 
6387     addptr(result, (1<<scale1));
6388   } // non constant
6389 
6390   // Scan string for start of substr in 16-byte vectors
6391   bind(SCAN_TO_SUBSTR);
6392   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6393   pcmpestri(vec, Address(result, 0), mode);
6394   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6395   subl(cnt1, stride);
6396   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6397   cmpl(cnt1, cnt2);
6398   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6399   addptr(result, 16);
6400 
6401   bind(ADJUST_STR);
6402   cmpl(cnt1, stride); // Do not read beyond string
6403   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6404   // Back-up string to avoid reading beyond string.
6405   lea(result, Address(result, cnt1, scale1, -16));
6406   movl(cnt1, stride);
6407   jmpb(SCAN_TO_SUBSTR);
6408 
6409   // Found a potential substr
6410   bind(FOUND_CANDIDATE);
6411   // After pcmpestri tmp(rcx) contains matched element index
6412 
6413   // Make sure string is still long enough
6414   subl(cnt1, tmp);
6415   cmpl(cnt1, cnt2);
6416   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
6417   // Left less then substring.
6418 
6419   bind(RET_NOT_FOUND);
6420   movl(result, -1);
6421   jmp(CLEANUP);
6422 
6423   bind(FOUND_SUBSTR);
6424   // Compute start addr of substr
6425   lea(result, Address(result, tmp, scale1));
6426   if (int_cnt2 > 0) { // Constant substring
6427     // Repeat search for small substring (< 8 chars)
6428     // from new point without reloading substring.
6429     // Have to check that we don't read beyond string.
6430     cmpl(tmp, stride-int_cnt2);
6431     jccb(Assembler::greater, ADJUST_STR);
6432     // Fall through if matched whole substring.
6433   } else { // non constant
6434     assert(int_cnt2 == -1, "should be != 0");
6435 
6436     addl(tmp, cnt2);
6437     // Found result if we matched whole substring.
6438     cmpl(tmp, stride);
6439     jcc(Assembler::lessEqual, RET_FOUND);
6440 
6441     // Repeat search for small substring (<= 8 chars)
6442     // from new point 'str1' without reloading substring.
6443     cmpl(cnt2, stride);
6444     // Have to check that we don't read beyond string.
6445     jccb(Assembler::lessEqual, ADJUST_STR);
6446 
6447     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
6448     // Compare the rest of substring (> 8 chars).
6449     movptr(str1, result);
6450 
6451     cmpl(tmp, cnt2);
6452     // First 8 chars are already matched.
6453     jccb(Assembler::equal, CHECK_NEXT);
6454 
6455     bind(SCAN_SUBSTR);
6456     pcmpestri(vec, Address(str1, 0), mode);
6457     // Need to reload strings pointers if not matched whole vector
6458     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6459 
6460     bind(CHECK_NEXT);
6461     subl(cnt2, stride);
6462     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
6463     addptr(str1, 16);
6464     if (ae == StrIntrinsicNode::UL) {
6465       addptr(str2, 8);
6466     } else {
6467       addptr(str2, 16);
6468     }
6469     subl(cnt1, stride);
6470     cmpl(cnt2, stride); // Do not read beyond substring
6471     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
6472     // Back-up strings to avoid reading beyond substring.
6473 
6474     if (ae == StrIntrinsicNode::UL) {
6475       lea(str2, Address(str2, cnt2, scale2, -8));
6476       lea(str1, Address(str1, cnt2, scale1, -16));
6477     } else {
6478       lea(str2, Address(str2, cnt2, scale2, -16));
6479       lea(str1, Address(str1, cnt2, scale1, -16));
6480     }
6481     subl(cnt1, cnt2);
6482     movl(cnt2, stride);
6483     addl(cnt1, stride);
6484     bind(CONT_SCAN_SUBSTR);
6485     if (ae == StrIntrinsicNode::UL) {
6486       pmovzxbw(vec, Address(str2, 0));
6487     } else {
6488       movdqu(vec, Address(str2, 0));
6489     }
6490     jmp(SCAN_SUBSTR);
6491 
6492     bind(RET_FOUND_LONG);
6493     movptr(str1, Address(rsp, wordSize));
6494   } // non constant
6495 
6496   bind(RET_FOUND);
6497   // Compute substr offset
6498   subptr(result, str1);
6499   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6500     shrl(result, 1); // index
6501   }
6502   bind(CLEANUP);
6503   pop(rsp); // restore SP
6504 
6505 } // string_indexof
6506 
6507 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
6508                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
6509   ShortBranchVerifier sbv(this);
6510   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6511 
6512   int stride = 8;
6513 
6514   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
6515         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
6516         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
6517         FOUND_SEQ_CHAR, DONE_LABEL;
6518 
6519   movptr(result, str1);
6520   if (UseAVX >= 2) {
6521     cmpl(cnt1, stride);
6522     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
6523     cmpl(cnt1, 2*stride);
6524     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
6525     movdl(vec1, ch);
6526     vpbroadcastw(vec1, vec1, Assembler::AVX_256bit);
6527     vpxor(vec2, vec2);
6528     movl(tmp, cnt1);
6529     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
6530     andl(cnt1,0x0000000F);  //tail count (in chars)
6531 
6532     bind(SCAN_TO_16_CHAR_LOOP);
6533     vmovdqu(vec3, Address(result, 0));
6534     vpcmpeqw(vec3, vec3, vec1, 1);
6535     vptest(vec2, vec3);
6536     jcc(Assembler::carryClear, FOUND_CHAR);
6537     addptr(result, 32);
6538     subl(tmp, 2*stride);
6539     jcc(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
6540     jmp(SCAN_TO_8_CHAR);
6541     bind(SCAN_TO_8_CHAR_INIT);
6542     movdl(vec1, ch);
6543     pshuflw(vec1, vec1, 0x00);
6544     pshufd(vec1, vec1, 0);
6545     pxor(vec2, vec2);
6546   }
6547   bind(SCAN_TO_8_CHAR);
6548   cmpl(cnt1, stride);
6549   if (UseAVX >= 2) {
6550     jcc(Assembler::less, SCAN_TO_CHAR);
6551   } else {
6552     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
6553     movdl(vec1, ch);
6554     pshuflw(vec1, vec1, 0x00);
6555     pshufd(vec1, vec1, 0);
6556     pxor(vec2, vec2);
6557   }
6558   movl(tmp, cnt1);
6559   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
6560   andl(cnt1,0x00000007);  //tail count (in chars)
6561 
6562   bind(SCAN_TO_8_CHAR_LOOP);
6563   movdqu(vec3, Address(result, 0));
6564   pcmpeqw(vec3, vec1);
6565   ptest(vec2, vec3);
6566   jcc(Assembler::carryClear, FOUND_CHAR);
6567   addptr(result, 16);
6568   subl(tmp, stride);
6569   jcc(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
6570   bind(SCAN_TO_CHAR);
6571   testl(cnt1, cnt1);
6572   jcc(Assembler::zero, RET_NOT_FOUND);
6573   bind(SCAN_TO_CHAR_LOOP);
6574   load_unsigned_short(tmp, Address(result, 0));
6575   cmpl(ch, tmp);
6576   jccb(Assembler::equal, FOUND_SEQ_CHAR);
6577   addptr(result, 2);
6578   subl(cnt1, 1);
6579   jccb(Assembler::zero, RET_NOT_FOUND);
6580   jmp(SCAN_TO_CHAR_LOOP);
6581 
6582   bind(RET_NOT_FOUND);
6583   movl(result, -1);
6584   jmpb(DONE_LABEL);
6585 
6586   bind(FOUND_CHAR);
6587   if (UseAVX >= 2) {
6588     vpmovmskb(tmp, vec3);
6589   } else {
6590     pmovmskb(tmp, vec3);
6591   }
6592   bsfl(ch, tmp);
6593   addl(result, ch);
6594 
6595   bind(FOUND_SEQ_CHAR);
6596   subptr(result, str1);
6597   shrl(result, 1);
6598 
6599   bind(DONE_LABEL);
6600 } // string_indexof_char
6601 
6602 // helper function for string_compare
6603 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
6604                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
6605                                         Address::ScaleFactor scale2, Register index, int ae) {
6606   if (ae == StrIntrinsicNode::LL) {
6607     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
6608     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
6609   } else if (ae == StrIntrinsicNode::UU) {
6610     load_unsigned_short(elem1, Address(str1, index, scale, 0));
6611     load_unsigned_short(elem2, Address(str2, index, scale, 0));
6612   } else {
6613     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
6614     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
6615   }
6616 }
6617 
6618 // Compare strings, used for char[] and byte[].
6619 void MacroAssembler::string_compare(Register str1, Register str2,
6620                                     Register cnt1, Register cnt2, Register result,
6621                                     XMMRegister vec1, int ae) {
6622   ShortBranchVerifier sbv(this);
6623   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
6624   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
6625   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
6626   int stride2x2 = 0x40;
6627   Address::ScaleFactor scale = Address::no_scale;
6628   Address::ScaleFactor scale1 = Address::no_scale;
6629   Address::ScaleFactor scale2 = Address::no_scale;
6630 
6631   if (ae != StrIntrinsicNode::LL) {
6632     stride2x2 = 0x20;
6633   }
6634 
6635   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
6636     shrl(cnt2, 1);
6637   }
6638   // Compute the minimum of the string lengths and the
6639   // difference of the string lengths (stack).
6640   // Do the conditional move stuff
6641   movl(result, cnt1);
6642   subl(cnt1, cnt2);
6643   push(cnt1);
6644   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
6645 
6646   // Is the minimum length zero?
6647   testl(cnt2, cnt2);
6648   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6649   if (ae == StrIntrinsicNode::LL) {
6650     // Load first bytes
6651     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
6652     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
6653   } else if (ae == StrIntrinsicNode::UU) {
6654     // Load first characters
6655     load_unsigned_short(result, Address(str1, 0));
6656     load_unsigned_short(cnt1, Address(str2, 0));
6657   } else {
6658     load_unsigned_byte(result, Address(str1, 0));
6659     load_unsigned_short(cnt1, Address(str2, 0));
6660   }
6661   subl(result, cnt1);
6662   jcc(Assembler::notZero,  POP_LABEL);
6663 
6664   if (ae == StrIntrinsicNode::UU) {
6665     // Divide length by 2 to get number of chars
6666     shrl(cnt2, 1);
6667   }
6668   cmpl(cnt2, 1);
6669   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6670 
6671   // Check if the strings start at the same location and setup scale and stride
6672   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6673     cmpptr(str1, str2);
6674     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6675     if (ae == StrIntrinsicNode::LL) {
6676       scale = Address::times_1;
6677       stride = 16;
6678     } else {
6679       scale = Address::times_2;
6680       stride = 8;
6681     }
6682   } else {
6683     scale1 = Address::times_1;
6684     scale2 = Address::times_2;
6685     // scale not used
6686     stride = 8;
6687   }
6688 
6689   if (UseAVX >= 2 && UseSSE42Intrinsics) {
6690     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
6691     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
6692     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
6693     Label COMPARE_TAIL_LONG;
6694     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
6695 
6696     int pcmpmask = 0x19;
6697     if (ae == StrIntrinsicNode::LL) {
6698       pcmpmask &= ~0x01;
6699     }
6700 
6701     // Setup to compare 16-chars (32-bytes) vectors,
6702     // start from first character again because it has aligned address.
6703     if (ae == StrIntrinsicNode::LL) {
6704       stride2 = 32;
6705     } else {
6706       stride2 = 16;
6707     }
6708     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6709       adr_stride = stride << scale;
6710     } else {
6711       adr_stride1 = 8;  //stride << scale1;
6712       adr_stride2 = 16; //stride << scale2;
6713     }
6714 
6715     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
6716     // rax and rdx are used by pcmpestri as elements counters
6717     movl(result, cnt2);
6718     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
6719     jcc(Assembler::zero, COMPARE_TAIL_LONG);
6720 
6721     // fast path : compare first 2 8-char vectors.
6722     bind(COMPARE_16_CHARS);
6723     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6724       movdqu(vec1, Address(str1, 0));
6725     } else {
6726       pmovzxbw(vec1, Address(str1, 0));
6727     }
6728     pcmpestri(vec1, Address(str2, 0), pcmpmask);
6729     jccb(Assembler::below, COMPARE_INDEX_CHAR);
6730 
6731     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6732       movdqu(vec1, Address(str1, adr_stride));
6733       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
6734     } else {
6735       pmovzxbw(vec1, Address(str1, adr_stride1));
6736       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
6737     }
6738     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
6739     addl(cnt1, stride);
6740 
6741     // Compare the characters at index in cnt1
6742     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
6743     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
6744     subl(result, cnt2);
6745     jmp(POP_LABEL);
6746 
6747     // Setup the registers to start vector comparison loop
6748     bind(COMPARE_WIDE_VECTORS);
6749     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6750       lea(str1, Address(str1, result, scale));
6751       lea(str2, Address(str2, result, scale));
6752     } else {
6753       lea(str1, Address(str1, result, scale1));
6754       lea(str2, Address(str2, result, scale2));
6755     }
6756     subl(result, stride2);
6757     subl(cnt2, stride2);
6758     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
6759     negptr(result);
6760 
6761     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
6762     bind(COMPARE_WIDE_VECTORS_LOOP);
6763 
6764 #ifdef _LP64
6765     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
6766       cmpl(cnt2, stride2x2);
6767       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
6768       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
6769       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
6770 
6771       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
6772       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6773         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
6774         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
6775       } else {
6776         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
6777         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
6778       }
6779       kortestql(k7, k7);
6780       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
6781       addptr(result, stride2x2);  // update since we already compared at this addr
6782       subl(cnt2, stride2x2);      // and sub the size too
6783       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
6784 
6785       vpxor(vec1, vec1);
6786       jmpb(COMPARE_WIDE_TAIL);
6787     }//if (VM_Version::supports_avx512vlbw())
6788 #endif // _LP64
6789 
6790 
6791     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
6792     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6793       vmovdqu(vec1, Address(str1, result, scale));
6794       vpxor(vec1, Address(str2, result, scale));
6795     } else {
6796       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
6797       vpxor(vec1, Address(str2, result, scale2));
6798     }
6799     vptest(vec1, vec1);
6800     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
6801     addptr(result, stride2);
6802     subl(cnt2, stride2);
6803     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
6804     // clean upper bits of YMM registers
6805     vpxor(vec1, vec1);
6806 
6807     // compare wide vectors tail
6808     bind(COMPARE_WIDE_TAIL);
6809     testptr(result, result);
6810     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6811 
6812     movl(result, stride2);
6813     movl(cnt2, result);
6814     negptr(result);
6815     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
6816 
6817     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
6818     bind(VECTOR_NOT_EQUAL);
6819     // clean upper bits of YMM registers
6820     vpxor(vec1, vec1);
6821     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6822       lea(str1, Address(str1, result, scale));
6823       lea(str2, Address(str2, result, scale));
6824     } else {
6825       lea(str1, Address(str1, result, scale1));
6826       lea(str2, Address(str2, result, scale2));
6827     }
6828     jmp(COMPARE_16_CHARS);
6829 
6830     // Compare tail chars, length between 1 to 15 chars
6831     bind(COMPARE_TAIL_LONG);
6832     movl(cnt2, result);
6833     cmpl(cnt2, stride);
6834     jcc(Assembler::less, COMPARE_SMALL_STR);
6835 
6836     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6837       movdqu(vec1, Address(str1, 0));
6838     } else {
6839       pmovzxbw(vec1, Address(str1, 0));
6840     }
6841     pcmpestri(vec1, Address(str2, 0), pcmpmask);
6842     jcc(Assembler::below, COMPARE_INDEX_CHAR);
6843     subptr(cnt2, stride);
6844     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6845     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6846       lea(str1, Address(str1, result, scale));
6847       lea(str2, Address(str2, result, scale));
6848     } else {
6849       lea(str1, Address(str1, result, scale1));
6850       lea(str2, Address(str2, result, scale2));
6851     }
6852     negptr(cnt2);
6853     jmpb(WHILE_HEAD_LABEL);
6854 
6855     bind(COMPARE_SMALL_STR);
6856   } else if (UseSSE42Intrinsics) {
6857     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
6858     int pcmpmask = 0x19;
6859     // Setup to compare 8-char (16-byte) vectors,
6860     // start from first character again because it has aligned address.
6861     movl(result, cnt2);
6862     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
6863     if (ae == StrIntrinsicNode::LL) {
6864       pcmpmask &= ~0x01;
6865     }
6866     jcc(Assembler::zero, COMPARE_TAIL);
6867     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6868       lea(str1, Address(str1, result, scale));
6869       lea(str2, Address(str2, result, scale));
6870     } else {
6871       lea(str1, Address(str1, result, scale1));
6872       lea(str2, Address(str2, result, scale2));
6873     }
6874     negptr(result);
6875 
6876     // pcmpestri
6877     //   inputs:
6878     //     vec1- substring
6879     //     rax - negative string length (elements count)
6880     //     mem - scanned string
6881     //     rdx - string length (elements count)
6882     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
6883     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
6884     //   outputs:
6885     //     rcx - first mismatched element index
6886     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
6887 
6888     bind(COMPARE_WIDE_VECTORS);
6889     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6890       movdqu(vec1, Address(str1, result, scale));
6891       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
6892     } else {
6893       pmovzxbw(vec1, Address(str1, result, scale1));
6894       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
6895     }
6896     // After pcmpestri cnt1(rcx) contains mismatched element index
6897 
6898     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
6899     addptr(result, stride);
6900     subptr(cnt2, stride);
6901     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
6902 
6903     // compare wide vectors tail
6904     testptr(result, result);
6905     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6906 
6907     movl(cnt2, stride);
6908     movl(result, stride);
6909     negptr(result);
6910     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6911       movdqu(vec1, Address(str1, result, scale));
6912       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
6913     } else {
6914       pmovzxbw(vec1, Address(str1, result, scale1));
6915       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
6916     }
6917     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
6918 
6919     // Mismatched characters in the vectors
6920     bind(VECTOR_NOT_EQUAL);
6921     addptr(cnt1, result);
6922     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
6923     subl(result, cnt2);
6924     jmpb(POP_LABEL);
6925 
6926     bind(COMPARE_TAIL); // limit is zero
6927     movl(cnt2, result);
6928     // Fallthru to tail compare
6929   }
6930   // Shift str2 and str1 to the end of the arrays, negate min
6931   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6932     lea(str1, Address(str1, cnt2, scale));
6933     lea(str2, Address(str2, cnt2, scale));
6934   } else {
6935     lea(str1, Address(str1, cnt2, scale1));
6936     lea(str2, Address(str2, cnt2, scale2));
6937   }
6938   decrementl(cnt2);  // first character was compared already
6939   negptr(cnt2);
6940 
6941   // Compare the rest of the elements
6942   bind(WHILE_HEAD_LABEL);
6943   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
6944   subl(result, cnt1);
6945   jccb(Assembler::notZero, POP_LABEL);
6946   increment(cnt2);
6947   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
6948 
6949   // Strings are equal up to min length.  Return the length difference.
6950   bind(LENGTH_DIFF_LABEL);
6951   pop(result);
6952   if (ae == StrIntrinsicNode::UU) {
6953     // Divide diff by 2 to get number of chars
6954     sarl(result, 1);
6955   }
6956   jmpb(DONE_LABEL);
6957 
6958 #ifdef _LP64
6959   if (VM_Version::supports_avx512vlbw()) {
6960 
6961     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
6962 
6963     kmovql(cnt1, k7);
6964     notq(cnt1);
6965     bsfq(cnt2, cnt1);
6966     if (ae != StrIntrinsicNode::LL) {
6967       // Divide diff by 2 to get number of chars
6968       sarl(cnt2, 1);
6969     }
6970     addq(result, cnt2);
6971     if (ae == StrIntrinsicNode::LL) {
6972       load_unsigned_byte(cnt1, Address(str2, result));
6973       load_unsigned_byte(result, Address(str1, result));
6974     } else if (ae == StrIntrinsicNode::UU) {
6975       load_unsigned_short(cnt1, Address(str2, result, scale));
6976       load_unsigned_short(result, Address(str1, result, scale));
6977     } else {
6978       load_unsigned_short(cnt1, Address(str2, result, scale2));
6979       load_unsigned_byte(result, Address(str1, result, scale1));
6980     }
6981     subl(result, cnt1);
6982     jmpb(POP_LABEL);
6983   }//if (VM_Version::supports_avx512vlbw())
6984 #endif // _LP64
6985 
6986   // Discard the stored length difference
6987   bind(POP_LABEL);
6988   pop(cnt1);
6989 
6990   // That's it
6991   bind(DONE_LABEL);
6992   if(ae == StrIntrinsicNode::UL) {
6993     negl(result);
6994   }
6995 
6996 }
6997 
6998 // Search for Non-ASCII character (Negative byte value) in a byte array,
6999 // return true if it has any and false otherwise.
7000 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7001 //   @HotSpotIntrinsicCandidate
7002 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7003 //     for (int i = off; i < off + len; i++) {
7004 //       if (ba[i] < 0) {
7005 //         return true;
7006 //       }
7007 //     }
7008 //     return false;
7009 //   }
7010 void MacroAssembler::has_negatives(Register ary1, Register len,
7011   Register result, Register tmp1,
7012   XMMRegister vec1, XMMRegister vec2) {
7013   // rsi: byte array
7014   // rcx: len
7015   // rax: result
7016   ShortBranchVerifier sbv(this);
7017   assert_different_registers(ary1, len, result, tmp1);
7018   assert_different_registers(vec1, vec2);
7019   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7020 
7021   // len == 0
7022   testl(len, len);
7023   jcc(Assembler::zero, FALSE_LABEL);
7024 
7025   if ((UseAVX > 2) && // AVX512
7026     VM_Version::supports_avx512vlbw() &&
7027     VM_Version::supports_bmi2()) {
7028 
7029     Label test_64_loop, test_tail;
7030     Register tmp3_aliased = len;
7031 
7032     movl(tmp1, len);
7033     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7034 
7035     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7036     andl(len, ~(64 - 1));    // vector count (in chars)
7037     jccb(Assembler::zero, test_tail);
7038 
7039     lea(ary1, Address(ary1, len, Address::times_1));
7040     negptr(len);
7041 
7042     bind(test_64_loop);
7043     // Check whether our 64 elements of size byte contain negatives
7044     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7045     kortestql(k2, k2);
7046     jcc(Assembler::notZero, TRUE_LABEL);
7047 
7048     addptr(len, 64);
7049     jccb(Assembler::notZero, test_64_loop);
7050 
7051 
7052     bind(test_tail);
7053     // bail out when there is nothing to be done
7054     testl(tmp1, -1);
7055     jcc(Assembler::zero, FALSE_LABEL);
7056 
7057     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7058 #ifdef _LP64
7059     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7060     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7061     notq(tmp3_aliased);
7062     kmovql(k3, tmp3_aliased);
7063 #else
7064     Label k_init;
7065     jmp(k_init);
7066 
7067     // We could not read 64-bits from a general purpose register thus we move
7068     // data required to compose 64 1's to the instruction stream
7069     // We emit 64 byte wide series of elements from 0..63 which later on would
7070     // be used as a compare targets with tail count contained in tmp1 register.
7071     // Result would be a k register having tmp1 consecutive number or 1
7072     // counting from least significant bit.
7073     address tmp = pc();
7074     emit_int64(0x0706050403020100);
7075     emit_int64(0x0F0E0D0C0B0A0908);
7076     emit_int64(0x1716151413121110);
7077     emit_int64(0x1F1E1D1C1B1A1918);
7078     emit_int64(0x2726252423222120);
7079     emit_int64(0x2F2E2D2C2B2A2928);
7080     emit_int64(0x3736353433323130);
7081     emit_int64(0x3F3E3D3C3B3A3938);
7082 
7083     bind(k_init);
7084     lea(len, InternalAddress(tmp));
7085     // create mask to test for negative byte inside a vector
7086     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7087     evpcmpgtb(k3, vec1, Address(len, 0), Assembler::AVX_512bit);
7088 
7089 #endif
7090     evpcmpgtb(k2, k3, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7091     ktestq(k2, k3);
7092     jcc(Assembler::notZero, TRUE_LABEL);
7093 
7094     jmp(FALSE_LABEL);
7095   } else {
7096     movl(result, len); // copy
7097 
7098     if (UseAVX == 2 && UseSSE >= 2) {
7099       // With AVX2, use 32-byte vector compare
7100       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7101 
7102       // Compare 32-byte vectors
7103       andl(result, 0x0000001f);  //   tail count (in bytes)
7104       andl(len, 0xffffffe0);   // vector count (in bytes)
7105       jccb(Assembler::zero, COMPARE_TAIL);
7106 
7107       lea(ary1, Address(ary1, len, Address::times_1));
7108       negptr(len);
7109 
7110       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7111       movdl(vec2, tmp1);
7112       vpbroadcastd(vec2, vec2, Assembler::AVX_256bit);
7113 
7114       bind(COMPARE_WIDE_VECTORS);
7115       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7116       vptest(vec1, vec2);
7117       jccb(Assembler::notZero, TRUE_LABEL);
7118       addptr(len, 32);
7119       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7120 
7121       testl(result, result);
7122       jccb(Assembler::zero, FALSE_LABEL);
7123 
7124       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7125       vptest(vec1, vec2);
7126       jccb(Assembler::notZero, TRUE_LABEL);
7127       jmpb(FALSE_LABEL);
7128 
7129       bind(COMPARE_TAIL); // len is zero
7130       movl(len, result);
7131       // Fallthru to tail compare
7132     } else if (UseSSE42Intrinsics) {
7133       // With SSE4.2, use double quad vector compare
7134       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7135 
7136       // Compare 16-byte vectors
7137       andl(result, 0x0000000f);  //   tail count (in bytes)
7138       andl(len, 0xfffffff0);   // vector count (in bytes)
7139       jcc(Assembler::zero, COMPARE_TAIL);
7140 
7141       lea(ary1, Address(ary1, len, Address::times_1));
7142       negptr(len);
7143 
7144       movl(tmp1, 0x80808080);
7145       movdl(vec2, tmp1);
7146       pshufd(vec2, vec2, 0);
7147 
7148       bind(COMPARE_WIDE_VECTORS);
7149       movdqu(vec1, Address(ary1, len, Address::times_1));
7150       ptest(vec1, vec2);
7151       jcc(Assembler::notZero, TRUE_LABEL);
7152       addptr(len, 16);
7153       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7154 
7155       testl(result, result);
7156       jcc(Assembler::zero, FALSE_LABEL);
7157 
7158       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7159       ptest(vec1, vec2);
7160       jccb(Assembler::notZero, TRUE_LABEL);
7161       jmpb(FALSE_LABEL);
7162 
7163       bind(COMPARE_TAIL); // len is zero
7164       movl(len, result);
7165       // Fallthru to tail compare
7166     }
7167   }
7168   // Compare 4-byte vectors
7169   andl(len, 0xfffffffc); // vector count (in bytes)
7170   jccb(Assembler::zero, COMPARE_CHAR);
7171 
7172   lea(ary1, Address(ary1, len, Address::times_1));
7173   negptr(len);
7174 
7175   bind(COMPARE_VECTORS);
7176   movl(tmp1, Address(ary1, len, Address::times_1));
7177   andl(tmp1, 0x80808080);
7178   jccb(Assembler::notZero, TRUE_LABEL);
7179   addptr(len, 4);
7180   jcc(Assembler::notZero, COMPARE_VECTORS);
7181 
7182   // Compare trailing char (final 2 bytes), if any
7183   bind(COMPARE_CHAR);
7184   testl(result, 0x2);   // tail  char
7185   jccb(Assembler::zero, COMPARE_BYTE);
7186   load_unsigned_short(tmp1, Address(ary1, 0));
7187   andl(tmp1, 0x00008080);
7188   jccb(Assembler::notZero, TRUE_LABEL);
7189   subptr(result, 2);
7190   lea(ary1, Address(ary1, 2));
7191 
7192   bind(COMPARE_BYTE);
7193   testl(result, 0x1);   // tail  byte
7194   jccb(Assembler::zero, FALSE_LABEL);
7195   load_unsigned_byte(tmp1, Address(ary1, 0));
7196   andl(tmp1, 0x00000080);
7197   jccb(Assembler::notEqual, TRUE_LABEL);
7198   jmpb(FALSE_LABEL);
7199 
7200   bind(TRUE_LABEL);
7201   movl(result, 1);   // return true
7202   jmpb(DONE);
7203 
7204   bind(FALSE_LABEL);
7205   xorl(result, result); // return false
7206 
7207   // That's it
7208   bind(DONE);
7209   if (UseAVX >= 2 && UseSSE >= 2) {
7210     // clean upper bits of YMM registers
7211     vpxor(vec1, vec1);
7212     vpxor(vec2, vec2);
7213   }
7214 }
7215 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
7216 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
7217                                    Register limit, Register result, Register chr,
7218                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
7219   ShortBranchVerifier sbv(this);
7220   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
7221 
7222   int length_offset  = arrayOopDesc::length_offset_in_bytes();
7223   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
7224 
7225   if (is_array_equ) {
7226     // Check the input args
7227     cmpoop(ary1, ary2);
7228     jcc(Assembler::equal, TRUE_LABEL);
7229 
7230     // Need additional checks for arrays_equals.
7231     testptr(ary1, ary1);
7232     jcc(Assembler::zero, FALSE_LABEL);
7233     testptr(ary2, ary2);
7234     jcc(Assembler::zero, FALSE_LABEL);
7235 
7236     // Check the lengths
7237     movl(limit, Address(ary1, length_offset));
7238     cmpl(limit, Address(ary2, length_offset));
7239     jcc(Assembler::notEqual, FALSE_LABEL);
7240   }
7241 
7242   // count == 0
7243   testl(limit, limit);
7244   jcc(Assembler::zero, TRUE_LABEL);
7245 
7246   if (is_array_equ) {
7247     // Load array address
7248     lea(ary1, Address(ary1, base_offset));
7249     lea(ary2, Address(ary2, base_offset));
7250   }
7251 
7252   if (is_array_equ && is_char) {
7253     // arrays_equals when used for char[].
7254     shll(limit, 1);      // byte count != 0
7255   }
7256   movl(result, limit); // copy
7257 
7258   if (UseAVX >= 2) {
7259     // With AVX2, use 32-byte vector compare
7260     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7261 
7262     // Compare 32-byte vectors
7263     andl(result, 0x0000001f);  //   tail count (in bytes)
7264     andl(limit, 0xffffffe0);   // vector count (in bytes)
7265     jcc(Assembler::zero, COMPARE_TAIL);
7266 
7267     lea(ary1, Address(ary1, limit, Address::times_1));
7268     lea(ary2, Address(ary2, limit, Address::times_1));
7269     negptr(limit);
7270 
7271     bind(COMPARE_WIDE_VECTORS);
7272 
7273 #ifdef _LP64
7274     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7275       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
7276 
7277       cmpl(limit, -64);
7278       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7279 
7280       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7281 
7282       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
7283       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
7284       kortestql(k7, k7);
7285       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
7286       addptr(limit, 64);  // update since we already compared at this addr
7287       cmpl(limit, -64);
7288       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7289 
7290       // At this point we may still need to compare -limit+result bytes.
7291       // We could execute the next two instruction and just continue via non-wide path:
7292       //  cmpl(limit, 0);
7293       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
7294       // But since we stopped at the points ary{1,2}+limit which are
7295       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
7296       // (|limit| <= 32 and result < 32),
7297       // we may just compare the last 64 bytes.
7298       //
7299       addptr(result, -64);   // it is safe, bc we just came from this area
7300       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
7301       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
7302       kortestql(k7, k7);
7303       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
7304 
7305       jmp(TRUE_LABEL);
7306 
7307       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7308 
7309     }//if (VM_Version::supports_avx512vlbw())
7310 #endif //_LP64
7311 
7312     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
7313     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
7314     vpxor(vec1, vec2);
7315 
7316     vptest(vec1, vec1);
7317     jcc(Assembler::notZero, FALSE_LABEL);
7318     addptr(limit, 32);
7319     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7320 
7321     testl(result, result);
7322     jcc(Assembler::zero, TRUE_LABEL);
7323 
7324     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7325     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
7326     vpxor(vec1, vec2);
7327 
7328     vptest(vec1, vec1);
7329     jccb(Assembler::notZero, FALSE_LABEL);
7330     jmpb(TRUE_LABEL);
7331 
7332     bind(COMPARE_TAIL); // limit is zero
7333     movl(limit, result);
7334     // Fallthru to tail compare
7335   } else if (UseSSE42Intrinsics) {
7336     // With SSE4.2, use double quad vector compare
7337     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7338 
7339     // Compare 16-byte vectors
7340     andl(result, 0x0000000f);  //   tail count (in bytes)
7341     andl(limit, 0xfffffff0);   // vector count (in bytes)
7342     jcc(Assembler::zero, COMPARE_TAIL);
7343 
7344     lea(ary1, Address(ary1, limit, Address::times_1));
7345     lea(ary2, Address(ary2, limit, Address::times_1));
7346     negptr(limit);
7347 
7348     bind(COMPARE_WIDE_VECTORS);
7349     movdqu(vec1, Address(ary1, limit, Address::times_1));
7350     movdqu(vec2, Address(ary2, limit, Address::times_1));
7351     pxor(vec1, vec2);
7352 
7353     ptest(vec1, vec1);
7354     jcc(Assembler::notZero, FALSE_LABEL);
7355     addptr(limit, 16);
7356     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7357 
7358     testl(result, result);
7359     jcc(Assembler::zero, TRUE_LABEL);
7360 
7361     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7362     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
7363     pxor(vec1, vec2);
7364 
7365     ptest(vec1, vec1);
7366     jccb(Assembler::notZero, FALSE_LABEL);
7367     jmpb(TRUE_LABEL);
7368 
7369     bind(COMPARE_TAIL); // limit is zero
7370     movl(limit, result);
7371     // Fallthru to tail compare
7372   }
7373 
7374   // Compare 4-byte vectors
7375   andl(limit, 0xfffffffc); // vector count (in bytes)
7376   jccb(Assembler::zero, COMPARE_CHAR);
7377 
7378   lea(ary1, Address(ary1, limit, Address::times_1));
7379   lea(ary2, Address(ary2, limit, Address::times_1));
7380   negptr(limit);
7381 
7382   bind(COMPARE_VECTORS);
7383   movl(chr, Address(ary1, limit, Address::times_1));
7384   cmpl(chr, Address(ary2, limit, Address::times_1));
7385   jccb(Assembler::notEqual, FALSE_LABEL);
7386   addptr(limit, 4);
7387   jcc(Assembler::notZero, COMPARE_VECTORS);
7388 
7389   // Compare trailing char (final 2 bytes), if any
7390   bind(COMPARE_CHAR);
7391   testl(result, 0x2);   // tail  char
7392   jccb(Assembler::zero, COMPARE_BYTE);
7393   load_unsigned_short(chr, Address(ary1, 0));
7394   load_unsigned_short(limit, Address(ary2, 0));
7395   cmpl(chr, limit);
7396   jccb(Assembler::notEqual, FALSE_LABEL);
7397 
7398   if (is_array_equ && is_char) {
7399     bind(COMPARE_BYTE);
7400   } else {
7401     lea(ary1, Address(ary1, 2));
7402     lea(ary2, Address(ary2, 2));
7403 
7404     bind(COMPARE_BYTE);
7405     testl(result, 0x1);   // tail  byte
7406     jccb(Assembler::zero, TRUE_LABEL);
7407     load_unsigned_byte(chr, Address(ary1, 0));
7408     load_unsigned_byte(limit, Address(ary2, 0));
7409     cmpl(chr, limit);
7410     jccb(Assembler::notEqual, FALSE_LABEL);
7411   }
7412   bind(TRUE_LABEL);
7413   movl(result, 1);   // return true
7414   jmpb(DONE);
7415 
7416   bind(FALSE_LABEL);
7417   xorl(result, result); // return false
7418 
7419   // That's it
7420   bind(DONE);
7421   if (UseAVX >= 2) {
7422     // clean upper bits of YMM registers
7423     vpxor(vec1, vec1);
7424     vpxor(vec2, vec2);
7425   }
7426 }
7427 
7428 #endif
7429 
7430 void MacroAssembler::generate_fill(BasicType t, bool aligned,
7431                                    Register to, Register value, Register count,
7432                                    Register rtmp, XMMRegister xtmp) {
7433   ShortBranchVerifier sbv(this);
7434   assert_different_registers(to, value, count, rtmp);
7435   Label L_exit;
7436   Label L_fill_2_bytes, L_fill_4_bytes;
7437 
7438   int shift = -1;
7439   switch (t) {
7440     case T_BYTE:
7441       shift = 2;
7442       break;
7443     case T_SHORT:
7444       shift = 1;
7445       break;
7446     case T_INT:
7447       shift = 0;
7448       break;
7449     default: ShouldNotReachHere();
7450   }
7451 
7452   if (t == T_BYTE) {
7453     andl(value, 0xff);
7454     movl(rtmp, value);
7455     shll(rtmp, 8);
7456     orl(value, rtmp);
7457   }
7458   if (t == T_SHORT) {
7459     andl(value, 0xffff);
7460   }
7461   if (t == T_BYTE || t == T_SHORT) {
7462     movl(rtmp, value);
7463     shll(rtmp, 16);
7464     orl(value, rtmp);
7465   }
7466 
7467   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
7468   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
7469   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
7470     Label L_skip_align2;
7471     // align source address at 4 bytes address boundary
7472     if (t == T_BYTE) {
7473       Label L_skip_align1;
7474       // One byte misalignment happens only for byte arrays
7475       testptr(to, 1);
7476       jccb(Assembler::zero, L_skip_align1);
7477       movb(Address(to, 0), value);
7478       increment(to);
7479       decrement(count);
7480       BIND(L_skip_align1);
7481     }
7482     // Two bytes misalignment happens only for byte and short (char) arrays
7483     testptr(to, 2);
7484     jccb(Assembler::zero, L_skip_align2);
7485     movw(Address(to, 0), value);
7486     addptr(to, 2);
7487     subl(count, 1<<(shift-1));
7488     BIND(L_skip_align2);
7489   }
7490   if (UseSSE < 2) {
7491     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7492     // Fill 32-byte chunks
7493     subl(count, 8 << shift);
7494     jcc(Assembler::less, L_check_fill_8_bytes);
7495     align(16);
7496 
7497     BIND(L_fill_32_bytes_loop);
7498 
7499     for (int i = 0; i < 32; i += 4) {
7500       movl(Address(to, i), value);
7501     }
7502 
7503     addptr(to, 32);
7504     subl(count, 8 << shift);
7505     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7506     BIND(L_check_fill_8_bytes);
7507     addl(count, 8 << shift);
7508     jccb(Assembler::zero, L_exit);
7509     jmpb(L_fill_8_bytes);
7510 
7511     //
7512     // length is too short, just fill qwords
7513     //
7514     BIND(L_fill_8_bytes_loop);
7515     movl(Address(to, 0), value);
7516     movl(Address(to, 4), value);
7517     addptr(to, 8);
7518     BIND(L_fill_8_bytes);
7519     subl(count, 1 << (shift + 1));
7520     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7521     // fall through to fill 4 bytes
7522   } else {
7523     Label L_fill_32_bytes;
7524     if (!UseUnalignedLoadStores) {
7525       // align to 8 bytes, we know we are 4 byte aligned to start
7526       testptr(to, 4);
7527       jccb(Assembler::zero, L_fill_32_bytes);
7528       movl(Address(to, 0), value);
7529       addptr(to, 4);
7530       subl(count, 1<<shift);
7531     }
7532     BIND(L_fill_32_bytes);
7533     {
7534       assert( UseSSE >= 2, "supported cpu only" );
7535       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7536       movdl(xtmp, value);
7537       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_512bit);
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         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
7548         addptr(to, 64);
7549         subl(count, 16 << shift);
7550         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7551 
7552         BIND(L_check_fill_32_bytes);
7553         addl(count, 8 << shift);
7554         jccb(Assembler::less, L_check_fill_8_bytes);
7555         vmovdqu(Address(to, 0), xtmp);
7556         addptr(to, 32);
7557         subl(count, 8 << shift);
7558 
7559         BIND(L_check_fill_8_bytes);
7560       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
7561         // Fill 64-byte chunks
7562         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7563         vpbroadcastd(xtmp, xtmp, Assembler::AVX_256bit);
7564 
7565         subl(count, 16 << shift);
7566         jcc(Assembler::less, L_check_fill_32_bytes);
7567         align(16);
7568 
7569         BIND(L_fill_64_bytes_loop);
7570         vmovdqu(Address(to, 0), xtmp);
7571         vmovdqu(Address(to, 32), xtmp);
7572         addptr(to, 64);
7573         subl(count, 16 << shift);
7574         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7575 
7576         BIND(L_check_fill_32_bytes);
7577         addl(count, 8 << shift);
7578         jccb(Assembler::less, L_check_fill_8_bytes);
7579         vmovdqu(Address(to, 0), xtmp);
7580         addptr(to, 32);
7581         subl(count, 8 << shift);
7582 
7583         BIND(L_check_fill_8_bytes);
7584         // clean upper bits of YMM registers
7585         movdl(xtmp, value);
7586         pshufd(xtmp, xtmp, 0);
7587       } else {
7588         // Fill 32-byte chunks
7589         pshufd(xtmp, xtmp, 0);
7590 
7591         subl(count, 8 << shift);
7592         jcc(Assembler::less, L_check_fill_8_bytes);
7593         align(16);
7594 
7595         BIND(L_fill_32_bytes_loop);
7596 
7597         if (UseUnalignedLoadStores) {
7598           movdqu(Address(to, 0), xtmp);
7599           movdqu(Address(to, 16), xtmp);
7600         } else {
7601           movq(Address(to, 0), xtmp);
7602           movq(Address(to, 8), xtmp);
7603           movq(Address(to, 16), xtmp);
7604           movq(Address(to, 24), xtmp);
7605         }
7606 
7607         addptr(to, 32);
7608         subl(count, 8 << shift);
7609         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7610 
7611         BIND(L_check_fill_8_bytes);
7612       }
7613       addl(count, 8 << shift);
7614       jccb(Assembler::zero, L_exit);
7615       jmpb(L_fill_8_bytes);
7616 
7617       //
7618       // length is too short, just fill qwords
7619       //
7620       BIND(L_fill_8_bytes_loop);
7621       movq(Address(to, 0), xtmp);
7622       addptr(to, 8);
7623       BIND(L_fill_8_bytes);
7624       subl(count, 1 << (shift + 1));
7625       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7626     }
7627   }
7628   // fill trailing 4 bytes
7629   BIND(L_fill_4_bytes);
7630   testl(count, 1<<shift);
7631   jccb(Assembler::zero, L_fill_2_bytes);
7632   movl(Address(to, 0), value);
7633   if (t == T_BYTE || t == T_SHORT) {
7634     Label L_fill_byte;
7635     addptr(to, 4);
7636     BIND(L_fill_2_bytes);
7637     // fill trailing 2 bytes
7638     testl(count, 1<<(shift-1));
7639     jccb(Assembler::zero, L_fill_byte);
7640     movw(Address(to, 0), value);
7641     if (t == T_BYTE) {
7642       addptr(to, 2);
7643       BIND(L_fill_byte);
7644       // fill trailing byte
7645       testl(count, 1);
7646       jccb(Assembler::zero, L_exit);
7647       movb(Address(to, 0), value);
7648     } else {
7649       BIND(L_fill_byte);
7650     }
7651   } else {
7652     BIND(L_fill_2_bytes);
7653   }
7654   BIND(L_exit);
7655 }
7656 
7657 // encode char[] to byte[] in ISO_8859_1
7658    //@HotSpotIntrinsicCandidate
7659    //private static int implEncodeISOArray(byte[] sa, int sp,
7660    //byte[] da, int dp, int len) {
7661    //  int i = 0;
7662    //  for (; i < len; i++) {
7663    //    char c = StringUTF16.getChar(sa, sp++);
7664    //    if (c > '\u00FF')
7665    //      break;
7666    //    da[dp++] = (byte)c;
7667    //  }
7668    //  return i;
7669    //}
7670 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
7671   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
7672   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
7673   Register tmp5, Register result) {
7674 
7675   // rsi: src
7676   // rdi: dst
7677   // rdx: len
7678   // rcx: tmp5
7679   // rax: result
7680   ShortBranchVerifier sbv(this);
7681   assert_different_registers(src, dst, len, tmp5, result);
7682   Label L_done, L_copy_1_char, L_copy_1_char_exit;
7683 
7684   // set result
7685   xorl(result, result);
7686   // check for zero length
7687   testl(len, len);
7688   jcc(Assembler::zero, L_done);
7689 
7690   movl(result, len);
7691 
7692   // Setup pointers
7693   lea(src, Address(src, len, Address::times_2)); // char[]
7694   lea(dst, Address(dst, len, Address::times_1)); // byte[]
7695   negptr(len);
7696 
7697   if (UseSSE42Intrinsics || UseAVX >= 2) {
7698     Label L_copy_8_chars, L_copy_8_chars_exit;
7699     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
7700 
7701     if (UseAVX >= 2) {
7702       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
7703       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
7704       movdl(tmp1Reg, tmp5);
7705       vpbroadcastd(tmp1Reg, tmp1Reg, Assembler::AVX_256bit);
7706       jmp(L_chars_32_check);
7707 
7708       bind(L_copy_32_chars);
7709       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
7710       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
7711       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
7712       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
7713       jccb(Assembler::notZero, L_copy_32_chars_exit);
7714       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
7715       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
7716       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
7717 
7718       bind(L_chars_32_check);
7719       addptr(len, 32);
7720       jcc(Assembler::lessEqual, L_copy_32_chars);
7721 
7722       bind(L_copy_32_chars_exit);
7723       subptr(len, 16);
7724       jccb(Assembler::greater, L_copy_16_chars_exit);
7725 
7726     } else if (UseSSE42Intrinsics) {
7727       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
7728       movdl(tmp1Reg, tmp5);
7729       pshufd(tmp1Reg, tmp1Reg, 0);
7730       jmpb(L_chars_16_check);
7731     }
7732 
7733     bind(L_copy_16_chars);
7734     if (UseAVX >= 2) {
7735       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
7736       vptest(tmp2Reg, tmp1Reg);
7737       jcc(Assembler::notZero, L_copy_16_chars_exit);
7738       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
7739       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
7740     } else {
7741       if (UseAVX > 0) {
7742         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
7743         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
7744         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
7745       } else {
7746         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
7747         por(tmp2Reg, tmp3Reg);
7748         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
7749         por(tmp2Reg, tmp4Reg);
7750       }
7751       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
7752       jccb(Assembler::notZero, L_copy_16_chars_exit);
7753       packuswb(tmp3Reg, tmp4Reg);
7754     }
7755     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
7756 
7757     bind(L_chars_16_check);
7758     addptr(len, 16);
7759     jcc(Assembler::lessEqual, L_copy_16_chars);
7760 
7761     bind(L_copy_16_chars_exit);
7762     if (UseAVX >= 2) {
7763       // clean upper bits of YMM registers
7764       vpxor(tmp2Reg, tmp2Reg);
7765       vpxor(tmp3Reg, tmp3Reg);
7766       vpxor(tmp4Reg, tmp4Reg);
7767       movdl(tmp1Reg, tmp5);
7768       pshufd(tmp1Reg, tmp1Reg, 0);
7769     }
7770     subptr(len, 8);
7771     jccb(Assembler::greater, L_copy_8_chars_exit);
7772 
7773     bind(L_copy_8_chars);
7774     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
7775     ptest(tmp3Reg, tmp1Reg);
7776     jccb(Assembler::notZero, L_copy_8_chars_exit);
7777     packuswb(tmp3Reg, tmp1Reg);
7778     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
7779     addptr(len, 8);
7780     jccb(Assembler::lessEqual, L_copy_8_chars);
7781 
7782     bind(L_copy_8_chars_exit);
7783     subptr(len, 8);
7784     jccb(Assembler::zero, L_done);
7785   }
7786 
7787   bind(L_copy_1_char);
7788   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
7789   testl(tmp5, 0xff00);      // check if Unicode char
7790   jccb(Assembler::notZero, L_copy_1_char_exit);
7791   movb(Address(dst, len, Address::times_1, 0), tmp5);
7792   addptr(len, 1);
7793   jccb(Assembler::less, L_copy_1_char);
7794 
7795   bind(L_copy_1_char_exit);
7796   addptr(result, len); // len is negative count of not processed elements
7797 
7798   bind(L_done);
7799 }
7800 
7801 #ifdef _LP64
7802 /**
7803  * Helper for multiply_to_len().
7804  */
7805 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
7806   addq(dest_lo, src1);
7807   adcq(dest_hi, 0);
7808   addq(dest_lo, src2);
7809   adcq(dest_hi, 0);
7810 }
7811 
7812 /**
7813  * Multiply 64 bit by 64 bit first loop.
7814  */
7815 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
7816                                            Register y, Register y_idx, Register z,
7817                                            Register carry, Register product,
7818                                            Register idx, Register kdx) {
7819   //
7820   //  jlong carry, x[], y[], z[];
7821   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
7822   //    huge_128 product = y[idx] * x[xstart] + carry;
7823   //    z[kdx] = (jlong)product;
7824   //    carry  = (jlong)(product >>> 64);
7825   //  }
7826   //  z[xstart] = carry;
7827   //
7828 
7829   Label L_first_loop, L_first_loop_exit;
7830   Label L_one_x, L_one_y, L_multiply;
7831 
7832   decrementl(xstart);
7833   jcc(Assembler::negative, L_one_x);
7834 
7835   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
7836   rorq(x_xstart, 32); // convert big-endian to little-endian
7837 
7838   bind(L_first_loop);
7839   decrementl(idx);
7840   jcc(Assembler::negative, L_first_loop_exit);
7841   decrementl(idx);
7842   jcc(Assembler::negative, L_one_y);
7843   movq(y_idx, Address(y, idx, Address::times_4,  0));
7844   rorq(y_idx, 32); // convert big-endian to little-endian
7845   bind(L_multiply);
7846   movq(product, x_xstart);
7847   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
7848   addq(product, carry);
7849   adcq(rdx, 0);
7850   subl(kdx, 2);
7851   movl(Address(z, kdx, Address::times_4,  4), product);
7852   shrq(product, 32);
7853   movl(Address(z, kdx, Address::times_4,  0), product);
7854   movq(carry, rdx);
7855   jmp(L_first_loop);
7856 
7857   bind(L_one_y);
7858   movl(y_idx, Address(y,  0));
7859   jmp(L_multiply);
7860 
7861   bind(L_one_x);
7862   movl(x_xstart, Address(x,  0));
7863   jmp(L_first_loop);
7864 
7865   bind(L_first_loop_exit);
7866 }
7867 
7868 /**
7869  * Multiply 64 bit by 64 bit and add 128 bit.
7870  */
7871 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
7872                                             Register yz_idx, Register idx,
7873                                             Register carry, Register product, int offset) {
7874   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
7875   //     z[kdx] = (jlong)product;
7876 
7877   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
7878   rorq(yz_idx, 32); // convert big-endian to little-endian
7879   movq(product, x_xstart);
7880   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
7881   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
7882   rorq(yz_idx, 32); // convert big-endian to little-endian
7883 
7884   add2_with_carry(rdx, product, carry, yz_idx);
7885 
7886   movl(Address(z, idx, Address::times_4,  offset+4), product);
7887   shrq(product, 32);
7888   movl(Address(z, idx, Address::times_4,  offset), product);
7889 
7890 }
7891 
7892 /**
7893  * Multiply 128 bit by 128 bit. Unrolled inner loop.
7894  */
7895 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
7896                                              Register yz_idx, Register idx, Register jdx,
7897                                              Register carry, Register product,
7898                                              Register carry2) {
7899   //   jlong carry, x[], y[], z[];
7900   //   int kdx = ystart+1;
7901   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
7902   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
7903   //     z[kdx+idx+1] = (jlong)product;
7904   //     jlong carry2  = (jlong)(product >>> 64);
7905   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
7906   //     z[kdx+idx] = (jlong)product;
7907   //     carry  = (jlong)(product >>> 64);
7908   //   }
7909   //   idx += 2;
7910   //   if (idx > 0) {
7911   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
7912   //     z[kdx+idx] = (jlong)product;
7913   //     carry  = (jlong)(product >>> 64);
7914   //   }
7915   //
7916 
7917   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
7918 
7919   movl(jdx, idx);
7920   andl(jdx, 0xFFFFFFFC);
7921   shrl(jdx, 2);
7922 
7923   bind(L_third_loop);
7924   subl(jdx, 1);
7925   jcc(Assembler::negative, L_third_loop_exit);
7926   subl(idx, 4);
7927 
7928   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
7929   movq(carry2, rdx);
7930 
7931   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
7932   movq(carry, rdx);
7933   jmp(L_third_loop);
7934 
7935   bind (L_third_loop_exit);
7936 
7937   andl (idx, 0x3);
7938   jcc(Assembler::zero, L_post_third_loop_done);
7939 
7940   Label L_check_1;
7941   subl(idx, 2);
7942   jcc(Assembler::negative, L_check_1);
7943 
7944   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
7945   movq(carry, rdx);
7946 
7947   bind (L_check_1);
7948   addl (idx, 0x2);
7949   andl (idx, 0x1);
7950   subl(idx, 1);
7951   jcc(Assembler::negative, L_post_third_loop_done);
7952 
7953   movl(yz_idx, Address(y, idx, Address::times_4,  0));
7954   movq(product, x_xstart);
7955   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
7956   movl(yz_idx, Address(z, idx, Address::times_4,  0));
7957 
7958   add2_with_carry(rdx, product, yz_idx, carry);
7959 
7960   movl(Address(z, idx, Address::times_4,  0), product);
7961   shrq(product, 32);
7962 
7963   shlq(rdx, 32);
7964   orq(product, rdx);
7965   movq(carry, product);
7966 
7967   bind(L_post_third_loop_done);
7968 }
7969 
7970 /**
7971  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
7972  *
7973  */
7974 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
7975                                                   Register carry, Register carry2,
7976                                                   Register idx, Register jdx,
7977                                                   Register yz_idx1, Register yz_idx2,
7978                                                   Register tmp, Register tmp3, Register tmp4) {
7979   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
7980 
7981   //   jlong carry, x[], y[], z[];
7982   //   int kdx = ystart+1;
7983   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
7984   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
7985   //     jlong carry2  = (jlong)(tmp3 >>> 64);
7986   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
7987   //     carry  = (jlong)(tmp4 >>> 64);
7988   //     z[kdx+idx+1] = (jlong)tmp3;
7989   //     z[kdx+idx] = (jlong)tmp4;
7990   //   }
7991   //   idx += 2;
7992   //   if (idx > 0) {
7993   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
7994   //     z[kdx+idx] = (jlong)yz_idx1;
7995   //     carry  = (jlong)(yz_idx1 >>> 64);
7996   //   }
7997   //
7998 
7999   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8000 
8001   movl(jdx, idx);
8002   andl(jdx, 0xFFFFFFFC);
8003   shrl(jdx, 2);
8004 
8005   bind(L_third_loop);
8006   subl(jdx, 1);
8007   jcc(Assembler::negative, L_third_loop_exit);
8008   subl(idx, 4);
8009 
8010   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8011   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8012   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8013   rorxq(yz_idx2, yz_idx2, 32);
8014 
8015   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8016   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8017 
8018   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8019   rorxq(yz_idx1, yz_idx1, 32);
8020   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8021   rorxq(yz_idx2, yz_idx2, 32);
8022 
8023   if (VM_Version::supports_adx()) {
8024     adcxq(tmp3, carry);
8025     adoxq(tmp3, yz_idx1);
8026 
8027     adcxq(tmp4, tmp);
8028     adoxq(tmp4, yz_idx2);
8029 
8030     movl(carry, 0); // does not affect flags
8031     adcxq(carry2, carry);
8032     adoxq(carry2, carry);
8033   } else {
8034     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8035     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8036   }
8037   movq(carry, carry2);
8038 
8039   movl(Address(z, idx, Address::times_4, 12), tmp3);
8040   shrq(tmp3, 32);
8041   movl(Address(z, idx, Address::times_4,  8), tmp3);
8042 
8043   movl(Address(z, idx, Address::times_4,  4), tmp4);
8044   shrq(tmp4, 32);
8045   movl(Address(z, idx, Address::times_4,  0), tmp4);
8046 
8047   jmp(L_third_loop);
8048 
8049   bind (L_third_loop_exit);
8050 
8051   andl (idx, 0x3);
8052   jcc(Assembler::zero, L_post_third_loop_done);
8053 
8054   Label L_check_1;
8055   subl(idx, 2);
8056   jcc(Assembler::negative, L_check_1);
8057 
8058   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8059   rorxq(yz_idx1, yz_idx1, 32);
8060   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8061   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8062   rorxq(yz_idx2, yz_idx2, 32);
8063 
8064   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8065 
8066   movl(Address(z, idx, Address::times_4,  4), tmp3);
8067   shrq(tmp3, 32);
8068   movl(Address(z, idx, Address::times_4,  0), tmp3);
8069   movq(carry, tmp4);
8070 
8071   bind (L_check_1);
8072   addl (idx, 0x2);
8073   andl (idx, 0x1);
8074   subl(idx, 1);
8075   jcc(Assembler::negative, L_post_third_loop_done);
8076   movl(tmp4, Address(y, idx, Address::times_4,  0));
8077   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8078   movl(tmp4, Address(z, idx, Address::times_4,  0));
8079 
8080   add2_with_carry(carry2, tmp3, tmp4, carry);
8081 
8082   movl(Address(z, idx, Address::times_4,  0), tmp3);
8083   shrq(tmp3, 32);
8084 
8085   shlq(carry2, 32);
8086   orq(tmp3, carry2);
8087   movq(carry, tmp3);
8088 
8089   bind(L_post_third_loop_done);
8090 }
8091 
8092 /**
8093  * Code for BigInteger::multiplyToLen() instrinsic.
8094  *
8095  * rdi: x
8096  * rax: xlen
8097  * rsi: y
8098  * rcx: ylen
8099  * r8:  z
8100  * r11: zlen
8101  * r12: tmp1
8102  * r13: tmp2
8103  * r14: tmp3
8104  * r15: tmp4
8105  * rbx: tmp5
8106  *
8107  */
8108 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8109                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8110   ShortBranchVerifier sbv(this);
8111   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8112 
8113   push(tmp1);
8114   push(tmp2);
8115   push(tmp3);
8116   push(tmp4);
8117   push(tmp5);
8118 
8119   push(xlen);
8120   push(zlen);
8121 
8122   const Register idx = tmp1;
8123   const Register kdx = tmp2;
8124   const Register xstart = tmp3;
8125 
8126   const Register y_idx = tmp4;
8127   const Register carry = tmp5;
8128   const Register product  = xlen;
8129   const Register x_xstart = zlen;  // reuse register
8130 
8131   // First Loop.
8132   //
8133   //  final static long LONG_MASK = 0xffffffffL;
8134   //  int xstart = xlen - 1;
8135   //  int ystart = ylen - 1;
8136   //  long carry = 0;
8137   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8138   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8139   //    z[kdx] = (int)product;
8140   //    carry = product >>> 32;
8141   //  }
8142   //  z[xstart] = (int)carry;
8143   //
8144 
8145   movl(idx, ylen);      // idx = ylen;
8146   movl(kdx, zlen);      // kdx = xlen+ylen;
8147   xorq(carry, carry);   // carry = 0;
8148 
8149   Label L_done;
8150 
8151   movl(xstart, xlen);
8152   decrementl(xstart);
8153   jcc(Assembler::negative, L_done);
8154 
8155   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8156 
8157   Label L_second_loop;
8158   testl(kdx, kdx);
8159   jcc(Assembler::zero, L_second_loop);
8160 
8161   Label L_carry;
8162   subl(kdx, 1);
8163   jcc(Assembler::zero, L_carry);
8164 
8165   movl(Address(z, kdx, Address::times_4,  0), carry);
8166   shrq(carry, 32);
8167   subl(kdx, 1);
8168 
8169   bind(L_carry);
8170   movl(Address(z, kdx, Address::times_4,  0), carry);
8171 
8172   // Second and third (nested) loops.
8173   //
8174   // for (int i = xstart-1; i >= 0; i--) { // Second loop
8175   //   carry = 0;
8176   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
8177   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
8178   //                    (z[k] & LONG_MASK) + carry;
8179   //     z[k] = (int)product;
8180   //     carry = product >>> 32;
8181   //   }
8182   //   z[i] = (int)carry;
8183   // }
8184   //
8185   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
8186 
8187   const Register jdx = tmp1;
8188 
8189   bind(L_second_loop);
8190   xorl(carry, carry);    // carry = 0;
8191   movl(jdx, ylen);       // j = ystart+1
8192 
8193   subl(xstart, 1);       // i = xstart-1;
8194   jcc(Assembler::negative, L_done);
8195 
8196   push (z);
8197 
8198   Label L_last_x;
8199   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
8200   subl(xstart, 1);       // i = xstart-1;
8201   jcc(Assembler::negative, L_last_x);
8202 
8203   if (UseBMI2Instructions) {
8204     movq(rdx,  Address(x, xstart, Address::times_4,  0));
8205     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
8206   } else {
8207     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8208     rorq(x_xstart, 32);  // convert big-endian to little-endian
8209   }
8210 
8211   Label L_third_loop_prologue;
8212   bind(L_third_loop_prologue);
8213 
8214   push (x);
8215   push (xstart);
8216   push (ylen);
8217 
8218 
8219   if (UseBMI2Instructions) {
8220     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
8221   } else { // !UseBMI2Instructions
8222     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
8223   }
8224 
8225   pop(ylen);
8226   pop(xlen);
8227   pop(x);
8228   pop(z);
8229 
8230   movl(tmp3, xlen);
8231   addl(tmp3, 1);
8232   movl(Address(z, tmp3, Address::times_4,  0), carry);
8233   subl(tmp3, 1);
8234   jccb(Assembler::negative, L_done);
8235 
8236   shrq(carry, 32);
8237   movl(Address(z, tmp3, Address::times_4,  0), carry);
8238   jmp(L_second_loop);
8239 
8240   // Next infrequent code is moved outside loops.
8241   bind(L_last_x);
8242   if (UseBMI2Instructions) {
8243     movl(rdx, Address(x,  0));
8244   } else {
8245     movl(x_xstart, Address(x,  0));
8246   }
8247   jmp(L_third_loop_prologue);
8248 
8249   bind(L_done);
8250 
8251   pop(zlen);
8252   pop(xlen);
8253 
8254   pop(tmp5);
8255   pop(tmp4);
8256   pop(tmp3);
8257   pop(tmp2);
8258   pop(tmp1);
8259 }
8260 
8261 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
8262   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
8263   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
8264   Label VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
8265   Label VECTOR8_TAIL, VECTOR4_TAIL;
8266   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
8267   Label SAME_TILL_END, DONE;
8268   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
8269 
8270   //scale is in rcx in both Win64 and Unix
8271   ShortBranchVerifier sbv(this);
8272 
8273   shlq(length);
8274   xorq(result, result);
8275 
8276   if ((UseAVX > 2) &&
8277       VM_Version::supports_avx512vlbw()) {
8278     Label VECTOR64_LOOP, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
8279 
8280     cmpq(length, 64);
8281     jcc(Assembler::less, VECTOR32_TAIL);
8282     movq(tmp1, length);
8283     andq(tmp1, 0x3F);      // tail count
8284     andq(length, ~(0x3F)); //vector count
8285 
8286     bind(VECTOR64_LOOP);
8287     // AVX512 code to compare 64 byte vectors.
8288     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
8289     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
8290     kortestql(k7, k7);
8291     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
8292     addq(result, 64);
8293     subq(length, 64);
8294     jccb(Assembler::notZero, VECTOR64_LOOP);
8295 
8296     //bind(VECTOR64_TAIL);
8297     testq(tmp1, tmp1);
8298     jcc(Assembler::zero, SAME_TILL_END);
8299 
8300     //bind(VECTOR64_TAIL);
8301     // AVX512 code to compare upto 63 byte vectors.
8302     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
8303     shlxq(tmp2, tmp2, tmp1);
8304     notq(tmp2);
8305     kmovql(k3, tmp2);
8306 
8307     evmovdqub(rymm0, k3, Address(obja, result), Assembler::AVX_512bit);
8308     evpcmpeqb(k7, k3, rymm0, Address(objb, result), Assembler::AVX_512bit);
8309 
8310     ktestql(k7, k3);
8311     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
8312 
8313     bind(VECTOR64_NOT_EQUAL);
8314     kmovql(tmp1, k7);
8315     notq(tmp1);
8316     tzcntq(tmp1, tmp1);
8317     addq(result, tmp1);
8318     shrq(result);
8319     jmp(DONE);
8320     bind(VECTOR32_TAIL);
8321   }
8322 
8323   cmpq(length, 8);
8324   jcc(Assembler::equal, VECTOR8_LOOP);
8325   jcc(Assembler::less, VECTOR4_TAIL);
8326 
8327   if (UseAVX >= 2) {
8328     Label VECTOR16_TAIL, VECTOR32_LOOP;
8329 
8330     cmpq(length, 16);
8331     jcc(Assembler::equal, VECTOR16_LOOP);
8332     jcc(Assembler::less, VECTOR8_LOOP);
8333 
8334     cmpq(length, 32);
8335     jccb(Assembler::less, VECTOR16_TAIL);
8336 
8337     subq(length, 32);
8338     bind(VECTOR32_LOOP);
8339     vmovdqu(rymm0, Address(obja, result));
8340     vmovdqu(rymm1, Address(objb, result));
8341     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
8342     vptest(rymm2, rymm2);
8343     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
8344     addq(result, 32);
8345     subq(length, 32);
8346     jcc(Assembler::greaterEqual, VECTOR32_LOOP);
8347     addq(length, 32);
8348     jcc(Assembler::equal, SAME_TILL_END);
8349     //falling through if less than 32 bytes left //close the branch here.
8350 
8351     bind(VECTOR16_TAIL);
8352     cmpq(length, 16);
8353     jccb(Assembler::less, VECTOR8_TAIL);
8354     bind(VECTOR16_LOOP);
8355     movdqu(rymm0, Address(obja, result));
8356     movdqu(rymm1, Address(objb, result));
8357     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
8358     ptest(rymm2, rymm2);
8359     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8360     addq(result, 16);
8361     subq(length, 16);
8362     jcc(Assembler::equal, SAME_TILL_END);
8363     //falling through if less than 16 bytes left
8364   } else {//regular intrinsics
8365 
8366     cmpq(length, 16);
8367     jccb(Assembler::less, VECTOR8_TAIL);
8368 
8369     subq(length, 16);
8370     bind(VECTOR16_LOOP);
8371     movdqu(rymm0, Address(obja, result));
8372     movdqu(rymm1, Address(objb, result));
8373     pxor(rymm0, rymm1);
8374     ptest(rymm0, rymm0);
8375     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8376     addq(result, 16);
8377     subq(length, 16);
8378     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
8379     addq(length, 16);
8380     jcc(Assembler::equal, SAME_TILL_END);
8381     //falling through if less than 16 bytes left
8382   }
8383 
8384   bind(VECTOR8_TAIL);
8385   cmpq(length, 8);
8386   jccb(Assembler::less, VECTOR4_TAIL);
8387   bind(VECTOR8_LOOP);
8388   movq(tmp1, Address(obja, result));
8389   movq(tmp2, Address(objb, result));
8390   xorq(tmp1, tmp2);
8391   testq(tmp1, tmp1);
8392   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
8393   addq(result, 8);
8394   subq(length, 8);
8395   jcc(Assembler::equal, SAME_TILL_END);
8396   //falling through if less than 8 bytes left
8397 
8398   bind(VECTOR4_TAIL);
8399   cmpq(length, 4);
8400   jccb(Assembler::less, BYTES_TAIL);
8401   bind(VECTOR4_LOOP);
8402   movl(tmp1, Address(obja, result));
8403   xorl(tmp1, Address(objb, result));
8404   testl(tmp1, tmp1);
8405   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
8406   addq(result, 4);
8407   subq(length, 4);
8408   jcc(Assembler::equal, SAME_TILL_END);
8409   //falling through if less than 4 bytes left
8410 
8411   bind(BYTES_TAIL);
8412   bind(BYTES_LOOP);
8413   load_unsigned_byte(tmp1, Address(obja, result));
8414   load_unsigned_byte(tmp2, Address(objb, result));
8415   xorl(tmp1, tmp2);
8416   testl(tmp1, tmp1);
8417   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8418   decq(length);
8419   jcc(Assembler::zero, SAME_TILL_END);
8420   incq(result);
8421   load_unsigned_byte(tmp1, Address(obja, result));
8422   load_unsigned_byte(tmp2, Address(objb, result));
8423   xorl(tmp1, tmp2);
8424   testl(tmp1, tmp1);
8425   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8426   decq(length);
8427   jcc(Assembler::zero, SAME_TILL_END);
8428   incq(result);
8429   load_unsigned_byte(tmp1, Address(obja, result));
8430   load_unsigned_byte(tmp2, Address(objb, result));
8431   xorl(tmp1, tmp2);
8432   testl(tmp1, tmp1);
8433   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8434   jmp(SAME_TILL_END);
8435 
8436   if (UseAVX >= 2) {
8437     bind(VECTOR32_NOT_EQUAL);
8438     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
8439     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
8440     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
8441     vpmovmskb(tmp1, rymm0);
8442     bsfq(tmp1, tmp1);
8443     addq(result, tmp1);
8444     shrq(result);
8445     jmp(DONE);
8446   }
8447 
8448   bind(VECTOR16_NOT_EQUAL);
8449   if (UseAVX >= 2) {
8450     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
8451     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
8452     pxor(rymm0, rymm2);
8453   } else {
8454     pcmpeqb(rymm2, rymm2);
8455     pxor(rymm0, rymm1);
8456     pcmpeqb(rymm0, rymm1);
8457     pxor(rymm0, rymm2);
8458   }
8459   pmovmskb(tmp1, rymm0);
8460   bsfq(tmp1, tmp1);
8461   addq(result, tmp1);
8462   shrq(result);
8463   jmpb(DONE);
8464 
8465   bind(VECTOR8_NOT_EQUAL);
8466   bind(VECTOR4_NOT_EQUAL);
8467   bsfq(tmp1, tmp1);
8468   shrq(tmp1, 3);
8469   addq(result, tmp1);
8470   bind(BYTES_NOT_EQUAL);
8471   shrq(result);
8472   jmpb(DONE);
8473 
8474   bind(SAME_TILL_END);
8475   mov64(result, -1);
8476 
8477   bind(DONE);
8478 }
8479 
8480 //Helper functions for square_to_len()
8481 
8482 /**
8483  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
8484  * Preserves x and z and modifies rest of the registers.
8485  */
8486 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8487   // Perform square and right shift by 1
8488   // Handle odd xlen case first, then for even xlen do the following
8489   // jlong carry = 0;
8490   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
8491   //     huge_128 product = x[j:j+1] * x[j:j+1];
8492   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
8493   //     z[i+2:i+3] = (jlong)(product >>> 1);
8494   //     carry = (jlong)product;
8495   // }
8496 
8497   xorq(tmp5, tmp5);     // carry
8498   xorq(rdxReg, rdxReg);
8499   xorl(tmp1, tmp1);     // index for x
8500   xorl(tmp4, tmp4);     // index for z
8501 
8502   Label L_first_loop, L_first_loop_exit;
8503 
8504   testl(xlen, 1);
8505   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
8506 
8507   // Square and right shift by 1 the odd element using 32 bit multiply
8508   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
8509   imulq(raxReg, raxReg);
8510   shrq(raxReg, 1);
8511   adcq(tmp5, 0);
8512   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
8513   incrementl(tmp1);
8514   addl(tmp4, 2);
8515 
8516   // Square and  right shift by 1 the rest using 64 bit multiply
8517   bind(L_first_loop);
8518   cmpptr(tmp1, xlen);
8519   jccb(Assembler::equal, L_first_loop_exit);
8520 
8521   // Square
8522   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
8523   rorq(raxReg, 32);    // convert big-endian to little-endian
8524   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
8525 
8526   // Right shift by 1 and save carry
8527   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
8528   rcrq(rdxReg, 1);
8529   rcrq(raxReg, 1);
8530   adcq(tmp5, 0);
8531 
8532   // Store result in z
8533   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
8534   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
8535 
8536   // Update indices for x and z
8537   addl(tmp1, 2);
8538   addl(tmp4, 4);
8539   jmp(L_first_loop);
8540 
8541   bind(L_first_loop_exit);
8542 }
8543 
8544 
8545 /**
8546  * Perform the following multiply add operation using BMI2 instructions
8547  * carry:sum = sum + op1*op2 + carry
8548  * op2 should be in rdx
8549  * op2 is preserved, all other registers are modified
8550  */
8551 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
8552   // assert op2 is rdx
8553   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
8554   addq(sum, carry);
8555   adcq(tmp2, 0);
8556   addq(sum, op1);
8557   adcq(tmp2, 0);
8558   movq(carry, tmp2);
8559 }
8560 
8561 /**
8562  * Perform the following multiply add operation:
8563  * carry:sum = sum + op1*op2 + carry
8564  * Preserves op1, op2 and modifies rest of registers
8565  */
8566 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
8567   // rdx:rax = op1 * op2
8568   movq(raxReg, op2);
8569   mulq(op1);
8570 
8571   //  rdx:rax = sum + carry + rdx:rax
8572   addq(sum, carry);
8573   adcq(rdxReg, 0);
8574   addq(sum, raxReg);
8575   adcq(rdxReg, 0);
8576 
8577   // carry:sum = rdx:sum
8578   movq(carry, rdxReg);
8579 }
8580 
8581 /**
8582  * Add 64 bit long carry into z[] with carry propogation.
8583  * Preserves z and carry register values and modifies rest of registers.
8584  *
8585  */
8586 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
8587   Label L_fourth_loop, L_fourth_loop_exit;
8588 
8589   movl(tmp1, 1);
8590   subl(zlen, 2);
8591   addq(Address(z, zlen, Address::times_4, 0), carry);
8592 
8593   bind(L_fourth_loop);
8594   jccb(Assembler::carryClear, L_fourth_loop_exit);
8595   subl(zlen, 2);
8596   jccb(Assembler::negative, L_fourth_loop_exit);
8597   addq(Address(z, zlen, Address::times_4, 0), tmp1);
8598   jmp(L_fourth_loop);
8599   bind(L_fourth_loop_exit);
8600 }
8601 
8602 /**
8603  * Shift z[] left by 1 bit.
8604  * Preserves x, len, z and zlen registers and modifies rest of the registers.
8605  *
8606  */
8607 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
8608 
8609   Label L_fifth_loop, L_fifth_loop_exit;
8610 
8611   // Fifth loop
8612   // Perform primitiveLeftShift(z, zlen, 1)
8613 
8614   const Register prev_carry = tmp1;
8615   const Register new_carry = tmp4;
8616   const Register value = tmp2;
8617   const Register zidx = tmp3;
8618 
8619   // int zidx, carry;
8620   // long value;
8621   // carry = 0;
8622   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
8623   //    (carry:value)  = (z[i] << 1) | carry ;
8624   //    z[i] = value;
8625   // }
8626 
8627   movl(zidx, zlen);
8628   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
8629 
8630   bind(L_fifth_loop);
8631   decl(zidx);  // Use decl to preserve carry flag
8632   decl(zidx);
8633   jccb(Assembler::negative, L_fifth_loop_exit);
8634 
8635   if (UseBMI2Instructions) {
8636      movq(value, Address(z, zidx, Address::times_4, 0));
8637      rclq(value, 1);
8638      rorxq(value, value, 32);
8639      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8640   }
8641   else {
8642     // clear new_carry
8643     xorl(new_carry, new_carry);
8644 
8645     // Shift z[i] by 1, or in previous carry and save new carry
8646     movq(value, Address(z, zidx, Address::times_4, 0));
8647     shlq(value, 1);
8648     adcl(new_carry, 0);
8649 
8650     orq(value, prev_carry);
8651     rorq(value, 0x20);
8652     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8653 
8654     // Set previous carry = new carry
8655     movl(prev_carry, new_carry);
8656   }
8657   jmp(L_fifth_loop);
8658 
8659   bind(L_fifth_loop_exit);
8660 }
8661 
8662 
8663 /**
8664  * Code for BigInteger::squareToLen() intrinsic
8665  *
8666  * rdi: x
8667  * rsi: len
8668  * r8:  z
8669  * rcx: zlen
8670  * r12: tmp1
8671  * r13: tmp2
8672  * r14: tmp3
8673  * r15: tmp4
8674  * rbx: tmp5
8675  *
8676  */
8677 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) {
8678 
8679   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, L_last_x, L_multiply;
8680   push(tmp1);
8681   push(tmp2);
8682   push(tmp3);
8683   push(tmp4);
8684   push(tmp5);
8685 
8686   // First loop
8687   // Store the squares, right shifted one bit (i.e., divided by 2).
8688   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
8689 
8690   // Add in off-diagonal sums.
8691   //
8692   // Second, third (nested) and fourth loops.
8693   // zlen +=2;
8694   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
8695   //    carry = 0;
8696   //    long op2 = x[xidx:xidx+1];
8697   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
8698   //       k -= 2;
8699   //       long op1 = x[j:j+1];
8700   //       long sum = z[k:k+1];
8701   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
8702   //       z[k:k+1] = sum;
8703   //    }
8704   //    add_one_64(z, k, carry, tmp_regs);
8705   // }
8706 
8707   const Register carry = tmp5;
8708   const Register sum = tmp3;
8709   const Register op1 = tmp4;
8710   Register op2 = tmp2;
8711 
8712   push(zlen);
8713   push(len);
8714   addl(zlen,2);
8715   bind(L_second_loop);
8716   xorq(carry, carry);
8717   subl(zlen, 4);
8718   subl(len, 2);
8719   push(zlen);
8720   push(len);
8721   cmpl(len, 0);
8722   jccb(Assembler::lessEqual, L_second_loop_exit);
8723 
8724   // Multiply an array by one 64 bit long.
8725   if (UseBMI2Instructions) {
8726     op2 = rdxReg;
8727     movq(op2, Address(x, len, Address::times_4,  0));
8728     rorxq(op2, op2, 32);
8729   }
8730   else {
8731     movq(op2, Address(x, len, Address::times_4,  0));
8732     rorq(op2, 32);
8733   }
8734 
8735   bind(L_third_loop);
8736   decrementl(len);
8737   jccb(Assembler::negative, L_third_loop_exit);
8738   decrementl(len);
8739   jccb(Assembler::negative, L_last_x);
8740 
8741   movq(op1, Address(x, len, Address::times_4,  0));
8742   rorq(op1, 32);
8743 
8744   bind(L_multiply);
8745   subl(zlen, 2);
8746   movq(sum, Address(z, zlen, Address::times_4,  0));
8747 
8748   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
8749   if (UseBMI2Instructions) {
8750     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
8751   }
8752   else {
8753     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8754   }
8755 
8756   movq(Address(z, zlen, Address::times_4, 0), sum);
8757 
8758   jmp(L_third_loop);
8759   bind(L_third_loop_exit);
8760 
8761   // Fourth loop
8762   // Add 64 bit long carry into z with carry propogation.
8763   // Uses offsetted zlen.
8764   add_one_64(z, zlen, carry, tmp1);
8765 
8766   pop(len);
8767   pop(zlen);
8768   jmp(L_second_loop);
8769 
8770   // Next infrequent code is moved outside loops.
8771   bind(L_last_x);
8772   movl(op1, Address(x, 0));
8773   jmp(L_multiply);
8774 
8775   bind(L_second_loop_exit);
8776   pop(len);
8777   pop(zlen);
8778   pop(len);
8779   pop(zlen);
8780 
8781   // Fifth loop
8782   // Shift z left 1 bit.
8783   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
8784 
8785   // z[zlen-1] |= x[len-1] & 1;
8786   movl(tmp3, Address(x, len, Address::times_4, -4));
8787   andl(tmp3, 1);
8788   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
8789 
8790   pop(tmp5);
8791   pop(tmp4);
8792   pop(tmp3);
8793   pop(tmp2);
8794   pop(tmp1);
8795 }
8796 
8797 /**
8798  * Helper function for mul_add()
8799  * Multiply the in[] by int k and add to out[] starting at offset offs using
8800  * 128 bit by 32 bit multiply and return the carry in tmp5.
8801  * Only quad int aligned length of in[] is operated on in this function.
8802  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
8803  * This function preserves out, in and k registers.
8804  * len and offset point to the appropriate index in "in" & "out" correspondingly
8805  * tmp5 has the carry.
8806  * other registers are temporary and are modified.
8807  *
8808  */
8809 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
8810   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
8811   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8812 
8813   Label L_first_loop, L_first_loop_exit;
8814 
8815   movl(tmp1, len);
8816   shrl(tmp1, 2);
8817 
8818   bind(L_first_loop);
8819   subl(tmp1, 1);
8820   jccb(Assembler::negative, L_first_loop_exit);
8821 
8822   subl(len, 4);
8823   subl(offset, 4);
8824 
8825   Register op2 = tmp2;
8826   const Register sum = tmp3;
8827   const Register op1 = tmp4;
8828   const Register carry = tmp5;
8829 
8830   if (UseBMI2Instructions) {
8831     op2 = rdxReg;
8832   }
8833 
8834   movq(op1, Address(in, len, Address::times_4,  8));
8835   rorq(op1, 32);
8836   movq(sum, Address(out, offset, Address::times_4,  8));
8837   rorq(sum, 32);
8838   if (UseBMI2Instructions) {
8839     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8840   }
8841   else {
8842     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8843   }
8844   // Store back in big endian from little endian
8845   rorq(sum, 0x20);
8846   movq(Address(out, offset, Address::times_4,  8), sum);
8847 
8848   movq(op1, Address(in, len, Address::times_4,  0));
8849   rorq(op1, 32);
8850   movq(sum, Address(out, offset, Address::times_4,  0));
8851   rorq(sum, 32);
8852   if (UseBMI2Instructions) {
8853     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8854   }
8855   else {
8856     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8857   }
8858   // Store back in big endian from little endian
8859   rorq(sum, 0x20);
8860   movq(Address(out, offset, Address::times_4,  0), sum);
8861 
8862   jmp(L_first_loop);
8863   bind(L_first_loop_exit);
8864 }
8865 
8866 /**
8867  * Code for BigInteger::mulAdd() intrinsic
8868  *
8869  * rdi: out
8870  * rsi: in
8871  * r11: offs (out.length - offset)
8872  * rcx: len
8873  * r8:  k
8874  * r12: tmp1
8875  * r13: tmp2
8876  * r14: tmp3
8877  * r15: tmp4
8878  * rbx: tmp5
8879  * Multiply the in[] by word k and add to out[], return the carry in rax
8880  */
8881 void MacroAssembler::mul_add(Register out, Register in, Register offs,
8882    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
8883    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8884 
8885   Label L_carry, L_last_in, L_done;
8886 
8887 // carry = 0;
8888 // for (int j=len-1; j >= 0; j--) {
8889 //    long product = (in[j] & LONG_MASK) * kLong +
8890 //                   (out[offs] & LONG_MASK) + carry;
8891 //    out[offs--] = (int)product;
8892 //    carry = product >>> 32;
8893 // }
8894 //
8895   push(tmp1);
8896   push(tmp2);
8897   push(tmp3);
8898   push(tmp4);
8899   push(tmp5);
8900 
8901   Register op2 = tmp2;
8902   const Register sum = tmp3;
8903   const Register op1 = tmp4;
8904   const Register carry =  tmp5;
8905 
8906   if (UseBMI2Instructions) {
8907     op2 = rdxReg;
8908     movl(op2, k);
8909   }
8910   else {
8911     movl(op2, k);
8912   }
8913 
8914   xorq(carry, carry);
8915 
8916   //First loop
8917 
8918   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
8919   //The carry is in tmp5
8920   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
8921 
8922   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
8923   decrementl(len);
8924   jccb(Assembler::negative, L_carry);
8925   decrementl(len);
8926   jccb(Assembler::negative, L_last_in);
8927 
8928   movq(op1, Address(in, len, Address::times_4,  0));
8929   rorq(op1, 32);
8930 
8931   subl(offs, 2);
8932   movq(sum, Address(out, offs, Address::times_4,  0));
8933   rorq(sum, 32);
8934 
8935   if (UseBMI2Instructions) {
8936     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8937   }
8938   else {
8939     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8940   }
8941 
8942   // Store back in big endian from little endian
8943   rorq(sum, 0x20);
8944   movq(Address(out, offs, Address::times_4,  0), sum);
8945 
8946   testl(len, len);
8947   jccb(Assembler::zero, L_carry);
8948 
8949   //Multiply the last in[] entry, if any
8950   bind(L_last_in);
8951   movl(op1, Address(in, 0));
8952   movl(sum, Address(out, offs, Address::times_4,  -4));
8953 
8954   movl(raxReg, k);
8955   mull(op1); //tmp4 * eax -> edx:eax
8956   addl(sum, carry);
8957   adcl(rdxReg, 0);
8958   addl(sum, raxReg);
8959   adcl(rdxReg, 0);
8960   movl(carry, rdxReg);
8961 
8962   movl(Address(out, offs, Address::times_4,  -4), sum);
8963 
8964   bind(L_carry);
8965   //return tmp5/carry as carry in rax
8966   movl(rax, carry);
8967 
8968   bind(L_done);
8969   pop(tmp5);
8970   pop(tmp4);
8971   pop(tmp3);
8972   pop(tmp2);
8973   pop(tmp1);
8974 }
8975 #endif
8976 
8977 /**
8978  * Emits code to update CRC-32 with a byte value according to constants in table
8979  *
8980  * @param [in,out]crc   Register containing the crc.
8981  * @param [in]val       Register containing the byte to fold into the CRC.
8982  * @param [in]table     Register containing the table of crc constants.
8983  *
8984  * uint32_t crc;
8985  * val = crc_table[(val ^ crc) & 0xFF];
8986  * crc = val ^ (crc >> 8);
8987  *
8988  */
8989 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
8990   xorl(val, crc);
8991   andl(val, 0xFF);
8992   shrl(crc, 8); // unsigned shift
8993   xorl(crc, Address(table, val, Address::times_4, 0));
8994 }
8995 
8996 /**
8997 * Fold four 128-bit data chunks
8998 */
8999 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9000   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9001   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9002   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9003   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9004 }
9005 
9006 /**
9007  * Fold 128-bit data chunk
9008  */
9009 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9010   if (UseAVX > 0) {
9011     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9012     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9013     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9014     pxor(xcrc, xtmp);
9015   } else {
9016     movdqa(xtmp, xcrc);
9017     pclmulhdq(xtmp, xK);   // [123:64]
9018     pclmulldq(xcrc, xK);   // [63:0]
9019     pxor(xcrc, xtmp);
9020     movdqu(xtmp, Address(buf, offset));
9021     pxor(xcrc, xtmp);
9022   }
9023 }
9024 
9025 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9026   if (UseAVX > 0) {
9027     vpclmulhdq(xtmp, xK, xcrc);
9028     vpclmulldq(xcrc, xK, xcrc);
9029     pxor(xcrc, xbuf);
9030     pxor(xcrc, xtmp);
9031   } else {
9032     movdqa(xtmp, xcrc);
9033     pclmulhdq(xtmp, xK);
9034     pclmulldq(xcrc, xK);
9035     pxor(xcrc, xbuf);
9036     pxor(xcrc, xtmp);
9037   }
9038 }
9039 
9040 /**
9041  * 8-bit folds to compute 32-bit CRC
9042  *
9043  * uint64_t xcrc;
9044  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9045  */
9046 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9047   movdl(tmp, xcrc);
9048   andl(tmp, 0xFF);
9049   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9050   psrldq(xcrc, 1); // unsigned shift one byte
9051   pxor(xcrc, xtmp);
9052 }
9053 
9054 /**
9055  * uint32_t crc;
9056  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9057  */
9058 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9059   movl(tmp, crc);
9060   andl(tmp, 0xFF);
9061   shrl(crc, 8);
9062   xorl(crc, Address(table, tmp, Address::times_4, 0));
9063 }
9064 
9065 /**
9066  * @param crc   register containing existing CRC (32-bit)
9067  * @param buf   register pointing to input byte buffer (byte*)
9068  * @param len   register containing number of bytes
9069  * @param table register that will contain address of CRC table
9070  * @param tmp   scratch register
9071  */
9072 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9073   assert_different_registers(crc, buf, len, table, tmp, rax);
9074 
9075   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9076   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9077 
9078   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9079   // context for the registers used, where all instructions below are using 128-bit mode
9080   // On EVEX without VL and BW, these instructions will all be AVX.
9081   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9082   notl(crc); // ~crc
9083   cmpl(len, 16);
9084   jcc(Assembler::less, L_tail);
9085 
9086   // Align buffer to 16 bytes
9087   movl(tmp, buf);
9088   andl(tmp, 0xF);
9089   jccb(Assembler::zero, L_aligned);
9090   subl(tmp,  16);
9091   addl(len, tmp);
9092 
9093   align(4);
9094   BIND(L_align_loop);
9095   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9096   update_byte_crc32(crc, rax, table);
9097   increment(buf);
9098   incrementl(tmp);
9099   jccb(Assembler::less, L_align_loop);
9100 
9101   BIND(L_aligned);
9102   movl(tmp, len); // save
9103   shrl(len, 4);
9104   jcc(Assembler::zero, L_tail_restore);
9105 
9106   // Fold total 512 bits of polynomial on each iteration
9107   if (VM_Version::supports_vpclmulqdq()) {
9108     Label Parallel_loop, L_No_Parallel;
9109 
9110     cmpl(len, 8);
9111     jccb(Assembler::less, L_No_Parallel);
9112 
9113     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9114     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9115     movdl(xmm5, crc);
9116     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9117     addptr(buf, 64);
9118     subl(len, 7);
9119     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9120 
9121     BIND(Parallel_loop);
9122     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9123     addptr(buf, 64);
9124     subl(len, 4);
9125     jcc(Assembler::greater, Parallel_loop);
9126 
9127     vextracti64x2(xmm2, xmm1, 0x01);
9128     vextracti64x2(xmm3, xmm1, 0x02);
9129     vextracti64x2(xmm4, xmm1, 0x03);
9130     jmp(L_fold_512b);
9131 
9132     BIND(L_No_Parallel);
9133   }
9134   // Fold crc into first bytes of vector
9135   movdqa(xmm1, Address(buf, 0));
9136   movdl(rax, xmm1);
9137   xorl(crc, rax);
9138   if (VM_Version::supports_sse4_1()) {
9139     pinsrd(xmm1, crc, 0);
9140   } else {
9141     pinsrw(xmm1, crc, 0);
9142     shrl(crc, 16);
9143     pinsrw(xmm1, crc, 1);
9144   }
9145   addptr(buf, 16);
9146   subl(len, 4); // len > 0
9147   jcc(Assembler::less, L_fold_tail);
9148 
9149   movdqa(xmm2, Address(buf,  0));
9150   movdqa(xmm3, Address(buf, 16));
9151   movdqa(xmm4, Address(buf, 32));
9152   addptr(buf, 48);
9153   subl(len, 3);
9154   jcc(Assembler::lessEqual, L_fold_512b);
9155 
9156   // Fold total 512 bits of polynomial on each iteration,
9157   // 128 bits per each of 4 parallel streams.
9158   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9159 
9160   align(32);
9161   BIND(L_fold_512b_loop);
9162   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9163   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9164   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9165   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9166   addptr(buf, 64);
9167   subl(len, 4);
9168   jcc(Assembler::greater, L_fold_512b_loop);
9169 
9170   // Fold 512 bits to 128 bits.
9171   BIND(L_fold_512b);
9172   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9173   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
9174   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
9175   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
9176 
9177   // Fold the rest of 128 bits data chunks
9178   BIND(L_fold_tail);
9179   addl(len, 3);
9180   jccb(Assembler::lessEqual, L_fold_128b);
9181   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9182 
9183   BIND(L_fold_tail_loop);
9184   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9185   addptr(buf, 16);
9186   decrementl(len);
9187   jccb(Assembler::greater, L_fold_tail_loop);
9188 
9189   // Fold 128 bits in xmm1 down into 32 bits in crc register.
9190   BIND(L_fold_128b);
9191   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
9192   if (UseAVX > 0) {
9193     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
9194     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
9195     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
9196   } else {
9197     movdqa(xmm2, xmm0);
9198     pclmulqdq(xmm2, xmm1, 0x1);
9199     movdqa(xmm3, xmm0);
9200     pand(xmm3, xmm2);
9201     pclmulqdq(xmm0, xmm3, 0x1);
9202   }
9203   psrldq(xmm1, 8);
9204   psrldq(xmm2, 4);
9205   pxor(xmm0, xmm1);
9206   pxor(xmm0, xmm2);
9207 
9208   // 8 8-bit folds to compute 32-bit CRC.
9209   for (int j = 0; j < 4; j++) {
9210     fold_8bit_crc32(xmm0, table, xmm1, rax);
9211   }
9212   movdl(crc, xmm0); // mov 32 bits to general register
9213   for (int j = 0; j < 4; j++) {
9214     fold_8bit_crc32(crc, table, rax);
9215   }
9216 
9217   BIND(L_tail_restore);
9218   movl(len, tmp); // restore
9219   BIND(L_tail);
9220   andl(len, 0xf);
9221   jccb(Assembler::zero, L_exit);
9222 
9223   // Fold the rest of bytes
9224   align(4);
9225   BIND(L_tail_loop);
9226   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9227   update_byte_crc32(crc, rax, table);
9228   increment(buf);
9229   decrementl(len);
9230   jccb(Assembler::greater, L_tail_loop);
9231 
9232   BIND(L_exit);
9233   notl(crc); // ~c
9234 }
9235 
9236 #ifdef _LP64
9237 // S. Gueron / Information Processing Letters 112 (2012) 184
9238 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
9239 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
9240 // Output: the 64-bit carry-less product of B * CONST
9241 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
9242                                      Register tmp1, Register tmp2, Register tmp3) {
9243   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9244   if (n > 0) {
9245     addq(tmp3, n * 256 * 8);
9246   }
9247   //    Q1 = TABLEExt[n][B & 0xFF];
9248   movl(tmp1, in);
9249   andl(tmp1, 0x000000FF);
9250   shll(tmp1, 3);
9251   addq(tmp1, tmp3);
9252   movq(tmp1, Address(tmp1, 0));
9253 
9254   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9255   movl(tmp2, in);
9256   shrl(tmp2, 8);
9257   andl(tmp2, 0x000000FF);
9258   shll(tmp2, 3);
9259   addq(tmp2, tmp3);
9260   movq(tmp2, Address(tmp2, 0));
9261 
9262   shlq(tmp2, 8);
9263   xorq(tmp1, tmp2);
9264 
9265   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9266   movl(tmp2, in);
9267   shrl(tmp2, 16);
9268   andl(tmp2, 0x000000FF);
9269   shll(tmp2, 3);
9270   addq(tmp2, tmp3);
9271   movq(tmp2, Address(tmp2, 0));
9272 
9273   shlq(tmp2, 16);
9274   xorq(tmp1, tmp2);
9275 
9276   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9277   shrl(in, 24);
9278   andl(in, 0x000000FF);
9279   shll(in, 3);
9280   addq(in, tmp3);
9281   movq(in, Address(in, 0));
9282 
9283   shlq(in, 24);
9284   xorq(in, tmp1);
9285   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9286 }
9287 
9288 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9289                                       Register in_out,
9290                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9291                                       XMMRegister w_xtmp2,
9292                                       Register tmp1,
9293                                       Register n_tmp2, Register n_tmp3) {
9294   if (is_pclmulqdq_supported) {
9295     movdl(w_xtmp1, in_out); // modified blindly
9296 
9297     movl(tmp1, const_or_pre_comp_const_index);
9298     movdl(w_xtmp2, tmp1);
9299     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9300 
9301     movdq(in_out, w_xtmp1);
9302   } else {
9303     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
9304   }
9305 }
9306 
9307 // Recombination Alternative 2: No bit-reflections
9308 // T1 = (CRC_A * U1) << 1
9309 // T2 = (CRC_B * U2) << 1
9310 // C1 = T1 >> 32
9311 // C2 = T2 >> 32
9312 // T1 = T1 & 0xFFFFFFFF
9313 // T2 = T2 & 0xFFFFFFFF
9314 // T1 = CRC32(0, T1)
9315 // T2 = CRC32(0, T2)
9316 // C1 = C1 ^ T1
9317 // C2 = C2 ^ T2
9318 // CRC = C1 ^ C2 ^ CRC_C
9319 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,
9320                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9321                                      Register tmp1, Register tmp2,
9322                                      Register n_tmp3) {
9323   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9324   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9325   shlq(in_out, 1);
9326   movl(tmp1, in_out);
9327   shrq(in_out, 32);
9328   xorl(tmp2, tmp2);
9329   crc32(tmp2, tmp1, 4);
9330   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
9331   shlq(in1, 1);
9332   movl(tmp1, in1);
9333   shrq(in1, 32);
9334   xorl(tmp2, tmp2);
9335   crc32(tmp2, tmp1, 4);
9336   xorl(in1, tmp2);
9337   xorl(in_out, in1);
9338   xorl(in_out, in2);
9339 }
9340 
9341 // Set N to predefined value
9342 // Subtract from a lenght of a buffer
9343 // execute in a loop:
9344 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
9345 // for i = 1 to N do
9346 //  CRC_A = CRC32(CRC_A, A[i])
9347 //  CRC_B = CRC32(CRC_B, B[i])
9348 //  CRC_C = CRC32(CRC_C, C[i])
9349 // end for
9350 // Recombine
9351 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,
9352                                        Register in_out1, Register in_out2, Register in_out3,
9353                                        Register tmp1, Register tmp2, Register tmp3,
9354                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9355                                        Register tmp4, Register tmp5,
9356                                        Register n_tmp6) {
9357   Label L_processPartitions;
9358   Label L_processPartition;
9359   Label L_exit;
9360 
9361   bind(L_processPartitions);
9362   cmpl(in_out1, 3 * size);
9363   jcc(Assembler::less, L_exit);
9364     xorl(tmp1, tmp1);
9365     xorl(tmp2, tmp2);
9366     movq(tmp3, in_out2);
9367     addq(tmp3, size);
9368 
9369     bind(L_processPartition);
9370       crc32(in_out3, Address(in_out2, 0), 8);
9371       crc32(tmp1, Address(in_out2, size), 8);
9372       crc32(tmp2, Address(in_out2, size * 2), 8);
9373       addq(in_out2, 8);
9374       cmpq(in_out2, tmp3);
9375       jcc(Assembler::less, L_processPartition);
9376     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9377             w_xtmp1, w_xtmp2, w_xtmp3,
9378             tmp4, tmp5,
9379             n_tmp6);
9380     addq(in_out2, 2 * size);
9381     subl(in_out1, 3 * size);
9382     jmp(L_processPartitions);
9383 
9384   bind(L_exit);
9385 }
9386 #else
9387 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
9388                                      Register tmp1, Register tmp2, Register tmp3,
9389                                      XMMRegister xtmp1, XMMRegister xtmp2) {
9390   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9391   if (n > 0) {
9392     addl(tmp3, n * 256 * 8);
9393   }
9394   //    Q1 = TABLEExt[n][B & 0xFF];
9395   movl(tmp1, in_out);
9396   andl(tmp1, 0x000000FF);
9397   shll(tmp1, 3);
9398   addl(tmp1, tmp3);
9399   movq(xtmp1, Address(tmp1, 0));
9400 
9401   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9402   movl(tmp2, in_out);
9403   shrl(tmp2, 8);
9404   andl(tmp2, 0x000000FF);
9405   shll(tmp2, 3);
9406   addl(tmp2, tmp3);
9407   movq(xtmp2, Address(tmp2, 0));
9408 
9409   psllq(xtmp2, 8);
9410   pxor(xtmp1, xtmp2);
9411 
9412   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9413   movl(tmp2, in_out);
9414   shrl(tmp2, 16);
9415   andl(tmp2, 0x000000FF);
9416   shll(tmp2, 3);
9417   addl(tmp2, tmp3);
9418   movq(xtmp2, Address(tmp2, 0));
9419 
9420   psllq(xtmp2, 16);
9421   pxor(xtmp1, xtmp2);
9422 
9423   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9424   shrl(in_out, 24);
9425   andl(in_out, 0x000000FF);
9426   shll(in_out, 3);
9427   addl(in_out, tmp3);
9428   movq(xtmp2, Address(in_out, 0));
9429 
9430   psllq(xtmp2, 24);
9431   pxor(xtmp1, xtmp2); // Result in CXMM
9432   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9433 }
9434 
9435 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9436                                       Register in_out,
9437                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9438                                       XMMRegister w_xtmp2,
9439                                       Register tmp1,
9440                                       Register n_tmp2, Register n_tmp3) {
9441   if (is_pclmulqdq_supported) {
9442     movdl(w_xtmp1, in_out);
9443 
9444     movl(tmp1, const_or_pre_comp_const_index);
9445     movdl(w_xtmp2, tmp1);
9446     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9447     // Keep result in XMM since GPR is 32 bit in length
9448   } else {
9449     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
9450   }
9451 }
9452 
9453 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,
9454                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9455                                      Register tmp1, Register tmp2,
9456                                      Register n_tmp3) {
9457   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9458   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9459 
9460   psllq(w_xtmp1, 1);
9461   movdl(tmp1, w_xtmp1);
9462   psrlq(w_xtmp1, 32);
9463   movdl(in_out, w_xtmp1);
9464 
9465   xorl(tmp2, tmp2);
9466   crc32(tmp2, tmp1, 4);
9467   xorl(in_out, tmp2);
9468 
9469   psllq(w_xtmp2, 1);
9470   movdl(tmp1, w_xtmp2);
9471   psrlq(w_xtmp2, 32);
9472   movdl(in1, w_xtmp2);
9473 
9474   xorl(tmp2, tmp2);
9475   crc32(tmp2, tmp1, 4);
9476   xorl(in1, tmp2);
9477   xorl(in_out, in1);
9478   xorl(in_out, in2);
9479 }
9480 
9481 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,
9482                                        Register in_out1, Register in_out2, Register in_out3,
9483                                        Register tmp1, Register tmp2, Register tmp3,
9484                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9485                                        Register tmp4, Register tmp5,
9486                                        Register n_tmp6) {
9487   Label L_processPartitions;
9488   Label L_processPartition;
9489   Label L_exit;
9490 
9491   bind(L_processPartitions);
9492   cmpl(in_out1, 3 * size);
9493   jcc(Assembler::less, L_exit);
9494     xorl(tmp1, tmp1);
9495     xorl(tmp2, tmp2);
9496     movl(tmp3, in_out2);
9497     addl(tmp3, size);
9498 
9499     bind(L_processPartition);
9500       crc32(in_out3, Address(in_out2, 0), 4);
9501       crc32(tmp1, Address(in_out2, size), 4);
9502       crc32(tmp2, Address(in_out2, size*2), 4);
9503       crc32(in_out3, Address(in_out2, 0+4), 4);
9504       crc32(tmp1, Address(in_out2, size+4), 4);
9505       crc32(tmp2, Address(in_out2, size*2+4), 4);
9506       addl(in_out2, 8);
9507       cmpl(in_out2, tmp3);
9508       jcc(Assembler::less, L_processPartition);
9509 
9510         push(tmp3);
9511         push(in_out1);
9512         push(in_out2);
9513         tmp4 = tmp3;
9514         tmp5 = in_out1;
9515         n_tmp6 = in_out2;
9516 
9517       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9518             w_xtmp1, w_xtmp2, w_xtmp3,
9519             tmp4, tmp5,
9520             n_tmp6);
9521 
9522         pop(in_out2);
9523         pop(in_out1);
9524         pop(tmp3);
9525 
9526     addl(in_out2, 2 * size);
9527     subl(in_out1, 3 * size);
9528     jmp(L_processPartitions);
9529 
9530   bind(L_exit);
9531 }
9532 #endif //LP64
9533 
9534 #ifdef _LP64
9535 // Algorithm 2: Pipelined usage of the CRC32 instruction.
9536 // Input: A buffer I of L bytes.
9537 // Output: the CRC32C value of the buffer.
9538 // Notations:
9539 // Write L = 24N + r, with N = floor (L/24).
9540 // r = L mod 24 (0 <= r < 24).
9541 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
9542 // N quadwords, and R consists of r bytes.
9543 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
9544 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
9545 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
9546 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
9547 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9548                                           Register tmp1, Register tmp2, Register tmp3,
9549                                           Register tmp4, Register tmp5, Register tmp6,
9550                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9551                                           bool is_pclmulqdq_supported) {
9552   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9553   Label L_wordByWord;
9554   Label L_byteByByteProlog;
9555   Label L_byteByByte;
9556   Label L_exit;
9557 
9558   if (is_pclmulqdq_supported ) {
9559     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9560     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
9561 
9562     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9563     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9564 
9565     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9566     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9567     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
9568   } else {
9569     const_or_pre_comp_const_index[0] = 1;
9570     const_or_pre_comp_const_index[1] = 0;
9571 
9572     const_or_pre_comp_const_index[2] = 3;
9573     const_or_pre_comp_const_index[3] = 2;
9574 
9575     const_or_pre_comp_const_index[4] = 5;
9576     const_or_pre_comp_const_index[5] = 4;
9577    }
9578   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9579                     in2, in1, in_out,
9580                     tmp1, tmp2, tmp3,
9581                     w_xtmp1, w_xtmp2, w_xtmp3,
9582                     tmp4, tmp5,
9583                     tmp6);
9584   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9585                     in2, in1, in_out,
9586                     tmp1, tmp2, tmp3,
9587                     w_xtmp1, w_xtmp2, w_xtmp3,
9588                     tmp4, tmp5,
9589                     tmp6);
9590   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9591                     in2, in1, in_out,
9592                     tmp1, tmp2, tmp3,
9593                     w_xtmp1, w_xtmp2, w_xtmp3,
9594                     tmp4, tmp5,
9595                     tmp6);
9596   movl(tmp1, in2);
9597   andl(tmp1, 0x00000007);
9598   negl(tmp1);
9599   addl(tmp1, in2);
9600   addq(tmp1, in1);
9601 
9602   BIND(L_wordByWord);
9603   cmpq(in1, tmp1);
9604   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9605     crc32(in_out, Address(in1, 0), 4);
9606     addq(in1, 4);
9607     jmp(L_wordByWord);
9608 
9609   BIND(L_byteByByteProlog);
9610   andl(in2, 0x00000007);
9611   movl(tmp2, 1);
9612 
9613   BIND(L_byteByByte);
9614   cmpl(tmp2, in2);
9615   jccb(Assembler::greater, L_exit);
9616     crc32(in_out, Address(in1, 0), 1);
9617     incq(in1);
9618     incl(tmp2);
9619     jmp(L_byteByByte);
9620 
9621   BIND(L_exit);
9622 }
9623 #else
9624 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9625                                           Register tmp1, Register  tmp2, Register tmp3,
9626                                           Register tmp4, Register  tmp5, Register tmp6,
9627                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9628                                           bool is_pclmulqdq_supported) {
9629   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9630   Label L_wordByWord;
9631   Label L_byteByByteProlog;
9632   Label L_byteByByte;
9633   Label L_exit;
9634 
9635   if (is_pclmulqdq_supported) {
9636     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9637     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
9638 
9639     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9640     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9641 
9642     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9643     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9644   } else {
9645     const_or_pre_comp_const_index[0] = 1;
9646     const_or_pre_comp_const_index[1] = 0;
9647 
9648     const_or_pre_comp_const_index[2] = 3;
9649     const_or_pre_comp_const_index[3] = 2;
9650 
9651     const_or_pre_comp_const_index[4] = 5;
9652     const_or_pre_comp_const_index[5] = 4;
9653   }
9654   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9655                     in2, in1, in_out,
9656                     tmp1, tmp2, tmp3,
9657                     w_xtmp1, w_xtmp2, w_xtmp3,
9658                     tmp4, tmp5,
9659                     tmp6);
9660   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9661                     in2, in1, in_out,
9662                     tmp1, tmp2, tmp3,
9663                     w_xtmp1, w_xtmp2, w_xtmp3,
9664                     tmp4, tmp5,
9665                     tmp6);
9666   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9667                     in2, in1, in_out,
9668                     tmp1, tmp2, tmp3,
9669                     w_xtmp1, w_xtmp2, w_xtmp3,
9670                     tmp4, tmp5,
9671                     tmp6);
9672   movl(tmp1, in2);
9673   andl(tmp1, 0x00000007);
9674   negl(tmp1);
9675   addl(tmp1, in2);
9676   addl(tmp1, in1);
9677 
9678   BIND(L_wordByWord);
9679   cmpl(in1, tmp1);
9680   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9681     crc32(in_out, Address(in1,0), 4);
9682     addl(in1, 4);
9683     jmp(L_wordByWord);
9684 
9685   BIND(L_byteByByteProlog);
9686   andl(in2, 0x00000007);
9687   movl(tmp2, 1);
9688 
9689   BIND(L_byteByByte);
9690   cmpl(tmp2, in2);
9691   jccb(Assembler::greater, L_exit);
9692     movb(tmp1, Address(in1, 0));
9693     crc32(in_out, tmp1, 1);
9694     incl(in1);
9695     incl(tmp2);
9696     jmp(L_byteByByte);
9697 
9698   BIND(L_exit);
9699 }
9700 #endif // LP64
9701 #undef BIND
9702 #undef BLOCK_COMMENT
9703 
9704 // Compress char[] array to byte[].
9705 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
9706 //   @HotSpotIntrinsicCandidate
9707 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
9708 //     for (int i = 0; i < len; i++) {
9709 //       int c = src[srcOff++];
9710 //       if (c >>> 8 != 0) {
9711 //         return 0;
9712 //       }
9713 //       dst[dstOff++] = (byte)c;
9714 //     }
9715 //     return len;
9716 //   }
9717 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
9718   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
9719   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
9720   Register tmp5, Register result) {
9721   Label copy_chars_loop, return_length, return_zero, done;
9722 
9723   // rsi: src
9724   // rdi: dst
9725   // rdx: len
9726   // rcx: tmp5
9727   // rax: result
9728 
9729   // rsi holds start addr of source char[] to be compressed
9730   // rdi holds start addr of destination byte[]
9731   // rdx holds length
9732 
9733   assert(len != result, "");
9734 
9735   // save length for return
9736   push(len);
9737 
9738   if ((UseAVX > 2) && // AVX512
9739     VM_Version::supports_avx512vlbw() &&
9740     VM_Version::supports_bmi2()) {
9741 
9742     Label copy_32_loop, copy_loop_tail, below_threshold;
9743 
9744     // alignment
9745     Label post_alignment;
9746 
9747     // if length of the string is less than 16, handle it in an old fashioned way
9748     testl(len, -32);
9749     jcc(Assembler::zero, below_threshold);
9750 
9751     // First check whether a character is compressable ( <= 0xFF).
9752     // Create mask to test for Unicode chars inside zmm vector
9753     movl(result, 0x00FF);
9754     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
9755 
9756     testl(len, -64);
9757     jcc(Assembler::zero, post_alignment);
9758 
9759     movl(tmp5, dst);
9760     andl(tmp5, (32 - 1));
9761     negl(tmp5);
9762     andl(tmp5, (32 - 1));
9763 
9764     // bail out when there is nothing to be done
9765     testl(tmp5, 0xFFFFFFFF);
9766     jcc(Assembler::zero, post_alignment);
9767 
9768     // ~(~0 << len), where len is the # of remaining elements to process
9769     movl(result, 0xFFFFFFFF);
9770     shlxl(result, result, tmp5);
9771     notl(result);
9772     kmovdl(k3, result);
9773 
9774     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
9775     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
9776     ktestd(k2, k3);
9777     jcc(Assembler::carryClear, return_zero);
9778 
9779     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
9780 
9781     addptr(src, tmp5);
9782     addptr(src, tmp5);
9783     addptr(dst, tmp5);
9784     subl(len, tmp5);
9785 
9786     bind(post_alignment);
9787     // end of alignment
9788 
9789     movl(tmp5, len);
9790     andl(tmp5, (32 - 1));    // tail count (in chars)
9791     andl(len, ~(32 - 1));    // vector count (in chars)
9792     jcc(Assembler::zero, copy_loop_tail);
9793 
9794     lea(src, Address(src, len, Address::times_2));
9795     lea(dst, Address(dst, len, Address::times_1));
9796     negptr(len);
9797 
9798     bind(copy_32_loop);
9799     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
9800     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
9801     kortestdl(k2, k2);
9802     jcc(Assembler::carryClear, return_zero);
9803 
9804     // All elements in current processed chunk are valid candidates for
9805     // compression. Write a truncated byte elements to the memory.
9806     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
9807     addptr(len, 32);
9808     jcc(Assembler::notZero, copy_32_loop);
9809 
9810     bind(copy_loop_tail);
9811     // bail out when there is nothing to be done
9812     testl(tmp5, 0xFFFFFFFF);
9813     jcc(Assembler::zero, return_length);
9814 
9815     movl(len, tmp5);
9816 
9817     // ~(~0 << len), where len is the # of remaining elements to process
9818     movl(result, 0xFFFFFFFF);
9819     shlxl(result, result, len);
9820     notl(result);
9821 
9822     kmovdl(k3, result);
9823 
9824     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
9825     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
9826     ktestd(k2, k3);
9827     jcc(Assembler::carryClear, return_zero);
9828 
9829     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
9830     jmp(return_length);
9831 
9832     bind(below_threshold);
9833   }
9834 
9835   if (UseSSE42Intrinsics) {
9836     Label copy_32_loop, copy_16, copy_tail;
9837 
9838     movl(result, len);
9839 
9840     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
9841 
9842     // vectored compression
9843     andl(len, 0xfffffff0);    // vector count (in chars)
9844     andl(result, 0x0000000f);    // tail count (in chars)
9845     testl(len, len);
9846     jcc(Assembler::zero, copy_16);
9847 
9848     // compress 16 chars per iter
9849     movdl(tmp1Reg, tmp5);
9850     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
9851     pxor(tmp4Reg, tmp4Reg);
9852 
9853     lea(src, Address(src, len, Address::times_2));
9854     lea(dst, Address(dst, len, Address::times_1));
9855     negptr(len);
9856 
9857     bind(copy_32_loop);
9858     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
9859     por(tmp4Reg, tmp2Reg);
9860     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
9861     por(tmp4Reg, tmp3Reg);
9862     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
9863     jcc(Assembler::notZero, return_zero);
9864     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
9865     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
9866     addptr(len, 16);
9867     jcc(Assembler::notZero, copy_32_loop);
9868 
9869     // compress next vector of 8 chars (if any)
9870     bind(copy_16);
9871     movl(len, result);
9872     andl(len, 0xfffffff8);    // vector count (in chars)
9873     andl(result, 0x00000007);    // tail count (in chars)
9874     testl(len, len);
9875     jccb(Assembler::zero, copy_tail);
9876 
9877     movdl(tmp1Reg, tmp5);
9878     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
9879     pxor(tmp3Reg, tmp3Reg);
9880 
9881     movdqu(tmp2Reg, Address(src, 0));
9882     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
9883     jccb(Assembler::notZero, return_zero);
9884     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
9885     movq(Address(dst, 0), tmp2Reg);
9886     addptr(src, 16);
9887     addptr(dst, 8);
9888 
9889     bind(copy_tail);
9890     movl(len, result);
9891   }
9892   // compress 1 char per iter
9893   testl(len, len);
9894   jccb(Assembler::zero, return_length);
9895   lea(src, Address(src, len, Address::times_2));
9896   lea(dst, Address(dst, len, Address::times_1));
9897   negptr(len);
9898 
9899   bind(copy_chars_loop);
9900   load_unsigned_short(result, Address(src, len, Address::times_2));
9901   testl(result, 0xff00);      // check if Unicode char
9902   jccb(Assembler::notZero, return_zero);
9903   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
9904   increment(len);
9905   jcc(Assembler::notZero, copy_chars_loop);
9906 
9907   // if compression succeeded, return length
9908   bind(return_length);
9909   pop(result);
9910   jmpb(done);
9911 
9912   // if compression failed, return 0
9913   bind(return_zero);
9914   xorl(result, result);
9915   addptr(rsp, wordSize);
9916 
9917   bind(done);
9918 }
9919 
9920 // Inflate byte[] array to char[].
9921 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
9922 //   @HotSpotIntrinsicCandidate
9923 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
9924 //     for (int i = 0; i < len; i++) {
9925 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
9926 //     }
9927 //   }
9928 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
9929   XMMRegister tmp1, Register tmp2) {
9930   Label copy_chars_loop, done, below_threshold;
9931   // rsi: src
9932   // rdi: dst
9933   // rdx: len
9934   // rcx: tmp2
9935 
9936   // rsi holds start addr of source byte[] to be inflated
9937   // rdi holds start addr of destination char[]
9938   // rdx holds length
9939   assert_different_registers(src, dst, len, tmp2);
9940 
9941   if ((UseAVX > 2) && // AVX512
9942     VM_Version::supports_avx512vlbw() &&
9943     VM_Version::supports_bmi2()) {
9944 
9945     Label copy_32_loop, copy_tail;
9946     Register tmp3_aliased = len;
9947 
9948     // if length of the string is less than 16, handle it in an old fashioned way
9949     testl(len, -16);
9950     jcc(Assembler::zero, below_threshold);
9951 
9952     // In order to use only one arithmetic operation for the main loop we use
9953     // this pre-calculation
9954     movl(tmp2, len);
9955     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
9956     andl(len, -32);     // vector count
9957     jccb(Assembler::zero, copy_tail);
9958 
9959     lea(src, Address(src, len, Address::times_1));
9960     lea(dst, Address(dst, len, Address::times_2));
9961     negptr(len);
9962 
9963 
9964     // inflate 32 chars per iter
9965     bind(copy_32_loop);
9966     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
9967     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
9968     addptr(len, 32);
9969     jcc(Assembler::notZero, copy_32_loop);
9970 
9971     bind(copy_tail);
9972     // bail out when there is nothing to be done
9973     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
9974     jcc(Assembler::zero, done);
9975 
9976     // ~(~0 << length), where length is the # of remaining elements to process
9977     movl(tmp3_aliased, -1);
9978     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
9979     notl(tmp3_aliased);
9980     kmovdl(k2, tmp3_aliased);
9981     evpmovzxbw(tmp1, k2, Address(src, 0), Assembler::AVX_512bit);
9982     evmovdquw(Address(dst, 0), k2, tmp1, Assembler::AVX_512bit);
9983 
9984     jmp(done);
9985   }
9986   if (UseSSE42Intrinsics) {
9987     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
9988 
9989     movl(tmp2, len);
9990 
9991     if (UseAVX > 1) {
9992       andl(tmp2, (16 - 1));
9993       andl(len, -16);
9994       jccb(Assembler::zero, copy_new_tail);
9995     } else {
9996       andl(tmp2, 0x00000007);   // tail count (in chars)
9997       andl(len, 0xfffffff8);    // vector count (in chars)
9998       jccb(Assembler::zero, copy_tail);
9999     }
10000 
10001     // vectored inflation
10002     lea(src, Address(src, len, Address::times_1));
10003     lea(dst, Address(dst, len, Address::times_2));
10004     negptr(len);
10005 
10006     if (UseAVX > 1) {
10007       bind(copy_16_loop);
10008       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10009       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10010       addptr(len, 16);
10011       jcc(Assembler::notZero, copy_16_loop);
10012 
10013       bind(below_threshold);
10014       bind(copy_new_tail);
10015       if ((UseAVX > 2) &&
10016         VM_Version::supports_avx512vlbw() &&
10017         VM_Version::supports_bmi2()) {
10018         movl(tmp2, len);
10019       } else {
10020         movl(len, tmp2);
10021       }
10022       andl(tmp2, 0x00000007);
10023       andl(len, 0xFFFFFFF8);
10024       jccb(Assembler::zero, copy_tail);
10025 
10026       pmovzxbw(tmp1, Address(src, 0));
10027       movdqu(Address(dst, 0), tmp1);
10028       addptr(src, 8);
10029       addptr(dst, 2 * 8);
10030 
10031       jmp(copy_tail, true);
10032     }
10033 
10034     // inflate 8 chars per iter
10035     bind(copy_8_loop);
10036     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10037     movdqu(Address(dst, len, Address::times_2), tmp1);
10038     addptr(len, 8);
10039     jcc(Assembler::notZero, copy_8_loop);
10040 
10041     bind(copy_tail);
10042     movl(len, tmp2);
10043 
10044     cmpl(len, 4);
10045     jccb(Assembler::less, copy_bytes);
10046 
10047     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10048     pmovzxbw(tmp1, tmp1);
10049     movq(Address(dst, 0), tmp1);
10050     subptr(len, 4);
10051     addptr(src, 4);
10052     addptr(dst, 8);
10053 
10054     bind(copy_bytes);
10055   } else {
10056     bind(below_threshold);
10057   }
10058 
10059   testl(len, len);
10060   jccb(Assembler::zero, done);
10061   lea(src, Address(src, len, Address::times_1));
10062   lea(dst, Address(dst, len, Address::times_2));
10063   negptr(len);
10064 
10065   // inflate 1 char per iter
10066   bind(copy_chars_loop);
10067   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10068   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10069   increment(len);
10070   jcc(Assembler::notZero, copy_chars_loop);
10071 
10072   bind(done);
10073 }
10074 
10075 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10076   switch (cond) {
10077     // Note some conditions are synonyms for others
10078     case Assembler::zero:         return Assembler::notZero;
10079     case Assembler::notZero:      return Assembler::zero;
10080     case Assembler::less:         return Assembler::greaterEqual;
10081     case Assembler::lessEqual:    return Assembler::greater;
10082     case Assembler::greater:      return Assembler::lessEqual;
10083     case Assembler::greaterEqual: return Assembler::less;
10084     case Assembler::below:        return Assembler::aboveEqual;
10085     case Assembler::belowEqual:   return Assembler::above;
10086     case Assembler::above:        return Assembler::belowEqual;
10087     case Assembler::aboveEqual:   return Assembler::below;
10088     case Assembler::overflow:     return Assembler::noOverflow;
10089     case Assembler::noOverflow:   return Assembler::overflow;
10090     case Assembler::negative:     return Assembler::positive;
10091     case Assembler::positive:     return Assembler::negative;
10092     case Assembler::parity:       return Assembler::noParity;
10093     case Assembler::noParity:     return Assembler::parity;
10094   }
10095   ShouldNotReachHere(); return Assembler::overflow;
10096 }
10097 
10098 SkipIfEqual::SkipIfEqual(
10099     MacroAssembler* masm, const bool* flag_addr, bool value) {
10100   _masm = masm;
10101   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10102   _masm->jcc(Assembler::equal, _label);
10103 }
10104 
10105 SkipIfEqual::~SkipIfEqual() {
10106   _masm->bind(_label);
10107 }
10108 
10109 // 32-bit Windows has its own fast-path implementation
10110 // of get_thread
10111 #if !defined(WIN32) || defined(_LP64)
10112 
10113 // This is simply a call to Thread::current()
10114 void MacroAssembler::get_thread(Register thread) {
10115   if (thread != rax) {
10116     push(rax);
10117   }
10118   LP64_ONLY(push(rdi);)
10119   LP64_ONLY(push(rsi);)
10120   push(rdx);
10121   push(rcx);
10122 #ifdef _LP64
10123   push(r8);
10124   push(r9);
10125   push(r10);
10126   push(r11);
10127 #endif
10128 
10129   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10130 
10131 #ifdef _LP64
10132   pop(r11);
10133   pop(r10);
10134   pop(r9);
10135   pop(r8);
10136 #endif
10137   pop(rcx);
10138   pop(rdx);
10139   LP64_ONLY(pop(rsi);)
10140   LP64_ONLY(pop(rdi);)
10141   if (thread != rax) {
10142     mov(thread, rax);
10143     pop(rax);
10144   }
10145 }
10146 
10147 #endif