1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/accessDecorators.hpp"
  37 #include "oops/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     decode_klass_not_null(dst);
5111   } else
5112 #endif
5113   {
5114 #ifdef _LP64
5115     shlq(dst, oopDesc::storage_props_nof_bits);
5116     shrq(dst, oopDesc::storage_props_nof_bits);
5117 #else
5118     andl(dst, oopDesc::wide_klass_mask());
5119 #endif
5120   }
5121 }
5122 
5123 void MacroAssembler::load_prototype_header(Register dst, Register src) {
5124   load_klass(dst, src);
5125   movptr(dst, Address(dst, Klass::prototype_header_offset()));
5126 }
5127 
5128 void MacroAssembler::store_klass(Register dst, Register src) {
5129 #ifdef _LP64
5130   if (UseCompressedClassPointers) {
5131     encode_klass_not_null(src);
5132     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5133   } else
5134 #endif
5135     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
5136 }
5137 
5138 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
5139                                     Register tmp1, Register thread_tmp) {
5140   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5141   decorators = AccessInternal::decorator_fixup(decorators);
5142   bool as_raw = (decorators & AS_RAW) != 0;
5143   if (as_raw) {
5144     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5145   } else {
5146     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
5147   }
5148 }
5149 
5150 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
5151                                      Register tmp1, Register tmp2, Register tmp3) {
5152   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5153   decorators = AccessInternal::decorator_fixup(decorators);
5154   bool as_raw = (decorators & AS_RAW) != 0;
5155   if (as_raw) {
5156     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2, tmp3);
5157   } else {
5158     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2, tmp3);
5159   }
5160 }
5161 
5162 void MacroAssembler::resolve(DecoratorSet decorators, Register obj) {
5163   // Use stronger ACCESS_WRITE|ACCESS_READ by default.
5164   if ((decorators & (ACCESS_READ | ACCESS_WRITE)) == 0) {
5165     decorators |= ACCESS_READ | ACCESS_WRITE;
5166   }
5167   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5168   return bs->resolve(this, decorators, obj);
5169 }
5170 
5171 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
5172                                    Register thread_tmp, DecoratorSet decorators) {
5173   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
5174 }
5175 
5176 // Doesn't do verfication, generates fixed size code
5177 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
5178                                             Register thread_tmp, DecoratorSet decorators) {
5179   access_load_at(T_OBJECT, IN_HEAP | IS_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
5180 }
5181 
5182 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
5183                                     Register tmp2, Register tmp3, DecoratorSet decorators) {
5184   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2, tmp3);
5185 }
5186 
5187 // Used for storing NULLs.
5188 void MacroAssembler::store_heap_oop_null(Address dst) {
5189   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg, noreg);
5190 }
5191 
5192 #ifdef _LP64
5193 void MacroAssembler::store_klass_gap(Register dst, Register src) {
5194   if (UseCompressedClassPointers) {
5195     // Store to klass gap in destination
5196     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
5197   }
5198 }
5199 
5200 #ifdef ASSERT
5201 void MacroAssembler::verify_heapbase(const char* msg) {
5202   assert (UseCompressedOops, "should be compressed");
5203   assert (Universe::heap() != NULL, "java heap should be initialized");
5204   if (CheckCompressedOops) {
5205     Label ok;
5206     push(rscratch1); // cmpptr trashes rscratch1
5207     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5208     jcc(Assembler::equal, ok);
5209     STOP(msg);
5210     bind(ok);
5211     pop(rscratch1);
5212   }
5213 }
5214 #endif
5215 
5216 // Algorithm must match oop.inline.hpp encode_heap_oop.
5217 void MacroAssembler::encode_heap_oop(Register r) {
5218 #ifdef ASSERT
5219   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
5220 #endif
5221   verify_oop(r, "broken oop in encode_heap_oop");
5222   if (Universe::narrow_oop_base() == NULL) {
5223     if (Universe::narrow_oop_shift() != 0) {
5224       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5225       shrq(r, LogMinObjAlignmentInBytes);
5226     }
5227     return;
5228   }
5229   testq(r, r);
5230   cmovq(Assembler::equal, r, r12_heapbase);
5231   subq(r, r12_heapbase);
5232   shrq(r, LogMinObjAlignmentInBytes);
5233 }
5234 
5235 void MacroAssembler::encode_heap_oop_not_null(Register r) {
5236 #ifdef ASSERT
5237   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
5238   if (CheckCompressedOops) {
5239     Label ok;
5240     testq(r, r);
5241     jcc(Assembler::notEqual, ok);
5242     STOP("null oop passed to encode_heap_oop_not_null");
5243     bind(ok);
5244   }
5245 #endif
5246   verify_oop(r, "broken oop in encode_heap_oop_not_null");
5247   if (Universe::narrow_oop_base() != NULL) {
5248     subq(r, r12_heapbase);
5249   }
5250   if (Universe::narrow_oop_shift() != 0) {
5251     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5252     shrq(r, LogMinObjAlignmentInBytes);
5253   }
5254 }
5255 
5256 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
5257 #ifdef ASSERT
5258   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
5259   if (CheckCompressedOops) {
5260     Label ok;
5261     testq(src, src);
5262     jcc(Assembler::notEqual, ok);
5263     STOP("null oop passed to encode_heap_oop_not_null2");
5264     bind(ok);
5265   }
5266 #endif
5267   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
5268   if (dst != src) {
5269     movq(dst, src);
5270   }
5271   if (Universe::narrow_oop_base() != NULL) {
5272     subq(dst, r12_heapbase);
5273   }
5274   if (Universe::narrow_oop_shift() != 0) {
5275     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5276     shrq(dst, LogMinObjAlignmentInBytes);
5277   }
5278 }
5279 
5280 void  MacroAssembler::decode_heap_oop(Register r) {
5281 #ifdef ASSERT
5282   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
5283 #endif
5284   if (Universe::narrow_oop_base() == NULL) {
5285     if (Universe::narrow_oop_shift() != 0) {
5286       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5287       shlq(r, LogMinObjAlignmentInBytes);
5288     }
5289   } else {
5290     Label done;
5291     shlq(r, LogMinObjAlignmentInBytes);
5292     jccb(Assembler::equal, done);
5293     addq(r, r12_heapbase);
5294     bind(done);
5295   }
5296   verify_oop(r, "broken oop in decode_heap_oop");
5297 }
5298 
5299 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
5300   // Note: it will change flags
5301   assert (UseCompressedOops, "should only be used for compressed headers");
5302   assert (Universe::heap() != NULL, "java heap should be initialized");
5303   // Cannot assert, unverified entry point counts instructions (see .ad file)
5304   // vtableStubs also counts instructions in pd_code_size_limit.
5305   // Also do not verify_oop as this is called by verify_oop.
5306   if (Universe::narrow_oop_shift() != 0) {
5307     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5308     shlq(r, LogMinObjAlignmentInBytes);
5309     if (Universe::narrow_oop_base() != NULL) {
5310       addq(r, r12_heapbase);
5311     }
5312   } else {
5313     assert (Universe::narrow_oop_base() == NULL, "sanity");
5314   }
5315 }
5316 
5317 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
5318   // Note: it will change flags
5319   assert (UseCompressedOops, "should only be used for compressed headers");
5320   assert (Universe::heap() != NULL, "java heap should be initialized");
5321   // Cannot assert, unverified entry point counts instructions (see .ad file)
5322   // vtableStubs also counts instructions in pd_code_size_limit.
5323   // Also do not verify_oop as this is called by verify_oop.
5324   if (Universe::narrow_oop_shift() != 0) {
5325     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
5326     if (LogMinObjAlignmentInBytes == Address::times_8) {
5327       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
5328     } else {
5329       if (dst != src) {
5330         movq(dst, src);
5331       }
5332       shlq(dst, LogMinObjAlignmentInBytes);
5333       if (Universe::narrow_oop_base() != NULL) {
5334         addq(dst, r12_heapbase);
5335       }
5336     }
5337   } else {
5338     assert (Universe::narrow_oop_base() == NULL, "sanity");
5339     if (dst != src) {
5340       movq(dst, src);
5341     }
5342   }
5343 }
5344 
5345 void MacroAssembler::encode_klass_not_null(Register r) {
5346   if (Universe::narrow_klass_base() != NULL) {
5347     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
5348     assert(r != r12_heapbase, "Encoding a klass in r12");
5349     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
5350     subq(r, r12_heapbase);
5351   }
5352   if (Universe::narrow_klass_shift() != 0) {
5353     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5354     shrq(r, LogKlassAlignmentInBytes);
5355   }
5356   if (Universe::narrow_klass_base() != NULL) {
5357     reinit_heapbase();
5358   }
5359 }
5360 
5361 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
5362   if (dst == src) {
5363     encode_klass_not_null(src);
5364   } else {
5365     if (Universe::narrow_klass_base() != NULL) {
5366       mov64(dst, (int64_t)Universe::narrow_klass_base());
5367       negq(dst);
5368       addq(dst, src);
5369     } else {
5370       movptr(dst, src);
5371     }
5372     if (Universe::narrow_klass_shift() != 0) {
5373       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5374       shrq(dst, LogKlassAlignmentInBytes);
5375     }
5376   }
5377 }
5378 
5379 // Function instr_size_for_decode_klass_not_null() counts the instructions
5380 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
5381 // when (Universe::heap() != NULL).  Hence, if the instructions they
5382 // generate change, then this method needs to be updated.
5383 int MacroAssembler::instr_size_for_decode_klass_not_null() {
5384   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
5385   if (Universe::narrow_klass_base() != NULL) {
5386     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
5387     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
5388   } else {
5389     // longest load decode klass function, mov64, leaq
5390     return 16;
5391   }
5392 }
5393 
5394 // !!! If the instructions that get generated here change then function
5395 // instr_size_for_decode_klass_not_null() needs to get updated.
5396 void  MacroAssembler::decode_klass_not_null(Register r) {
5397   // Note: it will change flags
5398   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5399   assert(r != r12_heapbase, "Decoding a klass in r12");
5400   andl(r, oopDesc::compressed_klass_mask());
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     andl(src, oopDesc::compressed_klass_mask());
5426     mov64(dst, (int64_t)Universe::narrow_klass_base());
5427     if (Universe::narrow_klass_shift() != 0) {
5428       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
5429       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
5430       leaq(dst, Address(dst, src, Address::times_8, 0));
5431     } else {
5432       addq(dst, src);
5433     }
5434   }
5435 }
5436 
5437 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
5438   assert (UseCompressedOops, "should only be used for compressed headers");
5439   assert (Universe::heap() != NULL, "java heap should be initialized");
5440   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5441   int oop_index = oop_recorder()->find_index(obj);
5442   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5443   mov_narrow_oop(dst, oop_index, rspec);
5444 }
5445 
5446 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
5447   assert (UseCompressedOops, "should only be used for compressed headers");
5448   assert (Universe::heap() != NULL, "java heap should be initialized");
5449   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5450   int oop_index = oop_recorder()->find_index(obj);
5451   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5452   mov_narrow_oop(dst, oop_index, rspec);
5453 }
5454 
5455 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
5456   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5457   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5458   int klass_index = oop_recorder()->find_index(k);
5459   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5460   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
5461 }
5462 
5463 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
5464   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5465   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5466   int klass_index = oop_recorder()->find_index(k);
5467   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5468   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
5469 }
5470 
5471 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
5472   assert (UseCompressedOops, "should only be used for compressed headers");
5473   assert (Universe::heap() != NULL, "java heap should be initialized");
5474   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5475   int oop_index = oop_recorder()->find_index(obj);
5476   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5477   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5478 }
5479 
5480 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
5481   assert (UseCompressedOops, "should only be used for compressed headers");
5482   assert (Universe::heap() != NULL, "java heap should be initialized");
5483   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5484   int oop_index = oop_recorder()->find_index(obj);
5485   RelocationHolder rspec = oop_Relocation::spec(oop_index);
5486   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
5487 }
5488 
5489 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
5490   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5491   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5492   int klass_index = oop_recorder()->find_index(k);
5493   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5494   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
5495 }
5496 
5497 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
5498   assert (UseCompressedClassPointers, "should only be used for compressed headers");
5499   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
5500   int klass_index = oop_recorder()->find_index(k);
5501   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
5502   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
5503 }
5504 
5505 void MacroAssembler::reinit_heapbase() {
5506   if (UseCompressedOops || UseCompressedClassPointers) {
5507     if (Universe::heap() != NULL) {
5508       if (Universe::narrow_oop_base() == NULL) {
5509         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
5510       } else {
5511         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
5512       }
5513     } else {
5514       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
5515     }
5516   }
5517 }
5518 
5519 #endif // _LP64
5520 
5521 // C2 compiled method's prolog code.
5522 void MacroAssembler::verified_entry(Compile* C, int sp_inc) {
5523   int framesize = C->frame_size_in_bytes();
5524   int bangsize = C->bang_size_in_bytes();
5525   bool fp_mode_24b = C->in_24_bit_fp_mode();
5526   int stack_bang_size = C->need_stack_bang(bangsize) ? bangsize : 0;
5527   bool is_stub = C->stub_function() != NULL;
5528 
5529   // WARNING: Initial instruction MUST be 5 bytes or longer so that
5530   // NativeJump::patch_verified_entry will be able to patch out the entry
5531   // code safely. The push to verify stack depth is ok at 5 bytes,
5532   // the frame allocation can be either 3 or 6 bytes. So if we don't do
5533   // stack bang then we must use the 6 byte frame allocation even if
5534   // we have no frame. :-(
5535   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
5536 
5537   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
5538   // Remove word for return addr
5539   framesize -= wordSize;
5540   stack_bang_size -= wordSize;
5541 
5542   // Calls to C2R adapters often do not accept exceptional returns.
5543   // We require that their callers must bang for them.  But be careful, because
5544   // some VM calls (such as call site linkage) can use several kilobytes of
5545   // stack.  But the stack safety zone should account for that.
5546   // See bugs 4446381, 4468289, 4497237.
5547   if (stack_bang_size > 0) {
5548     generate_stack_overflow_check(stack_bang_size);
5549 
5550     // We always push rbp, so that on return to interpreter rbp, will be
5551     // restored correctly and we can correct the stack.
5552     push(rbp);
5553     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5554     if (PreserveFramePointer) {
5555       mov(rbp, rsp);
5556     }
5557     // Remove word for ebp
5558     framesize -= wordSize;
5559 
5560     // Create frame
5561     if (framesize) {
5562       subptr(rsp, framesize);
5563     }
5564   } else {
5565     // Create frame (force generation of a 4 byte immediate value)
5566     subptr_imm32(rsp, framesize);
5567 
5568     // Save RBP register now.
5569     framesize -= wordSize;
5570     movptr(Address(rsp, framesize), rbp);
5571     // Save caller's stack pointer into RBP if the frame pointer is preserved.
5572     if (PreserveFramePointer) {
5573       movptr(rbp, rsp);
5574       if (framesize > 0) {
5575         addptr(rbp, framesize);
5576       }
5577     }
5578   }
5579 
5580   if (C->needs_stack_repair()) {
5581     // Save stack increment (also account for fixed framesize and rbp)
5582     assert((sp_inc & (StackAlignmentInBytes-1)) == 0, "stack increment not aligned");
5583     movptr(Address(rsp, C->sp_inc_offset()), sp_inc + framesize + wordSize);
5584   }
5585 
5586   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
5587     framesize -= wordSize;
5588     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
5589   }
5590 
5591 #ifndef _LP64
5592   // If method sets FPU control word do it now
5593   if (fp_mode_24b) {
5594     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
5595   }
5596   if (UseSSE >= 2 && VerifyFPU) {
5597     verify_FPU(0, "FPU stack must be clean on entry");
5598   }
5599 #endif
5600 
5601 #ifdef ASSERT
5602   if (VerifyStackAtCalls) {
5603     Label L;
5604     push(rax);
5605     mov(rax, rsp);
5606     andptr(rax, StackAlignmentInBytes-1);
5607     cmpptr(rax, StackAlignmentInBytes-wordSize);
5608     pop(rax);
5609     jcc(Assembler::equal, L);
5610     STOP("Stack is not properly aligned!");
5611     bind(L);
5612   }
5613 #endif
5614 
5615   if (!is_stub) {
5616     BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
5617     bs->nmethod_entry_barrier(this);
5618   }
5619 }
5620 
5621 // clear memory of size 'cnt' qwords, starting at 'base' using XMM/YMM registers
5622 void MacroAssembler::xmm_clear_mem(Register base, Register cnt, Register val, XMMRegister xtmp) {
5623   // cnt - number of qwords (8-byte words).
5624   // base - start address, qword aligned.
5625   Label L_zero_64_bytes, L_loop, L_sloop, L_tail, L_end;
5626   movdq(xtmp, val);
5627   if (UseAVX >= 2) {
5628     punpcklqdq(xtmp, xtmp);
5629     vinserti128_high(xtmp, xtmp);
5630   } else {
5631     punpcklqdq(xtmp, xtmp);
5632   }
5633   jmp(L_zero_64_bytes);
5634 
5635   BIND(L_loop);
5636   if (UseAVX >= 2) {
5637     vmovdqu(Address(base,  0), xtmp);
5638     vmovdqu(Address(base, 32), xtmp);
5639   } else {
5640     movdqu(Address(base,  0), xtmp);
5641     movdqu(Address(base, 16), xtmp);
5642     movdqu(Address(base, 32), xtmp);
5643     movdqu(Address(base, 48), xtmp);
5644   }
5645   addptr(base, 64);
5646 
5647   BIND(L_zero_64_bytes);
5648   subptr(cnt, 8);
5649   jccb(Assembler::greaterEqual, L_loop);
5650   addptr(cnt, 4);
5651   jccb(Assembler::less, L_tail);
5652   // Copy trailing 32 bytes
5653   if (UseAVX >= 2) {
5654     vmovdqu(Address(base, 0), xtmp);
5655   } else {
5656     movdqu(Address(base,  0), xtmp);
5657     movdqu(Address(base, 16), xtmp);
5658   }
5659   addptr(base, 32);
5660   subptr(cnt, 4);
5661 
5662   BIND(L_tail);
5663   addptr(cnt, 4);
5664   jccb(Assembler::lessEqual, L_end);
5665   decrement(cnt);
5666 
5667   BIND(L_sloop);
5668   movq(Address(base, 0), xtmp);
5669   addptr(base, 8);
5670   decrement(cnt);
5671   jccb(Assembler::greaterEqual, L_sloop);
5672   BIND(L_end);
5673 }
5674 
5675 void MacroAssembler::store_value_type_fields_to_buf(ciValueKlass* vk) {
5676 #ifndef _LP64
5677   super_call_VM_leaf(StubRoutines::store_value_type_fields_to_buf());
5678 #else
5679   // A value type might be returned. If fields are in registers we
5680   // need to allocate a value type instance and initialize it with
5681   // the value of the fields.
5682   Label skip, slow_case;
5683   // We only need a new buffered value if a new one is not returned
5684   testptr(rax, 1);
5685   jcc(Assembler::zero, skip);
5686 
5687   // Try to allocate a new buffered value (from the heap)
5688   if (UseTLAB) {
5689     // FIXME -- for smaller code, the inline allocation (and the slow case) should be moved inside the pack handler.
5690     if (vk != NULL) {
5691       // Called from C1, where the return type is statically known.
5692       movptr(rbx, (intptr_t)vk->get_ValueKlass());
5693       jint lh = vk->layout_helper();
5694       assert(lh != Klass::_lh_neutral_value, "inline class in return type must have been resolved");
5695       movl(r14, lh);
5696     } else {
5697       // Call from interpreter. RAX contains ((the ValueKlass* of the return type) | 0x01)
5698       mov(rbx, rax);
5699       andptr(rbx, -2);
5700       movl(r14, Address(rbx, Klass::layout_helper_offset()));
5701     }
5702 
5703     movptr(r13, Address(r15_thread, in_bytes(JavaThread::tlab_top_offset())));
5704     lea(r14, Address(r13, r14, Address::times_1));
5705     cmpptr(r14, Address(r15_thread, in_bytes(JavaThread::tlab_end_offset())));
5706     jcc(Assembler::above, slow_case);
5707     movptr(Address(r15_thread, in_bytes(JavaThread::tlab_top_offset())), r14);
5708     movptr(Address(r13, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::always_locked_prototype());
5709 
5710     xorl(rax, rax); // use zero reg to clear memory (shorter code)
5711     store_klass_gap(r13, rax);  // zero klass gap for compressed oops
5712 
5713     if (vk == NULL) {
5714       // store_klass corrupts rbx, so save it in rax for later use (interpreter case only).
5715       mov(rax, rbx);
5716     }
5717     store_klass(r13, rbx);  // klass
5718 
5719     // We have our new buffered value, initialize its fields with a
5720     // value class specific handler
5721     if (vk != NULL) {
5722       // FIXME -- do the packing in-line to avoid the runtime call
5723       mov(rax, r13);
5724       call(RuntimeAddress(vk->pack_handler()));
5725     } else {
5726       movptr(rbx, Address(rax, InstanceKlass::adr_valueklass_fixed_block_offset()));
5727       movptr(rbx, Address(rbx, ValueKlass::pack_handler_offset()));
5728       mov(rax, r13);
5729       call(rbx);
5730     }
5731     jmp(skip);
5732   }
5733 
5734   bind(slow_case);
5735   // We failed to allocate a new value, fall back to a runtime
5736   // call. Some oop field may be live in some registers but we can't
5737   // tell. That runtime call will take care of preserving them
5738   // across a GC if there's one.
5739   super_call_VM_leaf(StubRoutines::store_value_type_fields_to_buf());
5740   bind(skip);
5741 #endif
5742 }
5743 
5744 
5745 // Move a value between registers/stack slots and update the reg_state
5746 bool MacroAssembler::move_helper(VMReg from, VMReg to, BasicType bt, RegState reg_state[], int ret_off, int extra_stack_offset) {
5747   if (reg_state[to->value()] == reg_written) {
5748     return true; // Already written
5749   }
5750   if (from != to && bt != T_VOID) {
5751     if (reg_state[to->value()] == reg_readonly) {
5752       return false; // Not yet writable
5753     }
5754     if (from->is_reg()) {
5755       if (to->is_reg()) {
5756         if (from->is_XMMRegister()) {
5757           if (bt == T_DOUBLE) {
5758             movdbl(to->as_XMMRegister(), from->as_XMMRegister());
5759           } else {
5760             assert(bt == T_FLOAT, "must be float");
5761             movflt(to->as_XMMRegister(), from->as_XMMRegister());
5762           }
5763         } else {
5764           movq(to->as_Register(), from->as_Register());
5765         }
5766       } else {
5767         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
5768         assert(st_off != ret_off, "overwriting return address at %d", st_off);
5769         Address to_addr = Address(rsp, st_off);
5770         if (from->is_XMMRegister()) {
5771           if (bt == T_DOUBLE) {
5772             movdbl(to_addr, from->as_XMMRegister());
5773           } else {
5774             assert(bt == T_FLOAT, "must be float");
5775             movflt(to_addr, from->as_XMMRegister());
5776           }
5777         } else {
5778           movq(to_addr, from->as_Register());
5779         }
5780       }
5781     } else {
5782       Address from_addr = Address(rsp, from->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset);
5783       if (to->is_reg()) {
5784         if (to->is_XMMRegister()) {
5785           if (bt == T_DOUBLE) {
5786             movdbl(to->as_XMMRegister(), from_addr);
5787           } else {
5788             assert(bt == T_FLOAT, "must be float");
5789             movflt(to->as_XMMRegister(), from_addr);
5790           }
5791         } else {
5792           movq(to->as_Register(), from_addr);
5793         }
5794       } else {
5795         int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
5796         assert(st_off != ret_off, "overwriting return address at %d", st_off);
5797         movq(r13, from_addr);
5798         movq(Address(rsp, st_off), r13);
5799       }
5800     }
5801   }
5802   // Update register states
5803   reg_state[from->value()] = reg_writable;
5804   reg_state[to->value()] = reg_written;
5805   return true;
5806 }
5807 
5808 // Read all fields from a value type oop and store the values in registers/stack slots
5809 bool MacroAssembler::unpack_value_helper(const GrowableArray<SigEntry>* sig, int& sig_index, VMReg from, VMRegPair* regs_to,
5810                                          int& to_index, RegState reg_state[], int ret_off, int extra_stack_offset) {
5811   Register fromReg = from->is_reg() ? from->as_Register() : noreg;
5812   assert(sig->at(sig_index)._bt == T_VOID, "should be at end delimiter");
5813 
5814   int vt = 1;
5815   bool done = true;
5816   bool mark_done = true;
5817   do {
5818     sig_index--;
5819     BasicType bt = sig->at(sig_index)._bt;
5820     if (bt == T_VALUETYPE) {
5821       vt--;
5822     } else if (bt == T_VOID &&
5823                sig->at(sig_index-1)._bt != T_LONG &&
5824                sig->at(sig_index-1)._bt != T_DOUBLE) {
5825       vt++;
5826     } else if (SigEntry::is_reserved_entry(sig, sig_index)) {
5827       to_index--; // Ignore this
5828     } else {
5829       assert(to_index >= 0, "invalid to_index");
5830       VMRegPair pair_to = regs_to[to_index--];
5831       VMReg to = pair_to.first();
5832 
5833       if (bt == T_VOID) continue;
5834 
5835       int idx = (int)to->value();
5836       if (reg_state[idx] == reg_readonly) {
5837          if (idx != from->value()) {
5838            mark_done = false;
5839          }
5840          done = false;
5841          continue;
5842       } else if (reg_state[idx] == reg_written) {
5843         continue;
5844       } else {
5845         assert(reg_state[idx] == reg_writable, "must be writable");
5846         reg_state[idx] = reg_written;
5847        }
5848 
5849       if (fromReg == noreg) {
5850         int st_off = from->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
5851         movq(r10, Address(rsp, st_off));
5852         fromReg = r10;
5853       }
5854 
5855       int off = sig->at(sig_index)._offset;
5856       assert(off > 0, "offset in object should be positive");
5857       bool is_oop = (bt == T_OBJECT || bt == T_ARRAY);
5858 
5859       Address fromAddr = Address(fromReg, off);
5860       bool is_signed = (bt != T_CHAR) && (bt != T_BOOLEAN);
5861       if (!to->is_XMMRegister()) {
5862         Register dst = to->is_stack() ? r13 : to->as_Register();
5863         if (is_oop) {
5864           load_heap_oop(dst, fromAddr);
5865         } else {
5866           load_sized_value(dst, fromAddr, type2aelembytes(bt), is_signed);
5867         }
5868         if (to->is_stack()) {
5869           int st_off = to->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
5870           assert(st_off != ret_off, "overwriting return address at %d", st_off);
5871           movq(Address(rsp, st_off), dst);
5872         }
5873       } else {
5874         if (bt == T_DOUBLE) {
5875           movdbl(to->as_XMMRegister(), fromAddr);
5876         } else {
5877           assert(bt == T_FLOAT, "must be float");
5878           movflt(to->as_XMMRegister(), fromAddr);
5879         }
5880       }
5881     }
5882   } while (vt != 0);
5883   if (mark_done && reg_state[from->value()] != reg_written) {
5884     // This is okay because no one else will write to that slot
5885     reg_state[from->value()] = reg_writable;
5886   }
5887   return done;
5888 }
5889 
5890 class ScalarizedValueArgsStream : public StackObj {
5891   const GrowableArray<SigEntry>* _sig_cc;
5892   int _sig_cc_index;
5893   const VMRegPair* _regs_cc;
5894   int _regs_cc_count;
5895   int _regs_cc_index;
5896   int _vt;
5897   DEBUG_ONLY(bool _finished);
5898 public:
5899   ScalarizedValueArgsStream(const GrowableArray<SigEntry>* sig_cc, int sig_cc_index, VMRegPair* regs_cc, int regs_cc_count, int regs_cc_index) :
5900     _sig_cc(sig_cc), _sig_cc_index(sig_cc_index), _regs_cc(regs_cc), _regs_cc_count(regs_cc_count), _regs_cc_index(regs_cc_index) {
5901     assert(_sig_cc->at(_sig_cc_index)._bt == T_VALUETYPE, "should be at end delimiter");
5902     _vt = 1;
5903     DEBUG_ONLY(_finished = false);
5904   }
5905 
5906   bool next(VMRegPair& pair, BasicType& bt) {
5907     assert(!_finished, "sanity");
5908     do {
5909       _sig_cc_index++;
5910       bt = _sig_cc->at(_sig_cc_index)._bt;
5911       if (bt == T_VALUETYPE) {
5912         _vt++;
5913       } else if (bt == T_VOID &&
5914                  _sig_cc->at(_sig_cc_index-1)._bt != T_LONG &&
5915                  _sig_cc->at(_sig_cc_index-1)._bt != T_DOUBLE) {
5916         _vt--;
5917       } else if (SigEntry::is_reserved_entry(_sig_cc, _sig_cc_index)) {
5918         _regs_cc_index++;
5919       } else {
5920         assert(_regs_cc_index < _regs_cc_count, "must be");
5921         pair = _regs_cc[_regs_cc_index++];
5922         VMReg r1 = pair.first();
5923         VMReg r2 = pair.second();
5924 
5925         if (!r1->is_valid()) {
5926           assert(!r2->is_valid(), "must be invalid");
5927         } else {
5928           return true;
5929         }
5930       }
5931     } while (_vt != 0);
5932 
5933     DEBUG_ONLY(_finished = true);
5934     return false;
5935   }
5936 
5937   int sig_cc_index() {return _sig_cc_index;}
5938   int regs_cc_index() {return _regs_cc_index;}
5939 };
5940 
5941 static void skip_unpacked_fields(const GrowableArray<SigEntry>* sig, int& sig_index, VMRegPair* regs_from, int regs_from_count, int& from_index) {
5942   ScalarizedValueArgsStream stream(sig, sig_index, regs_from, regs_from_count, from_index);
5943   VMRegPair from_pair;
5944   BasicType bt;
5945   while (stream.next(from_pair, bt)) {}
5946   sig_index = stream.sig_cc_index();
5947   from_index = stream.regs_cc_index();
5948 }
5949 
5950 static bool is_reg_in_unpacked_fields(const GrowableArray<SigEntry>* sig, int sig_index, VMReg to, VMRegPair* regs_from, int regs_from_count, int from_index) {
5951   ScalarizedValueArgsStream stream(sig, sig_index, regs_from, regs_from_count, from_index);
5952   VMRegPair from_pair;
5953   BasicType bt;
5954   while (stream.next(from_pair, bt)) {
5955     if (from_pair.first() == to) {
5956       return true;
5957     }
5958   }
5959 
5960   return false;
5961 }
5962 
5963 // Pack fields back into a value type oop
5964 bool MacroAssembler::pack_value_helper(const GrowableArray<SigEntry>* sig, int& sig_index, int vtarg_index,
5965                                        VMReg to, VMRegPair* regs_from, int regs_from_count, int& from_index, RegState reg_state[],
5966                                        int ret_off, int extra_stack_offset) {
5967   assert(sig->at(sig_index)._bt == T_VALUETYPE, "should be at end delimiter");
5968   assert(to->is_valid(), "must be");
5969 
5970   if (reg_state[to->value()] == reg_written) {
5971     skip_unpacked_fields(sig, sig_index, regs_from, regs_from_count, from_index);
5972     return true; // Already written
5973   }
5974 
5975   Register val_array = rax;
5976   Register val_obj_tmp = r11;
5977   Register from_reg_tmp = r10;
5978   Register tmp1 = r14;
5979   Register tmp2 = r13;
5980   Register tmp3 = rbx;
5981   Register val_obj = to->is_stack() ? val_obj_tmp : to->as_Register();
5982 
5983   if (reg_state[to->value()] == reg_readonly) {
5984     if (!is_reg_in_unpacked_fields(sig, sig_index, to, regs_from, regs_from_count, from_index)) {
5985       skip_unpacked_fields(sig, sig_index, regs_from, regs_from_count, from_index);
5986       return false; // Not yet writable
5987     }
5988     val_obj = val_obj_tmp;
5989   }
5990 
5991   int index = arrayOopDesc::base_offset_in_bytes(T_OBJECT) + vtarg_index * type2aelembytes(T_VALUETYPE);
5992   load_heap_oop(val_obj, Address(val_array, index));
5993 
5994   ScalarizedValueArgsStream stream(sig, sig_index, regs_from, regs_from_count, from_index);
5995   VMRegPair from_pair;
5996   BasicType bt;
5997   while (stream.next(from_pair, bt)) {
5998     int off = sig->at(stream.sig_cc_index())._offset;
5999     assert(off > 0, "offset in object should be positive");
6000     bool is_oop = (bt == T_OBJECT || bt == T_ARRAY);
6001     size_t size_in_bytes = is_java_primitive(bt) ? type2aelembytes(bt) : wordSize;
6002 
6003     VMReg from_r1 = from_pair.first();
6004     VMReg from_r2 = from_pair.second();
6005 
6006     // Pack the scalarized field into the value object.
6007     Address dst(val_obj, off);
6008     if (!from_r1->is_XMMRegister()) {
6009       Register from_reg;
6010 
6011       if (from_r1->is_stack()) {
6012         from_reg = from_reg_tmp;
6013         int ld_off = from_r1->reg2stack() * VMRegImpl::stack_slot_size + extra_stack_offset;
6014         load_sized_value(from_reg, Address(rsp, ld_off), size_in_bytes, /* is_signed */ false);
6015       } else {
6016         from_reg = from_r1->as_Register();
6017       }
6018 
6019       if (is_oop) {
6020         DecoratorSet decorators = IN_HEAP | ACCESS_WRITE;
6021         store_heap_oop(dst, from_reg, tmp1, tmp2, tmp3, decorators);
6022       } else {
6023         store_sized_value(dst, from_reg, size_in_bytes);
6024       }
6025     } else {
6026       if (from_r2->is_valid()) {
6027         movdbl(dst, from_r1->as_XMMRegister());
6028       } else {
6029         movflt(dst, from_r1->as_XMMRegister());
6030       }
6031     }
6032     reg_state[from_r1->value()] = reg_writable;
6033   }
6034   sig_index = stream.sig_cc_index();
6035   from_index = stream.regs_cc_index();
6036 
6037   assert(reg_state[to->value()] == reg_writable, "must have already been read");
6038   bool success = move_helper(val_obj->as_VMReg(), to, T_OBJECT, reg_state, ret_off, extra_stack_offset);
6039   assert(success, "to register must be writeable");
6040 
6041   return true;
6042 }
6043 
6044 // Unpack all value type arguments passed as oops
6045 void MacroAssembler::unpack_value_args(Compile* C, bool receiver_only) {
6046   assert(C->has_scalarized_args(), "value type argument scalarization is disabled");
6047   Method* method = C->method()->get_Method();
6048   const GrowableArray<SigEntry>* sig_cc = method->adapter()->get_sig_cc();
6049   assert(sig_cc != NULL, "must have scalarized signature");
6050 
6051   // Get unscalarized calling convention
6052   BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sig_cc->length()); // FIXME - may underflow if we support values with no fields!
6053   int args_passed = 0;
6054   if (!method->is_static()) {
6055     sig_bt[args_passed++] = T_OBJECT;
6056   }
6057   if (!receiver_only) {
6058     for (SignatureStream ss(method->signature()); !ss.at_return_type(); ss.next()) {
6059       BasicType bt = ss.type();
6060       sig_bt[args_passed++] = bt;
6061       if (type2size[bt] == 2) {
6062         sig_bt[args_passed++] = T_VOID;
6063       }
6064     }
6065   } else {
6066     // Only unpack the receiver, all other arguments are already scalarized
6067     InstanceKlass* holder = method->method_holder();
6068     int rec_len = holder->is_value() ? ValueKlass::cast(holder)->extended_sig()->length() : 1;
6069     // Copy scalarized signature but skip receiver, value type delimiters and reserved entries
6070     for (int i = 0; i < sig_cc->length(); i++) {
6071       if (!SigEntry::is_reserved_entry(sig_cc, i)) {
6072         if (SigEntry::skip_value_delimiters(sig_cc, i) && rec_len <= 0) {
6073           sig_bt[args_passed++] = sig_cc->at(i)._bt;
6074         }
6075         rec_len--;
6076       }
6077     }
6078   }
6079   VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, args_passed);
6080   int args_on_stack = SharedRuntime::java_calling_convention(sig_bt, regs, args_passed, false);
6081 
6082   // Get scalarized calling convention
6083   int args_passed_cc = SigEntry::fill_sig_bt(sig_cc, sig_bt);
6084   VMRegPair* regs_cc = NEW_RESOURCE_ARRAY(VMRegPair, sig_cc->length());
6085   int args_on_stack_cc = SharedRuntime::java_calling_convention(sig_bt, regs_cc, args_passed_cc, false);
6086 
6087   int extra_stack_offset = wordSize; // stack has the returned address
6088   int sp_inc = shuffle_value_args(false, receiver_only, extra_stack_offset, sig_bt, sig_cc,
6089                                   args_passed, args_on_stack, regs,
6090                                   args_passed_cc, args_on_stack_cc, regs_cc);
6091   // Emit code for verified entry and save increment for stack repair on return
6092   verified_entry(C, sp_inc);
6093 }
6094 
6095 int MacroAssembler::shuffle_value_args(bool is_packing, bool receiver_only, int extra_stack_offset,
6096                                        BasicType* sig_bt, const GrowableArray<SigEntry>* sig_cc,
6097                                        int args_passed, int args_on_stack, VMRegPair* regs,            // from
6098                                        int args_passed_to, int args_on_stack_to, VMRegPair* regs_to) { // to
6099   // Check if we need to extend the stack for unpacking
6100   int sp_inc = (args_on_stack_to - args_on_stack) * VMRegImpl::stack_slot_size;
6101   if (sp_inc > 0) {
6102     // Save the return address, adjust the stack (make sure it is properly
6103     // 16-byte aligned) and copy the return address to the new top of the stack.
6104     pop(r13);
6105     sp_inc = align_up(sp_inc, StackAlignmentInBytes);
6106     subptr(rsp, sp_inc);
6107     push(r13);
6108   } else {
6109     // The scalarized calling convention needs less stack space than the unscalarized one.
6110     // No need to extend the stack, the caller will take care of these adjustments.
6111     sp_inc = 0;
6112   }
6113 
6114   int ret_off; // make sure we don't overwrite the return address
6115   if (is_packing) {
6116     // For C1 code, the VVEP doesn't have reserved slots, so we store the returned address at
6117     // rsp[0] during shuffling.
6118     ret_off = 0;
6119   } else {
6120     // C2 code ensures that sp_inc is a reserved slot.
6121     ret_off = sp_inc;
6122   }
6123 
6124   // Initialize register/stack slot states (make all writable)
6125   int max_stack = MAX2(args_on_stack + sp_inc/VMRegImpl::stack_slot_size, args_on_stack_to);
6126   int max_reg = VMRegImpl::stack2reg(max_stack)->value();
6127   RegState* reg_state = NEW_RESOURCE_ARRAY(RegState, max_reg);
6128   for (int i = 0; i < max_reg; ++i) {
6129     reg_state[i] = reg_writable;
6130   }
6131   // Set all source registers/stack slots to readonly to prevent accidental overwriting
6132   for (int i = 0; i < args_passed; ++i) {
6133     VMReg reg = regs[i].first();
6134     if (!reg->is_valid()) continue;
6135     if (reg->is_stack()) {
6136       // Update source stack location by adding stack increment
6137       reg = VMRegImpl::stack2reg(reg->reg2stack() + sp_inc/VMRegImpl::stack_slot_size);
6138       regs[i] = reg;
6139     }
6140     assert(reg->value() >= 0 && reg->value() < max_reg, "reg value out of bounds");
6141     reg_state[reg->value()] = reg_readonly;
6142   }
6143 
6144   // Emit code for packing/unpacking value type arguments
6145   // We try multiple times and eventually start spilling to resolve (circular) dependencies
6146   bool done = false;
6147   for (int i = 0; i < 2*args_passed_to && !done; ++i) {
6148     done = true;
6149     bool spill = (i > args_passed_to); // Start spilling?
6150     // Iterate over all arguments (when unpacking, do in reverse)
6151     int step = is_packing ? 1 : -1;
6152     int from_index    = is_packing ? 0 : args_passed      - 1;
6153     int to_index      = is_packing ? 0 : args_passed_to   - 1;
6154     int sig_index     = is_packing ? 0 : sig_cc->length() - 1;
6155     int sig_index_end = is_packing ? sig_cc->length() : -1;
6156     int vtarg_index = 0;
6157     for (; sig_index != sig_index_end; sig_index += step) {
6158       assert(0 <= sig_index && sig_index < sig_cc->length(), "index out of bounds");
6159       if (SigEntry::is_reserved_entry(sig_cc, sig_index)) {
6160         if (is_packing) {
6161           if (i == 0) {
6162             // The reserved entries are not used by the packed args, so make them writable
6163             VMReg from_reg = regs[from_index].first();
6164             if (from_reg->is_valid()) {
6165               assert(from_reg->is_stack(), "reserved entries must be stack");
6166               reg_state[from_reg->value()] = reg_writable;
6167             }
6168           }
6169           from_index += step;
6170         } else {
6171           to_index += step;
6172         }
6173       } else {
6174         assert(0 <= from_index && from_index < args_passed, "index out of bounds");
6175         assert(0 <= to_index && to_index < args_passed_to, "index out of bounds");
6176         if (spill) {
6177           // This call returns true IFF we should keep trying to spill in this round.
6178           spill = shuffle_value_args_spill(is_packing, sig_cc, sig_index, regs, from_index, args_passed,
6179                                            reg_state, ret_off, extra_stack_offset);
6180         }
6181         BasicType bt = sig_cc->at(sig_index)._bt;
6182         if (SigEntry::skip_value_delimiters(sig_cc, sig_index)) {
6183           VMReg from_reg = regs[from_index].first();
6184           done &= move_helper(from_reg, regs_to[to_index].first(), bt, reg_state, ret_off, extra_stack_offset);
6185           to_index += step;
6186         } else if (is_packing || !receiver_only || (from_index == 0 && bt == T_VOID)) {
6187           if (is_packing) {
6188             VMReg reg_to = regs_to[to_index].first();
6189             done &= pack_value_helper(sig_cc, sig_index, vtarg_index, reg_to, regs, args_passed, from_index,
6190                                       reg_state, ret_off, extra_stack_offset);
6191             vtarg_index ++;
6192             to_index ++;
6193             continue; // from_index already adjusted
6194           } else {
6195             VMReg from_reg = regs[from_index].first();
6196             done &= unpack_value_helper(sig_cc, sig_index, from_reg, regs_to, to_index, reg_state, ret_off, extra_stack_offset);
6197           }
6198         } else {
6199           continue;
6200         }
6201         from_index += step;
6202       }
6203     }
6204   }
6205   guarantee(done, "Could not resolve circular dependency when shuffling value type arguments");
6206   return sp_inc;
6207 }
6208 
6209 bool MacroAssembler::shuffle_value_args_spill(bool is_packing, const GrowableArray<SigEntry>* sig_cc, int sig_cc_index,
6210                                               VMRegPair* regs_from, int from_index, int regs_from_count,
6211                                               RegState* reg_state, int ret_off, int extra_stack_offset) {
6212   VMReg reg;
6213 
6214   if (!is_packing || SigEntry::skip_value_delimiters(sig_cc, sig_cc_index)) {
6215     reg = regs_from[from_index].first();
6216     if (!reg->is_valid() || reg_state[reg->value()] != reg_readonly) {
6217       // Spilling this won't break circles
6218       return true;
6219     }
6220   } else {
6221     ScalarizedValueArgsStream stream(sig_cc, sig_cc_index, regs_from, regs_from_count, from_index);
6222     VMRegPair from_pair;
6223     BasicType bt;
6224     bool found = false;
6225     while (stream.next(from_pair, bt)) {
6226       reg = from_pair.first();
6227       assert(reg->is_valid(), "must be");
6228       if (reg_state[reg->value()] == reg_readonly) {
6229         found = true;
6230         break;
6231       }
6232     }
6233     if (!found) {
6234       // Spilling fields in this value arg won't break circles
6235       return true;
6236     }
6237   }
6238 
6239   // Spill argument to be able to write the source and resolve circular dependencies
6240   VMReg spill_reg = reg->is_XMMRegister() ? xmm8->as_VMReg() : r14->as_VMReg();
6241   if (reg_state[spill_reg->value()] == reg_readonly) {
6242     // We have already spilled (in previous round). The spilled register should be consumed by this round.
6243   } else {
6244     bool res = move_helper(reg, spill_reg, T_DOUBLE, reg_state, ret_off, extra_stack_offset);
6245     assert(res, "Spilling should not fail");
6246     // Set spill_reg as new source and update state
6247     reg = spill_reg;
6248     regs_from[from_index].set1(reg);
6249     reg_state[reg->value()] = reg_readonly;
6250   }
6251 
6252   return false; // Do not spill again in this round
6253 }
6254 
6255 // Restores the stack on return
6256 void MacroAssembler::restore_stack(Compile* C) {
6257   int framesize = C->frame_size_in_bytes();
6258   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6259   // Remove word for return addr already pushed and RBP
6260   framesize -= 2*wordSize;
6261 
6262   if (C->needs_stack_repair()) {
6263     // Restore rbp and repair rsp by adding the stack increment
6264     movq(rbp, Address(rsp, framesize));
6265     addq(rsp, Address(rsp, C->sp_inc_offset()));
6266   } else {
6267     if (framesize > 0) {
6268       addq(rsp, framesize);
6269     }
6270     pop(rbp);
6271   }
6272 }
6273 
6274 void MacroAssembler::clear_mem(Register base, Register cnt, Register val, XMMRegister xtmp, bool is_large, bool word_copy_only) {
6275   // cnt - number of qwords (8-byte words).
6276   // base - start address, qword aligned.
6277   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6278   assert(base==rdi, "base register must be edi for rep stos");
6279   assert(val==rax,   "tmp register must be eax for rep stos");
6280   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6281   assert(InitArrayShortSize % BytesPerLong == 0,
6282     "InitArrayShortSize should be the multiple of BytesPerLong");
6283 
6284   Label DONE;
6285 
6286   if (!is_large) {
6287     Label LOOP, LONG;
6288     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6289     jccb(Assembler::greater, LONG);
6290 
6291     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6292 
6293     decrement(cnt);
6294     jccb(Assembler::negative, DONE); // Zero length
6295 
6296     // Use individual pointer-sized stores for small counts:
6297     BIND(LOOP);
6298     movptr(Address(base, cnt, Address::times_ptr), val);
6299     decrement(cnt);
6300     jccb(Assembler::greaterEqual, LOOP);
6301     jmpb(DONE);
6302 
6303     BIND(LONG);
6304   }
6305 
6306   // Use longer rep-prefixed ops for non-small counts:
6307   if (UseFastStosb && !word_copy_only) {
6308     shlptr(cnt, 3); // convert to number of bytes
6309     rep_stosb();
6310   } else if (UseXMMForObjInit) {
6311     xmm_clear_mem(base, cnt, val, xtmp);
6312   } else {
6313     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6314     rep_stos();
6315   }
6316 
6317   BIND(DONE);
6318 }
6319 
6320 #ifdef COMPILER2
6321 
6322 // IndexOf for constant substrings with size >= 8 chars
6323 // which don't need to be loaded through stack.
6324 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6325                                       Register cnt1, Register cnt2,
6326                                       int int_cnt2,  Register result,
6327                                       XMMRegister vec, Register tmp,
6328                                       int ae) {
6329   ShortBranchVerifier sbv(this);
6330   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6331   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6332 
6333   // This method uses the pcmpestri instruction with bound registers
6334   //   inputs:
6335   //     xmm - substring
6336   //     rax - substring length (elements count)
6337   //     mem - scanned string
6338   //     rdx - string length (elements count)
6339   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6340   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6341   //   outputs:
6342   //     rcx - matched index in string
6343   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6344   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6345   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6346   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6347   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6348 
6349   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6350         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6351         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6352 
6353   // Note, inline_string_indexOf() generates checks:
6354   // if (substr.count > string.count) return -1;
6355   // if (substr.count == 0) return 0;
6356   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6357 
6358   // Load substring.
6359   if (ae == StrIntrinsicNode::UL) {
6360     pmovzxbw(vec, Address(str2, 0));
6361   } else {
6362     movdqu(vec, Address(str2, 0));
6363   }
6364   movl(cnt2, int_cnt2);
6365   movptr(result, str1); // string addr
6366 
6367   if (int_cnt2 > stride) {
6368     jmpb(SCAN_TO_SUBSTR);
6369 
6370     // Reload substr for rescan, this code
6371     // is executed only for large substrings (> 8 chars)
6372     bind(RELOAD_SUBSTR);
6373     if (ae == StrIntrinsicNode::UL) {
6374       pmovzxbw(vec, Address(str2, 0));
6375     } else {
6376       movdqu(vec, Address(str2, 0));
6377     }
6378     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6379 
6380     bind(RELOAD_STR);
6381     // We came here after the beginning of the substring was
6382     // matched but the rest of it was not so we need to search
6383     // again. Start from the next element after the previous match.
6384 
6385     // cnt2 is number of substring reminding elements and
6386     // cnt1 is number of string reminding elements when cmp failed.
6387     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6388     subl(cnt1, cnt2);
6389     addl(cnt1, int_cnt2);
6390     movl(cnt2, int_cnt2); // Now restore cnt2
6391 
6392     decrementl(cnt1);     // Shift to next element
6393     cmpl(cnt1, cnt2);
6394     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6395 
6396     addptr(result, (1<<scale1));
6397 
6398   } // (int_cnt2 > 8)
6399 
6400   // Scan string for start of substr in 16-byte vectors
6401   bind(SCAN_TO_SUBSTR);
6402   pcmpestri(vec, Address(result, 0), mode);
6403   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6404   subl(cnt1, stride);
6405   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6406   cmpl(cnt1, cnt2);
6407   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6408   addptr(result, 16);
6409   jmpb(SCAN_TO_SUBSTR);
6410 
6411   // Found a potential substr
6412   bind(FOUND_CANDIDATE);
6413   // Matched whole vector if first element matched (tmp(rcx) == 0).
6414   if (int_cnt2 == stride) {
6415     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6416   } else { // int_cnt2 > 8
6417     jccb(Assembler::overflow, FOUND_SUBSTR);
6418   }
6419   // After pcmpestri tmp(rcx) contains matched element index
6420   // Compute start addr of substr
6421   lea(result, Address(result, tmp, scale1));
6422 
6423   // Make sure string is still long enough
6424   subl(cnt1, tmp);
6425   cmpl(cnt1, cnt2);
6426   if (int_cnt2 == stride) {
6427     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6428   } else { // int_cnt2 > 8
6429     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6430   }
6431   // Left less then substring.
6432 
6433   bind(RET_NOT_FOUND);
6434   movl(result, -1);
6435   jmp(EXIT);
6436 
6437   if (int_cnt2 > stride) {
6438     // This code is optimized for the case when whole substring
6439     // is matched if its head is matched.
6440     bind(MATCH_SUBSTR_HEAD);
6441     pcmpestri(vec, Address(result, 0), mode);
6442     // Reload only string if does not match
6443     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6444 
6445     Label CONT_SCAN_SUBSTR;
6446     // Compare the rest of substring (> 8 chars).
6447     bind(FOUND_SUBSTR);
6448     // First 8 chars are already matched.
6449     negptr(cnt2);
6450     addptr(cnt2, stride);
6451 
6452     bind(SCAN_SUBSTR);
6453     subl(cnt1, stride);
6454     cmpl(cnt2, -stride); // Do not read beyond substring
6455     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6456     // Back-up strings to avoid reading beyond substring:
6457     // cnt1 = cnt1 - cnt2 + 8
6458     addl(cnt1, cnt2); // cnt2 is negative
6459     addl(cnt1, stride);
6460     movl(cnt2, stride); negptr(cnt2);
6461     bind(CONT_SCAN_SUBSTR);
6462     if (int_cnt2 < (int)G) {
6463       int tail_off1 = int_cnt2<<scale1;
6464       int tail_off2 = int_cnt2<<scale2;
6465       if (ae == StrIntrinsicNode::UL) {
6466         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6467       } else {
6468         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6469       }
6470       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6471     } else {
6472       // calculate index in register to avoid integer overflow (int_cnt2*2)
6473       movl(tmp, int_cnt2);
6474       addptr(tmp, cnt2);
6475       if (ae == StrIntrinsicNode::UL) {
6476         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6477       } else {
6478         movdqu(vec, Address(str2, tmp, scale2, 0));
6479       }
6480       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6481     }
6482     // Need to reload strings pointers if not matched whole vector
6483     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6484     addptr(cnt2, stride);
6485     jcc(Assembler::negative, SCAN_SUBSTR);
6486     // Fall through if found full substring
6487 
6488   } // (int_cnt2 > 8)
6489 
6490   bind(RET_FOUND);
6491   // Found result if we matched full small substring.
6492   // Compute substr offset
6493   subptr(result, str1);
6494   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6495     shrl(result, 1); // index
6496   }
6497   bind(EXIT);
6498 
6499 } // string_indexofC8
6500 
6501 // Small strings are loaded through stack if they cross page boundary.
6502 void MacroAssembler::string_indexof(Register str1, Register str2,
6503                                     Register cnt1, Register cnt2,
6504                                     int int_cnt2,  Register result,
6505                                     XMMRegister vec, Register tmp,
6506                                     int ae) {
6507   ShortBranchVerifier sbv(this);
6508   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6509   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6510 
6511   //
6512   // int_cnt2 is length of small (< 8 chars) constant substring
6513   // or (-1) for non constant substring in which case its length
6514   // is in cnt2 register.
6515   //
6516   // Note, inline_string_indexOf() generates checks:
6517   // if (substr.count > string.count) return -1;
6518   // if (substr.count == 0) return 0;
6519   //
6520   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6521   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
6522   // This method uses the pcmpestri instruction with bound registers
6523   //   inputs:
6524   //     xmm - substring
6525   //     rax - substring length (elements count)
6526   //     mem - scanned string
6527   //     rdx - string length (elements count)
6528   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6529   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6530   //   outputs:
6531   //     rcx - matched index in string
6532   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6533   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6534   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6535   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6536 
6537   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
6538         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
6539         FOUND_CANDIDATE;
6540 
6541   { //========================================================
6542     // We don't know where these strings are located
6543     // and we can't read beyond them. Load them through stack.
6544     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
6545 
6546     movptr(tmp, rsp); // save old SP
6547 
6548     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
6549       if (int_cnt2 == (1>>scale2)) { // One byte
6550         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
6551         load_unsigned_byte(result, Address(str2, 0));
6552         movdl(vec, result); // move 32 bits
6553       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
6554         // Not enough header space in 32-bit VM: 12+3 = 15.
6555         movl(result, Address(str2, -1));
6556         shrl(result, 8);
6557         movdl(vec, result); // move 32 bits
6558       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
6559         load_unsigned_short(result, Address(str2, 0));
6560         movdl(vec, result); // move 32 bits
6561       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
6562         movdl(vec, Address(str2, 0)); // move 32 bits
6563       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
6564         movq(vec, Address(str2, 0));  // move 64 bits
6565       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
6566         // Array header size is 12 bytes in 32-bit VM
6567         // + 6 bytes for 3 chars == 18 bytes,
6568         // enough space to load vec and shift.
6569         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
6570         if (ae == StrIntrinsicNode::UL) {
6571           int tail_off = int_cnt2-8;
6572           pmovzxbw(vec, Address(str2, tail_off));
6573           psrldq(vec, -2*tail_off);
6574         }
6575         else {
6576           int tail_off = int_cnt2*(1<<scale2);
6577           movdqu(vec, Address(str2, tail_off-16));
6578           psrldq(vec, 16-tail_off);
6579         }
6580       }
6581     } else { // not constant substring
6582       cmpl(cnt2, stride);
6583       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
6584 
6585       // We can read beyond string if srt+16 does not cross page boundary
6586       // since heaps are aligned and mapped by pages.
6587       assert(os::vm_page_size() < (int)G, "default page should be small");
6588       movl(result, str2); // We need only low 32 bits
6589       andl(result, (os::vm_page_size()-1));
6590       cmpl(result, (os::vm_page_size()-16));
6591       jccb(Assembler::belowEqual, CHECK_STR);
6592 
6593       // Move small strings to stack to allow load 16 bytes into vec.
6594       subptr(rsp, 16);
6595       int stk_offset = wordSize-(1<<scale2);
6596       push(cnt2);
6597 
6598       bind(COPY_SUBSTR);
6599       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
6600         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
6601         movb(Address(rsp, cnt2, scale2, stk_offset), result);
6602       } else if (ae == StrIntrinsicNode::UU) {
6603         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
6604         movw(Address(rsp, cnt2, scale2, stk_offset), result);
6605       }
6606       decrement(cnt2);
6607       jccb(Assembler::notZero, COPY_SUBSTR);
6608 
6609       pop(cnt2);
6610       movptr(str2, rsp);  // New substring address
6611     } // non constant
6612 
6613     bind(CHECK_STR);
6614     cmpl(cnt1, stride);
6615     jccb(Assembler::aboveEqual, BIG_STRINGS);
6616 
6617     // Check cross page boundary.
6618     movl(result, str1); // We need only low 32 bits
6619     andl(result, (os::vm_page_size()-1));
6620     cmpl(result, (os::vm_page_size()-16));
6621     jccb(Assembler::belowEqual, BIG_STRINGS);
6622 
6623     subptr(rsp, 16);
6624     int stk_offset = -(1<<scale1);
6625     if (int_cnt2 < 0) { // not constant
6626       push(cnt2);
6627       stk_offset += wordSize;
6628     }
6629     movl(cnt2, cnt1);
6630 
6631     bind(COPY_STR);
6632     if (ae == StrIntrinsicNode::LL) {
6633       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
6634       movb(Address(rsp, cnt2, scale1, stk_offset), result);
6635     } else {
6636       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
6637       movw(Address(rsp, cnt2, scale1, stk_offset), result);
6638     }
6639     decrement(cnt2);
6640     jccb(Assembler::notZero, COPY_STR);
6641 
6642     if (int_cnt2 < 0) { // not constant
6643       pop(cnt2);
6644     }
6645     movptr(str1, rsp);  // New string address
6646 
6647     bind(BIG_STRINGS);
6648     // Load substring.
6649     if (int_cnt2 < 0) { // -1
6650       if (ae == StrIntrinsicNode::UL) {
6651         pmovzxbw(vec, Address(str2, 0));
6652       } else {
6653         movdqu(vec, Address(str2, 0));
6654       }
6655       push(cnt2);       // substr count
6656       push(str2);       // substr addr
6657       push(str1);       // string addr
6658     } else {
6659       // Small (< 8 chars) constant substrings are loaded already.
6660       movl(cnt2, int_cnt2);
6661     }
6662     push(tmp);  // original SP
6663 
6664   } // Finished loading
6665 
6666   //========================================================
6667   // Start search
6668   //
6669 
6670   movptr(result, str1); // string addr
6671 
6672   if (int_cnt2  < 0) {  // Only for non constant substring
6673     jmpb(SCAN_TO_SUBSTR);
6674 
6675     // SP saved at sp+0
6676     // String saved at sp+1*wordSize
6677     // Substr saved at sp+2*wordSize
6678     // Substr count saved at sp+3*wordSize
6679 
6680     // Reload substr for rescan, this code
6681     // is executed only for large substrings (> 8 chars)
6682     bind(RELOAD_SUBSTR);
6683     movptr(str2, Address(rsp, 2*wordSize));
6684     movl(cnt2, Address(rsp, 3*wordSize));
6685     if (ae == StrIntrinsicNode::UL) {
6686       pmovzxbw(vec, Address(str2, 0));
6687     } else {
6688       movdqu(vec, Address(str2, 0));
6689     }
6690     // We came here after the beginning of the substring was
6691     // matched but the rest of it was not so we need to search
6692     // again. Start from the next element after the previous match.
6693     subptr(str1, result); // Restore counter
6694     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6695       shrl(str1, 1);
6696     }
6697     addl(cnt1, str1);
6698     decrementl(cnt1);   // Shift to next element
6699     cmpl(cnt1, cnt2);
6700     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6701 
6702     addptr(result, (1<<scale1));
6703   } // non constant
6704 
6705   // Scan string for start of substr in 16-byte vectors
6706   bind(SCAN_TO_SUBSTR);
6707   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6708   pcmpestri(vec, Address(result, 0), mode);
6709   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6710   subl(cnt1, stride);
6711   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6712   cmpl(cnt1, cnt2);
6713   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6714   addptr(result, 16);
6715 
6716   bind(ADJUST_STR);
6717   cmpl(cnt1, stride); // Do not read beyond string
6718   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6719   // Back-up string to avoid reading beyond string.
6720   lea(result, Address(result, cnt1, scale1, -16));
6721   movl(cnt1, stride);
6722   jmpb(SCAN_TO_SUBSTR);
6723 
6724   // Found a potential substr
6725   bind(FOUND_CANDIDATE);
6726   // After pcmpestri tmp(rcx) contains matched element index
6727 
6728   // Make sure string is still long enough
6729   subl(cnt1, tmp);
6730   cmpl(cnt1, cnt2);
6731   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
6732   // Left less then substring.
6733 
6734   bind(RET_NOT_FOUND);
6735   movl(result, -1);
6736   jmp(CLEANUP);
6737 
6738   bind(FOUND_SUBSTR);
6739   // Compute start addr of substr
6740   lea(result, Address(result, tmp, scale1));
6741   if (int_cnt2 > 0) { // Constant substring
6742     // Repeat search for small substring (< 8 chars)
6743     // from new point without reloading substring.
6744     // Have to check that we don't read beyond string.
6745     cmpl(tmp, stride-int_cnt2);
6746     jccb(Assembler::greater, ADJUST_STR);
6747     // Fall through if matched whole substring.
6748   } else { // non constant
6749     assert(int_cnt2 == -1, "should be != 0");
6750 
6751     addl(tmp, cnt2);
6752     // Found result if we matched whole substring.
6753     cmpl(tmp, stride);
6754     jcc(Assembler::lessEqual, RET_FOUND);
6755 
6756     // Repeat search for small substring (<= 8 chars)
6757     // from new point 'str1' without reloading substring.
6758     cmpl(cnt2, stride);
6759     // Have to check that we don't read beyond string.
6760     jccb(Assembler::lessEqual, ADJUST_STR);
6761 
6762     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
6763     // Compare the rest of substring (> 8 chars).
6764     movptr(str1, result);
6765 
6766     cmpl(tmp, cnt2);
6767     // First 8 chars are already matched.
6768     jccb(Assembler::equal, CHECK_NEXT);
6769 
6770     bind(SCAN_SUBSTR);
6771     pcmpestri(vec, Address(str1, 0), mode);
6772     // Need to reload strings pointers if not matched whole vector
6773     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6774 
6775     bind(CHECK_NEXT);
6776     subl(cnt2, stride);
6777     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
6778     addptr(str1, 16);
6779     if (ae == StrIntrinsicNode::UL) {
6780       addptr(str2, 8);
6781     } else {
6782       addptr(str2, 16);
6783     }
6784     subl(cnt1, stride);
6785     cmpl(cnt2, stride); // Do not read beyond substring
6786     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
6787     // Back-up strings to avoid reading beyond substring.
6788 
6789     if (ae == StrIntrinsicNode::UL) {
6790       lea(str2, Address(str2, cnt2, scale2, -8));
6791       lea(str1, Address(str1, cnt2, scale1, -16));
6792     } else {
6793       lea(str2, Address(str2, cnt2, scale2, -16));
6794       lea(str1, Address(str1, cnt2, scale1, -16));
6795     }
6796     subl(cnt1, cnt2);
6797     movl(cnt2, stride);
6798     addl(cnt1, stride);
6799     bind(CONT_SCAN_SUBSTR);
6800     if (ae == StrIntrinsicNode::UL) {
6801       pmovzxbw(vec, Address(str2, 0));
6802     } else {
6803       movdqu(vec, Address(str2, 0));
6804     }
6805     jmp(SCAN_SUBSTR);
6806 
6807     bind(RET_FOUND_LONG);
6808     movptr(str1, Address(rsp, wordSize));
6809   } // non constant
6810 
6811   bind(RET_FOUND);
6812   // Compute substr offset
6813   subptr(result, str1);
6814   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6815     shrl(result, 1); // index
6816   }
6817   bind(CLEANUP);
6818   pop(rsp); // restore SP
6819 
6820 } // string_indexof
6821 
6822 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
6823                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
6824   ShortBranchVerifier sbv(this);
6825   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6826 
6827   int stride = 8;
6828 
6829   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
6830         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
6831         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
6832         FOUND_SEQ_CHAR, DONE_LABEL;
6833 
6834   movptr(result, str1);
6835   if (UseAVX >= 2) {
6836     cmpl(cnt1, stride);
6837     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
6838     cmpl(cnt1, 2*stride);
6839     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
6840     movdl(vec1, ch);
6841     vpbroadcastw(vec1, vec1, Assembler::AVX_256bit);
6842     vpxor(vec2, vec2);
6843     movl(tmp, cnt1);
6844     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
6845     andl(cnt1,0x0000000F);  //tail count (in chars)
6846 
6847     bind(SCAN_TO_16_CHAR_LOOP);
6848     vmovdqu(vec3, Address(result, 0));
6849     vpcmpeqw(vec3, vec3, vec1, 1);
6850     vptest(vec2, vec3);
6851     jcc(Assembler::carryClear, FOUND_CHAR);
6852     addptr(result, 32);
6853     subl(tmp, 2*stride);
6854     jcc(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
6855     jmp(SCAN_TO_8_CHAR);
6856     bind(SCAN_TO_8_CHAR_INIT);
6857     movdl(vec1, ch);
6858     pshuflw(vec1, vec1, 0x00);
6859     pshufd(vec1, vec1, 0);
6860     pxor(vec2, vec2);
6861   }
6862   bind(SCAN_TO_8_CHAR);
6863   cmpl(cnt1, stride);
6864   if (UseAVX >= 2) {
6865     jcc(Assembler::less, SCAN_TO_CHAR);
6866   } else {
6867     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
6868     movdl(vec1, ch);
6869     pshuflw(vec1, vec1, 0x00);
6870     pshufd(vec1, vec1, 0);
6871     pxor(vec2, vec2);
6872   }
6873   movl(tmp, cnt1);
6874   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
6875   andl(cnt1,0x00000007);  //tail count (in chars)
6876 
6877   bind(SCAN_TO_8_CHAR_LOOP);
6878   movdqu(vec3, Address(result, 0));
6879   pcmpeqw(vec3, vec1);
6880   ptest(vec2, vec3);
6881   jcc(Assembler::carryClear, FOUND_CHAR);
6882   addptr(result, 16);
6883   subl(tmp, stride);
6884   jcc(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
6885   bind(SCAN_TO_CHAR);
6886   testl(cnt1, cnt1);
6887   jcc(Assembler::zero, RET_NOT_FOUND);
6888   bind(SCAN_TO_CHAR_LOOP);
6889   load_unsigned_short(tmp, Address(result, 0));
6890   cmpl(ch, tmp);
6891   jccb(Assembler::equal, FOUND_SEQ_CHAR);
6892   addptr(result, 2);
6893   subl(cnt1, 1);
6894   jccb(Assembler::zero, RET_NOT_FOUND);
6895   jmp(SCAN_TO_CHAR_LOOP);
6896 
6897   bind(RET_NOT_FOUND);
6898   movl(result, -1);
6899   jmpb(DONE_LABEL);
6900 
6901   bind(FOUND_CHAR);
6902   if (UseAVX >= 2) {
6903     vpmovmskb(tmp, vec3);
6904   } else {
6905     pmovmskb(tmp, vec3);
6906   }
6907   bsfl(ch, tmp);
6908   addl(result, ch);
6909 
6910   bind(FOUND_SEQ_CHAR);
6911   subptr(result, str1);
6912   shrl(result, 1);
6913 
6914   bind(DONE_LABEL);
6915 } // string_indexof_char
6916 
6917 // helper function for string_compare
6918 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
6919                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
6920                                         Address::ScaleFactor scale2, Register index, int ae) {
6921   if (ae == StrIntrinsicNode::LL) {
6922     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
6923     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
6924   } else if (ae == StrIntrinsicNode::UU) {
6925     load_unsigned_short(elem1, Address(str1, index, scale, 0));
6926     load_unsigned_short(elem2, Address(str2, index, scale, 0));
6927   } else {
6928     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
6929     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
6930   }
6931 }
6932 
6933 // Compare strings, used for char[] and byte[].
6934 void MacroAssembler::string_compare(Register str1, Register str2,
6935                                     Register cnt1, Register cnt2, Register result,
6936                                     XMMRegister vec1, int ae) {
6937   ShortBranchVerifier sbv(this);
6938   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
6939   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
6940   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
6941   int stride2x2 = 0x40;
6942   Address::ScaleFactor scale = Address::no_scale;
6943   Address::ScaleFactor scale1 = Address::no_scale;
6944   Address::ScaleFactor scale2 = Address::no_scale;
6945 
6946   if (ae != StrIntrinsicNode::LL) {
6947     stride2x2 = 0x20;
6948   }
6949 
6950   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
6951     shrl(cnt2, 1);
6952   }
6953   // Compute the minimum of the string lengths and the
6954   // difference of the string lengths (stack).
6955   // Do the conditional move stuff
6956   movl(result, cnt1);
6957   subl(cnt1, cnt2);
6958   push(cnt1);
6959   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
6960 
6961   // Is the minimum length zero?
6962   testl(cnt2, cnt2);
6963   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
6964   if (ae == StrIntrinsicNode::LL) {
6965     // Load first bytes
6966     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
6967     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
6968   } else if (ae == StrIntrinsicNode::UU) {
6969     // Load first characters
6970     load_unsigned_short(result, Address(str1, 0));
6971     load_unsigned_short(cnt1, Address(str2, 0));
6972   } else {
6973     load_unsigned_byte(result, Address(str1, 0));
6974     load_unsigned_short(cnt1, Address(str2, 0));
6975   }
6976   subl(result, cnt1);
6977   jcc(Assembler::notZero,  POP_LABEL);
6978 
6979   if (ae == StrIntrinsicNode::UU) {
6980     // Divide length by 2 to get number of chars
6981     shrl(cnt2, 1);
6982   }
6983   cmpl(cnt2, 1);
6984   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6985 
6986   // Check if the strings start at the same location and setup scale and stride
6987   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
6988     cmpptr(str1, str2);
6989     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
6990     if (ae == StrIntrinsicNode::LL) {
6991       scale = Address::times_1;
6992       stride = 16;
6993     } else {
6994       scale = Address::times_2;
6995       stride = 8;
6996     }
6997   } else {
6998     scale1 = Address::times_1;
6999     scale2 = Address::times_2;
7000     // scale not used
7001     stride = 8;
7002   }
7003 
7004   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7005     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7006     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7007     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7008     Label COMPARE_TAIL_LONG;
7009     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7010 
7011     int pcmpmask = 0x19;
7012     if (ae == StrIntrinsicNode::LL) {
7013       pcmpmask &= ~0x01;
7014     }
7015 
7016     // Setup to compare 16-chars (32-bytes) vectors,
7017     // start from first character again because it has aligned address.
7018     if (ae == StrIntrinsicNode::LL) {
7019       stride2 = 32;
7020     } else {
7021       stride2 = 16;
7022     }
7023     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7024       adr_stride = stride << scale;
7025     } else {
7026       adr_stride1 = 8;  //stride << scale1;
7027       adr_stride2 = 16; //stride << scale2;
7028     }
7029 
7030     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7031     // rax and rdx are used by pcmpestri as elements counters
7032     movl(result, cnt2);
7033     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7034     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7035 
7036     // fast path : compare first 2 8-char vectors.
7037     bind(COMPARE_16_CHARS);
7038     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7039       movdqu(vec1, Address(str1, 0));
7040     } else {
7041       pmovzxbw(vec1, Address(str1, 0));
7042     }
7043     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7044     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7045 
7046     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7047       movdqu(vec1, Address(str1, adr_stride));
7048       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7049     } else {
7050       pmovzxbw(vec1, Address(str1, adr_stride1));
7051       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7052     }
7053     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7054     addl(cnt1, stride);
7055 
7056     // Compare the characters at index in cnt1
7057     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7058     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7059     subl(result, cnt2);
7060     jmp(POP_LABEL);
7061 
7062     // Setup the registers to start vector comparison loop
7063     bind(COMPARE_WIDE_VECTORS);
7064     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7065       lea(str1, Address(str1, result, scale));
7066       lea(str2, Address(str2, result, scale));
7067     } else {
7068       lea(str1, Address(str1, result, scale1));
7069       lea(str2, Address(str2, result, scale2));
7070     }
7071     subl(result, stride2);
7072     subl(cnt2, stride2);
7073     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7074     negptr(result);
7075 
7076     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7077     bind(COMPARE_WIDE_VECTORS_LOOP);
7078 
7079 #ifdef _LP64
7080     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7081       cmpl(cnt2, stride2x2);
7082       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7083       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7084       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7085 
7086       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7087       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7088         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7089         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7090       } else {
7091         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7092         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7093       }
7094       kortestql(k7, k7);
7095       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7096       addptr(result, stride2x2);  // update since we already compared at this addr
7097       subl(cnt2, stride2x2);      // and sub the size too
7098       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7099 
7100       vpxor(vec1, vec1);
7101       jmpb(COMPARE_WIDE_TAIL);
7102     }//if (VM_Version::supports_avx512vlbw())
7103 #endif // _LP64
7104 
7105 
7106     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7107     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7108       vmovdqu(vec1, Address(str1, result, scale));
7109       vpxor(vec1, Address(str2, result, scale));
7110     } else {
7111       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7112       vpxor(vec1, Address(str2, result, scale2));
7113     }
7114     vptest(vec1, vec1);
7115     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7116     addptr(result, stride2);
7117     subl(cnt2, stride2);
7118     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7119     // clean upper bits of YMM registers
7120     vpxor(vec1, vec1);
7121 
7122     // compare wide vectors tail
7123     bind(COMPARE_WIDE_TAIL);
7124     testptr(result, result);
7125     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7126 
7127     movl(result, stride2);
7128     movl(cnt2, result);
7129     negptr(result);
7130     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7131 
7132     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7133     bind(VECTOR_NOT_EQUAL);
7134     // clean upper bits of YMM registers
7135     vpxor(vec1, vec1);
7136     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7137       lea(str1, Address(str1, result, scale));
7138       lea(str2, Address(str2, result, scale));
7139     } else {
7140       lea(str1, Address(str1, result, scale1));
7141       lea(str2, Address(str2, result, scale2));
7142     }
7143     jmp(COMPARE_16_CHARS);
7144 
7145     // Compare tail chars, length between 1 to 15 chars
7146     bind(COMPARE_TAIL_LONG);
7147     movl(cnt2, result);
7148     cmpl(cnt2, stride);
7149     jcc(Assembler::less, COMPARE_SMALL_STR);
7150 
7151     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7152       movdqu(vec1, Address(str1, 0));
7153     } else {
7154       pmovzxbw(vec1, Address(str1, 0));
7155     }
7156     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7157     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7158     subptr(cnt2, stride);
7159     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7160     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7161       lea(str1, Address(str1, result, scale));
7162       lea(str2, Address(str2, result, scale));
7163     } else {
7164       lea(str1, Address(str1, result, scale1));
7165       lea(str2, Address(str2, result, scale2));
7166     }
7167     negptr(cnt2);
7168     jmpb(WHILE_HEAD_LABEL);
7169 
7170     bind(COMPARE_SMALL_STR);
7171   } else if (UseSSE42Intrinsics) {
7172     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7173     int pcmpmask = 0x19;
7174     // Setup to compare 8-char (16-byte) vectors,
7175     // start from first character again because it has aligned address.
7176     movl(result, cnt2);
7177     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7178     if (ae == StrIntrinsicNode::LL) {
7179       pcmpmask &= ~0x01;
7180     }
7181     jcc(Assembler::zero, COMPARE_TAIL);
7182     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7183       lea(str1, Address(str1, result, scale));
7184       lea(str2, Address(str2, result, scale));
7185     } else {
7186       lea(str1, Address(str1, result, scale1));
7187       lea(str2, Address(str2, result, scale2));
7188     }
7189     negptr(result);
7190 
7191     // pcmpestri
7192     //   inputs:
7193     //     vec1- substring
7194     //     rax - negative string length (elements count)
7195     //     mem - scanned string
7196     //     rdx - string length (elements count)
7197     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7198     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7199     //   outputs:
7200     //     rcx - first mismatched element index
7201     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7202 
7203     bind(COMPARE_WIDE_VECTORS);
7204     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7205       movdqu(vec1, Address(str1, result, scale));
7206       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7207     } else {
7208       pmovzxbw(vec1, Address(str1, result, scale1));
7209       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7210     }
7211     // After pcmpestri cnt1(rcx) contains mismatched element index
7212 
7213     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7214     addptr(result, stride);
7215     subptr(cnt2, stride);
7216     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7217 
7218     // compare wide vectors tail
7219     testptr(result, result);
7220     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7221 
7222     movl(cnt2, stride);
7223     movl(result, stride);
7224     negptr(result);
7225     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7226       movdqu(vec1, Address(str1, result, scale));
7227       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7228     } else {
7229       pmovzxbw(vec1, Address(str1, result, scale1));
7230       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7231     }
7232     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7233 
7234     // Mismatched characters in the vectors
7235     bind(VECTOR_NOT_EQUAL);
7236     addptr(cnt1, result);
7237     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7238     subl(result, cnt2);
7239     jmpb(POP_LABEL);
7240 
7241     bind(COMPARE_TAIL); // limit is zero
7242     movl(cnt2, result);
7243     // Fallthru to tail compare
7244   }
7245   // Shift str2 and str1 to the end of the arrays, negate min
7246   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7247     lea(str1, Address(str1, cnt2, scale));
7248     lea(str2, Address(str2, cnt2, scale));
7249   } else {
7250     lea(str1, Address(str1, cnt2, scale1));
7251     lea(str2, Address(str2, cnt2, scale2));
7252   }
7253   decrementl(cnt2);  // first character was compared already
7254   negptr(cnt2);
7255 
7256   // Compare the rest of the elements
7257   bind(WHILE_HEAD_LABEL);
7258   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7259   subl(result, cnt1);
7260   jccb(Assembler::notZero, POP_LABEL);
7261   increment(cnt2);
7262   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7263 
7264   // Strings are equal up to min length.  Return the length difference.
7265   bind(LENGTH_DIFF_LABEL);
7266   pop(result);
7267   if (ae == StrIntrinsicNode::UU) {
7268     // Divide diff by 2 to get number of chars
7269     sarl(result, 1);
7270   }
7271   jmpb(DONE_LABEL);
7272 
7273 #ifdef _LP64
7274   if (VM_Version::supports_avx512vlbw()) {
7275 
7276     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7277 
7278     kmovql(cnt1, k7);
7279     notq(cnt1);
7280     bsfq(cnt2, cnt1);
7281     if (ae != StrIntrinsicNode::LL) {
7282       // Divide diff by 2 to get number of chars
7283       sarl(cnt2, 1);
7284     }
7285     addq(result, cnt2);
7286     if (ae == StrIntrinsicNode::LL) {
7287       load_unsigned_byte(cnt1, Address(str2, result));
7288       load_unsigned_byte(result, Address(str1, result));
7289     } else if (ae == StrIntrinsicNode::UU) {
7290       load_unsigned_short(cnt1, Address(str2, result, scale));
7291       load_unsigned_short(result, Address(str1, result, scale));
7292     } else {
7293       load_unsigned_short(cnt1, Address(str2, result, scale2));
7294       load_unsigned_byte(result, Address(str1, result, scale1));
7295     }
7296     subl(result, cnt1);
7297     jmpb(POP_LABEL);
7298   }//if (VM_Version::supports_avx512vlbw())
7299 #endif // _LP64
7300 
7301   // Discard the stored length difference
7302   bind(POP_LABEL);
7303   pop(cnt1);
7304 
7305   // That's it
7306   bind(DONE_LABEL);
7307   if(ae == StrIntrinsicNode::UL) {
7308     negl(result);
7309   }
7310 
7311 }
7312 
7313 // Search for Non-ASCII character (Negative byte value) in a byte array,
7314 // return true if it has any and false otherwise.
7315 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7316 //   @HotSpotIntrinsicCandidate
7317 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7318 //     for (int i = off; i < off + len; i++) {
7319 //       if (ba[i] < 0) {
7320 //         return true;
7321 //       }
7322 //     }
7323 //     return false;
7324 //   }
7325 void MacroAssembler::has_negatives(Register ary1, Register len,
7326   Register result, Register tmp1,
7327   XMMRegister vec1, XMMRegister vec2) {
7328   // rsi: byte array
7329   // rcx: len
7330   // rax: result
7331   ShortBranchVerifier sbv(this);
7332   assert_different_registers(ary1, len, result, tmp1);
7333   assert_different_registers(vec1, vec2);
7334   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7335 
7336   // len == 0
7337   testl(len, len);
7338   jcc(Assembler::zero, FALSE_LABEL);
7339 
7340   if ((UseAVX > 2) && // AVX512
7341     VM_Version::supports_avx512vlbw() &&
7342     VM_Version::supports_bmi2()) {
7343 
7344     Label test_64_loop, test_tail;
7345     Register tmp3_aliased = len;
7346 
7347     movl(tmp1, len);
7348     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7349 
7350     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7351     andl(len, ~(64 - 1));    // vector count (in chars)
7352     jccb(Assembler::zero, test_tail);
7353 
7354     lea(ary1, Address(ary1, len, Address::times_1));
7355     negptr(len);
7356 
7357     bind(test_64_loop);
7358     // Check whether our 64 elements of size byte contain negatives
7359     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7360     kortestql(k2, k2);
7361     jcc(Assembler::notZero, TRUE_LABEL);
7362 
7363     addptr(len, 64);
7364     jccb(Assembler::notZero, test_64_loop);
7365 
7366 
7367     bind(test_tail);
7368     // bail out when there is nothing to be done
7369     testl(tmp1, -1);
7370     jcc(Assembler::zero, FALSE_LABEL);
7371 
7372     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7373 #ifdef _LP64
7374     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7375     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7376     notq(tmp3_aliased);
7377     kmovql(k3, tmp3_aliased);
7378 #else
7379     Label k_init;
7380     jmp(k_init);
7381 
7382     // We could not read 64-bits from a general purpose register thus we move
7383     // data required to compose 64 1's to the instruction stream
7384     // We emit 64 byte wide series of elements from 0..63 which later on would
7385     // be used as a compare targets with tail count contained in tmp1 register.
7386     // Result would be a k register having tmp1 consecutive number or 1
7387     // counting from least significant bit.
7388     address tmp = pc();
7389     emit_int64(0x0706050403020100);
7390     emit_int64(0x0F0E0D0C0B0A0908);
7391     emit_int64(0x1716151413121110);
7392     emit_int64(0x1F1E1D1C1B1A1918);
7393     emit_int64(0x2726252423222120);
7394     emit_int64(0x2F2E2D2C2B2A2928);
7395     emit_int64(0x3736353433323130);
7396     emit_int64(0x3F3E3D3C3B3A3938);
7397 
7398     bind(k_init);
7399     lea(len, InternalAddress(tmp));
7400     // create mask to test for negative byte inside a vector
7401     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7402     evpcmpgtb(k3, vec1, Address(len, 0), Assembler::AVX_512bit);
7403 
7404 #endif
7405     evpcmpgtb(k2, k3, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7406     ktestq(k2, k3);
7407     jcc(Assembler::notZero, TRUE_LABEL);
7408 
7409     jmp(FALSE_LABEL);
7410   } else {
7411     movl(result, len); // copy
7412 
7413     if (UseAVX == 2 && UseSSE >= 2) {
7414       // With AVX2, use 32-byte vector compare
7415       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7416 
7417       // Compare 32-byte vectors
7418       andl(result, 0x0000001f);  //   tail count (in bytes)
7419       andl(len, 0xffffffe0);   // vector count (in bytes)
7420       jccb(Assembler::zero, COMPARE_TAIL);
7421 
7422       lea(ary1, Address(ary1, len, Address::times_1));
7423       negptr(len);
7424 
7425       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7426       movdl(vec2, tmp1);
7427       vpbroadcastd(vec2, vec2, Assembler::AVX_256bit);
7428 
7429       bind(COMPARE_WIDE_VECTORS);
7430       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7431       vptest(vec1, vec2);
7432       jccb(Assembler::notZero, TRUE_LABEL);
7433       addptr(len, 32);
7434       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7435 
7436       testl(result, result);
7437       jccb(Assembler::zero, FALSE_LABEL);
7438 
7439       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7440       vptest(vec1, vec2);
7441       jccb(Assembler::notZero, TRUE_LABEL);
7442       jmpb(FALSE_LABEL);
7443 
7444       bind(COMPARE_TAIL); // len is zero
7445       movl(len, result);
7446       // Fallthru to tail compare
7447     } else if (UseSSE42Intrinsics) {
7448       // With SSE4.2, use double quad vector compare
7449       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7450 
7451       // Compare 16-byte vectors
7452       andl(result, 0x0000000f);  //   tail count (in bytes)
7453       andl(len, 0xfffffff0);   // vector count (in bytes)
7454       jcc(Assembler::zero, COMPARE_TAIL);
7455 
7456       lea(ary1, Address(ary1, len, Address::times_1));
7457       negptr(len);
7458 
7459       movl(tmp1, 0x80808080);
7460       movdl(vec2, tmp1);
7461       pshufd(vec2, vec2, 0);
7462 
7463       bind(COMPARE_WIDE_VECTORS);
7464       movdqu(vec1, Address(ary1, len, Address::times_1));
7465       ptest(vec1, vec2);
7466       jcc(Assembler::notZero, TRUE_LABEL);
7467       addptr(len, 16);
7468       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7469 
7470       testl(result, result);
7471       jcc(Assembler::zero, FALSE_LABEL);
7472 
7473       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7474       ptest(vec1, vec2);
7475       jccb(Assembler::notZero, TRUE_LABEL);
7476       jmpb(FALSE_LABEL);
7477 
7478       bind(COMPARE_TAIL); // len is zero
7479       movl(len, result);
7480       // Fallthru to tail compare
7481     }
7482   }
7483   // Compare 4-byte vectors
7484   andl(len, 0xfffffffc); // vector count (in bytes)
7485   jccb(Assembler::zero, COMPARE_CHAR);
7486 
7487   lea(ary1, Address(ary1, len, Address::times_1));
7488   negptr(len);
7489 
7490   bind(COMPARE_VECTORS);
7491   movl(tmp1, Address(ary1, len, Address::times_1));
7492   andl(tmp1, 0x80808080);
7493   jccb(Assembler::notZero, TRUE_LABEL);
7494   addptr(len, 4);
7495   jcc(Assembler::notZero, COMPARE_VECTORS);
7496 
7497   // Compare trailing char (final 2 bytes), if any
7498   bind(COMPARE_CHAR);
7499   testl(result, 0x2);   // tail  char
7500   jccb(Assembler::zero, COMPARE_BYTE);
7501   load_unsigned_short(tmp1, Address(ary1, 0));
7502   andl(tmp1, 0x00008080);
7503   jccb(Assembler::notZero, TRUE_LABEL);
7504   subptr(result, 2);
7505   lea(ary1, Address(ary1, 2));
7506 
7507   bind(COMPARE_BYTE);
7508   testl(result, 0x1);   // tail  byte
7509   jccb(Assembler::zero, FALSE_LABEL);
7510   load_unsigned_byte(tmp1, Address(ary1, 0));
7511   andl(tmp1, 0x00000080);
7512   jccb(Assembler::notEqual, TRUE_LABEL);
7513   jmpb(FALSE_LABEL);
7514 
7515   bind(TRUE_LABEL);
7516   movl(result, 1);   // return true
7517   jmpb(DONE);
7518 
7519   bind(FALSE_LABEL);
7520   xorl(result, result); // return false
7521 
7522   // That's it
7523   bind(DONE);
7524   if (UseAVX >= 2 && UseSSE >= 2) {
7525     // clean upper bits of YMM registers
7526     vpxor(vec1, vec1);
7527     vpxor(vec2, vec2);
7528   }
7529 }
7530 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
7531 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
7532                                    Register limit, Register result, Register chr,
7533                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
7534   ShortBranchVerifier sbv(this);
7535   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
7536 
7537   int length_offset  = arrayOopDesc::length_offset_in_bytes();
7538   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
7539 
7540   if (is_array_equ) {
7541     // Check the input args
7542     cmpoop(ary1, ary2);
7543     jcc(Assembler::equal, TRUE_LABEL);
7544 
7545     // Need additional checks for arrays_equals.
7546     testptr(ary1, ary1);
7547     jcc(Assembler::zero, FALSE_LABEL);
7548     testptr(ary2, ary2);
7549     jcc(Assembler::zero, FALSE_LABEL);
7550 
7551     // Check the lengths
7552     movl(limit, Address(ary1, length_offset));
7553     cmpl(limit, Address(ary2, length_offset));
7554     jcc(Assembler::notEqual, FALSE_LABEL);
7555   }
7556 
7557   // count == 0
7558   testl(limit, limit);
7559   jcc(Assembler::zero, TRUE_LABEL);
7560 
7561   if (is_array_equ) {
7562     // Load array address
7563     lea(ary1, Address(ary1, base_offset));
7564     lea(ary2, Address(ary2, base_offset));
7565   }
7566 
7567   if (is_array_equ && is_char) {
7568     // arrays_equals when used for char[].
7569     shll(limit, 1);      // byte count != 0
7570   }
7571   movl(result, limit); // copy
7572 
7573   if (UseAVX >= 2) {
7574     // With AVX2, use 32-byte vector compare
7575     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7576 
7577     // Compare 32-byte vectors
7578     andl(result, 0x0000001f);  //   tail count (in bytes)
7579     andl(limit, 0xffffffe0);   // vector count (in bytes)
7580     jcc(Assembler::zero, COMPARE_TAIL);
7581 
7582     lea(ary1, Address(ary1, limit, Address::times_1));
7583     lea(ary2, Address(ary2, limit, Address::times_1));
7584     negptr(limit);
7585 
7586     bind(COMPARE_WIDE_VECTORS);
7587 
7588 #ifdef _LP64
7589     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7590       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
7591 
7592       cmpl(limit, -64);
7593       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7594 
7595       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7596 
7597       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
7598       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
7599       kortestql(k7, k7);
7600       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
7601       addptr(limit, 64);  // update since we already compared at this addr
7602       cmpl(limit, -64);
7603       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7604 
7605       // At this point we may still need to compare -limit+result bytes.
7606       // We could execute the next two instruction and just continue via non-wide path:
7607       //  cmpl(limit, 0);
7608       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
7609       // But since we stopped at the points ary{1,2}+limit which are
7610       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
7611       // (|limit| <= 32 and result < 32),
7612       // we may just compare the last 64 bytes.
7613       //
7614       addptr(result, -64);   // it is safe, bc we just came from this area
7615       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
7616       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
7617       kortestql(k7, k7);
7618       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
7619 
7620       jmp(TRUE_LABEL);
7621 
7622       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7623 
7624     }//if (VM_Version::supports_avx512vlbw())
7625 #endif //_LP64
7626 
7627     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
7628     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
7629     vpxor(vec1, vec2);
7630 
7631     vptest(vec1, vec1);
7632     jcc(Assembler::notZero, FALSE_LABEL);
7633     addptr(limit, 32);
7634     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7635 
7636     testl(result, result);
7637     jcc(Assembler::zero, TRUE_LABEL);
7638 
7639     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7640     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
7641     vpxor(vec1, vec2);
7642 
7643     vptest(vec1, vec1);
7644     jccb(Assembler::notZero, FALSE_LABEL);
7645     jmpb(TRUE_LABEL);
7646 
7647     bind(COMPARE_TAIL); // limit is zero
7648     movl(limit, result);
7649     // Fallthru to tail compare
7650   } else if (UseSSE42Intrinsics) {
7651     // With SSE4.2, use double quad vector compare
7652     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7653 
7654     // Compare 16-byte vectors
7655     andl(result, 0x0000000f);  //   tail count (in bytes)
7656     andl(limit, 0xfffffff0);   // vector count (in bytes)
7657     jcc(Assembler::zero, COMPARE_TAIL);
7658 
7659     lea(ary1, Address(ary1, limit, Address::times_1));
7660     lea(ary2, Address(ary2, limit, Address::times_1));
7661     negptr(limit);
7662 
7663     bind(COMPARE_WIDE_VECTORS);
7664     movdqu(vec1, Address(ary1, limit, Address::times_1));
7665     movdqu(vec2, Address(ary2, limit, Address::times_1));
7666     pxor(vec1, vec2);
7667 
7668     ptest(vec1, vec1);
7669     jcc(Assembler::notZero, FALSE_LABEL);
7670     addptr(limit, 16);
7671     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7672 
7673     testl(result, result);
7674     jcc(Assembler::zero, TRUE_LABEL);
7675 
7676     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7677     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
7678     pxor(vec1, vec2);
7679 
7680     ptest(vec1, vec1);
7681     jccb(Assembler::notZero, FALSE_LABEL);
7682     jmpb(TRUE_LABEL);
7683 
7684     bind(COMPARE_TAIL); // limit is zero
7685     movl(limit, result);
7686     // Fallthru to tail compare
7687   }
7688 
7689   // Compare 4-byte vectors
7690   andl(limit, 0xfffffffc); // vector count (in bytes)
7691   jccb(Assembler::zero, COMPARE_CHAR);
7692 
7693   lea(ary1, Address(ary1, limit, Address::times_1));
7694   lea(ary2, Address(ary2, limit, Address::times_1));
7695   negptr(limit);
7696 
7697   bind(COMPARE_VECTORS);
7698   movl(chr, Address(ary1, limit, Address::times_1));
7699   cmpl(chr, Address(ary2, limit, Address::times_1));
7700   jccb(Assembler::notEqual, FALSE_LABEL);
7701   addptr(limit, 4);
7702   jcc(Assembler::notZero, COMPARE_VECTORS);
7703 
7704   // Compare trailing char (final 2 bytes), if any
7705   bind(COMPARE_CHAR);
7706   testl(result, 0x2);   // tail  char
7707   jccb(Assembler::zero, COMPARE_BYTE);
7708   load_unsigned_short(chr, Address(ary1, 0));
7709   load_unsigned_short(limit, Address(ary2, 0));
7710   cmpl(chr, limit);
7711   jccb(Assembler::notEqual, FALSE_LABEL);
7712 
7713   if (is_array_equ && is_char) {
7714     bind(COMPARE_BYTE);
7715   } else {
7716     lea(ary1, Address(ary1, 2));
7717     lea(ary2, Address(ary2, 2));
7718 
7719     bind(COMPARE_BYTE);
7720     testl(result, 0x1);   // tail  byte
7721     jccb(Assembler::zero, TRUE_LABEL);
7722     load_unsigned_byte(chr, Address(ary1, 0));
7723     load_unsigned_byte(limit, Address(ary2, 0));
7724     cmpl(chr, limit);
7725     jccb(Assembler::notEqual, FALSE_LABEL);
7726   }
7727   bind(TRUE_LABEL);
7728   movl(result, 1);   // return true
7729   jmpb(DONE);
7730 
7731   bind(FALSE_LABEL);
7732   xorl(result, result); // return false
7733 
7734   // That's it
7735   bind(DONE);
7736   if (UseAVX >= 2) {
7737     // clean upper bits of YMM registers
7738     vpxor(vec1, vec1);
7739     vpxor(vec2, vec2);
7740   }
7741 }
7742 
7743 #endif
7744 
7745 void MacroAssembler::generate_fill(BasicType t, bool aligned,
7746                                    Register to, Register value, Register count,
7747                                    Register rtmp, XMMRegister xtmp) {
7748   ShortBranchVerifier sbv(this);
7749   assert_different_registers(to, value, count, rtmp);
7750   Label L_exit;
7751   Label L_fill_2_bytes, L_fill_4_bytes;
7752 
7753   int shift = -1;
7754   switch (t) {
7755     case T_BYTE:
7756       shift = 2;
7757       break;
7758     case T_SHORT:
7759       shift = 1;
7760       break;
7761     case T_INT:
7762       shift = 0;
7763       break;
7764     default: ShouldNotReachHere();
7765   }
7766 
7767   if (t == T_BYTE) {
7768     andl(value, 0xff);
7769     movl(rtmp, value);
7770     shll(rtmp, 8);
7771     orl(value, rtmp);
7772   }
7773   if (t == T_SHORT) {
7774     andl(value, 0xffff);
7775   }
7776   if (t == T_BYTE || t == T_SHORT) {
7777     movl(rtmp, value);
7778     shll(rtmp, 16);
7779     orl(value, rtmp);
7780   }
7781 
7782   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
7783   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
7784   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
7785     Label L_skip_align2;
7786     // align source address at 4 bytes address boundary
7787     if (t == T_BYTE) {
7788       Label L_skip_align1;
7789       // One byte misalignment happens only for byte arrays
7790       testptr(to, 1);
7791       jccb(Assembler::zero, L_skip_align1);
7792       movb(Address(to, 0), value);
7793       increment(to);
7794       decrement(count);
7795       BIND(L_skip_align1);
7796     }
7797     // Two bytes misalignment happens only for byte and short (char) arrays
7798     testptr(to, 2);
7799     jccb(Assembler::zero, L_skip_align2);
7800     movw(Address(to, 0), value);
7801     addptr(to, 2);
7802     subl(count, 1<<(shift-1));
7803     BIND(L_skip_align2);
7804   }
7805   if (UseSSE < 2) {
7806     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7807     // Fill 32-byte chunks
7808     subl(count, 8 << shift);
7809     jcc(Assembler::less, L_check_fill_8_bytes);
7810     align(16);
7811 
7812     BIND(L_fill_32_bytes_loop);
7813 
7814     for (int i = 0; i < 32; i += 4) {
7815       movl(Address(to, i), value);
7816     }
7817 
7818     addptr(to, 32);
7819     subl(count, 8 << shift);
7820     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7821     BIND(L_check_fill_8_bytes);
7822     addl(count, 8 << shift);
7823     jccb(Assembler::zero, L_exit);
7824     jmpb(L_fill_8_bytes);
7825 
7826     //
7827     // length is too short, just fill qwords
7828     //
7829     BIND(L_fill_8_bytes_loop);
7830     movl(Address(to, 0), value);
7831     movl(Address(to, 4), value);
7832     addptr(to, 8);
7833     BIND(L_fill_8_bytes);
7834     subl(count, 1 << (shift + 1));
7835     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7836     // fall through to fill 4 bytes
7837   } else {
7838     Label L_fill_32_bytes;
7839     if (!UseUnalignedLoadStores) {
7840       // align to 8 bytes, we know we are 4 byte aligned to start
7841       testptr(to, 4);
7842       jccb(Assembler::zero, L_fill_32_bytes);
7843       movl(Address(to, 0), value);
7844       addptr(to, 4);
7845       subl(count, 1<<shift);
7846     }
7847     BIND(L_fill_32_bytes);
7848     {
7849       assert( UseSSE >= 2, "supported cpu only" );
7850       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7851       movdl(xtmp, value);
7852       if (UseAVX > 2 && UseUnalignedLoadStores) {
7853         // Fill 64-byte chunks
7854         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7855         vpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
7856 
7857         subl(count, 16 << shift);
7858         jcc(Assembler::less, L_check_fill_32_bytes);
7859         align(16);
7860 
7861         BIND(L_fill_64_bytes_loop);
7862         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
7863         addptr(to, 64);
7864         subl(count, 16 << shift);
7865         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7866 
7867         BIND(L_check_fill_32_bytes);
7868         addl(count, 8 << shift);
7869         jccb(Assembler::less, L_check_fill_8_bytes);
7870         vmovdqu(Address(to, 0), xtmp);
7871         addptr(to, 32);
7872         subl(count, 8 << shift);
7873 
7874         BIND(L_check_fill_8_bytes);
7875       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
7876         // Fill 64-byte chunks
7877         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7878         vpbroadcastd(xtmp, xtmp, Assembler::AVX_256bit);
7879 
7880         subl(count, 16 << shift);
7881         jcc(Assembler::less, L_check_fill_32_bytes);
7882         align(16);
7883 
7884         BIND(L_fill_64_bytes_loop);
7885         vmovdqu(Address(to, 0), xtmp);
7886         vmovdqu(Address(to, 32), xtmp);
7887         addptr(to, 64);
7888         subl(count, 16 << shift);
7889         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7890 
7891         BIND(L_check_fill_32_bytes);
7892         addl(count, 8 << shift);
7893         jccb(Assembler::less, L_check_fill_8_bytes);
7894         vmovdqu(Address(to, 0), xtmp);
7895         addptr(to, 32);
7896         subl(count, 8 << shift);
7897 
7898         BIND(L_check_fill_8_bytes);
7899         // clean upper bits of YMM registers
7900         movdl(xtmp, value);
7901         pshufd(xtmp, xtmp, 0);
7902       } else {
7903         // Fill 32-byte chunks
7904         pshufd(xtmp, xtmp, 0);
7905 
7906         subl(count, 8 << shift);
7907         jcc(Assembler::less, L_check_fill_8_bytes);
7908         align(16);
7909 
7910         BIND(L_fill_32_bytes_loop);
7911 
7912         if (UseUnalignedLoadStores) {
7913           movdqu(Address(to, 0), xtmp);
7914           movdqu(Address(to, 16), xtmp);
7915         } else {
7916           movq(Address(to, 0), xtmp);
7917           movq(Address(to, 8), xtmp);
7918           movq(Address(to, 16), xtmp);
7919           movq(Address(to, 24), xtmp);
7920         }
7921 
7922         addptr(to, 32);
7923         subl(count, 8 << shift);
7924         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7925 
7926         BIND(L_check_fill_8_bytes);
7927       }
7928       addl(count, 8 << shift);
7929       jccb(Assembler::zero, L_exit);
7930       jmpb(L_fill_8_bytes);
7931 
7932       //
7933       // length is too short, just fill qwords
7934       //
7935       BIND(L_fill_8_bytes_loop);
7936       movq(Address(to, 0), xtmp);
7937       addptr(to, 8);
7938       BIND(L_fill_8_bytes);
7939       subl(count, 1 << (shift + 1));
7940       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7941     }
7942   }
7943   // fill trailing 4 bytes
7944   BIND(L_fill_4_bytes);
7945   testl(count, 1<<shift);
7946   jccb(Assembler::zero, L_fill_2_bytes);
7947   movl(Address(to, 0), value);
7948   if (t == T_BYTE || t == T_SHORT) {
7949     Label L_fill_byte;
7950     addptr(to, 4);
7951     BIND(L_fill_2_bytes);
7952     // fill trailing 2 bytes
7953     testl(count, 1<<(shift-1));
7954     jccb(Assembler::zero, L_fill_byte);
7955     movw(Address(to, 0), value);
7956     if (t == T_BYTE) {
7957       addptr(to, 2);
7958       BIND(L_fill_byte);
7959       // fill trailing byte
7960       testl(count, 1);
7961       jccb(Assembler::zero, L_exit);
7962       movb(Address(to, 0), value);
7963     } else {
7964       BIND(L_fill_byte);
7965     }
7966   } else {
7967     BIND(L_fill_2_bytes);
7968   }
7969   BIND(L_exit);
7970 }
7971 
7972 // encode char[] to byte[] in ISO_8859_1
7973    //@HotSpotIntrinsicCandidate
7974    //private static int implEncodeISOArray(byte[] sa, int sp,
7975    //byte[] da, int dp, int len) {
7976    //  int i = 0;
7977    //  for (; i < len; i++) {
7978    //    char c = StringUTF16.getChar(sa, sp++);
7979    //    if (c > '\u00FF')
7980    //      break;
7981    //    da[dp++] = (byte)c;
7982    //  }
7983    //  return i;
7984    //}
7985 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
7986   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
7987   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
7988   Register tmp5, Register result) {
7989 
7990   // rsi: src
7991   // rdi: dst
7992   // rdx: len
7993   // rcx: tmp5
7994   // rax: result
7995   ShortBranchVerifier sbv(this);
7996   assert_different_registers(src, dst, len, tmp5, result);
7997   Label L_done, L_copy_1_char, L_copy_1_char_exit;
7998 
7999   // set result
8000   xorl(result, result);
8001   // check for zero length
8002   testl(len, len);
8003   jcc(Assembler::zero, L_done);
8004 
8005   movl(result, len);
8006 
8007   // Setup pointers
8008   lea(src, Address(src, len, Address::times_2)); // char[]
8009   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8010   negptr(len);
8011 
8012   if (UseSSE42Intrinsics || UseAVX >= 2) {
8013     Label L_copy_8_chars, L_copy_8_chars_exit;
8014     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8015 
8016     if (UseAVX >= 2) {
8017       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8018       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8019       movdl(tmp1Reg, tmp5);
8020       vpbroadcastd(tmp1Reg, tmp1Reg, Assembler::AVX_256bit);
8021       jmp(L_chars_32_check);
8022 
8023       bind(L_copy_32_chars);
8024       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8025       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8026       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8027       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8028       jccb(Assembler::notZero, L_copy_32_chars_exit);
8029       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8030       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8031       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8032 
8033       bind(L_chars_32_check);
8034       addptr(len, 32);
8035       jcc(Assembler::lessEqual, L_copy_32_chars);
8036 
8037       bind(L_copy_32_chars_exit);
8038       subptr(len, 16);
8039       jccb(Assembler::greater, L_copy_16_chars_exit);
8040 
8041     } else if (UseSSE42Intrinsics) {
8042       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8043       movdl(tmp1Reg, tmp5);
8044       pshufd(tmp1Reg, tmp1Reg, 0);
8045       jmpb(L_chars_16_check);
8046     }
8047 
8048     bind(L_copy_16_chars);
8049     if (UseAVX >= 2) {
8050       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8051       vptest(tmp2Reg, tmp1Reg);
8052       jcc(Assembler::notZero, L_copy_16_chars_exit);
8053       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8054       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8055     } else {
8056       if (UseAVX > 0) {
8057         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8058         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8059         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8060       } else {
8061         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8062         por(tmp2Reg, tmp3Reg);
8063         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8064         por(tmp2Reg, tmp4Reg);
8065       }
8066       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8067       jccb(Assembler::notZero, L_copy_16_chars_exit);
8068       packuswb(tmp3Reg, tmp4Reg);
8069     }
8070     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8071 
8072     bind(L_chars_16_check);
8073     addptr(len, 16);
8074     jcc(Assembler::lessEqual, L_copy_16_chars);
8075 
8076     bind(L_copy_16_chars_exit);
8077     if (UseAVX >= 2) {
8078       // clean upper bits of YMM registers
8079       vpxor(tmp2Reg, tmp2Reg);
8080       vpxor(tmp3Reg, tmp3Reg);
8081       vpxor(tmp4Reg, tmp4Reg);
8082       movdl(tmp1Reg, tmp5);
8083       pshufd(tmp1Reg, tmp1Reg, 0);
8084     }
8085     subptr(len, 8);
8086     jccb(Assembler::greater, L_copy_8_chars_exit);
8087 
8088     bind(L_copy_8_chars);
8089     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8090     ptest(tmp3Reg, tmp1Reg);
8091     jccb(Assembler::notZero, L_copy_8_chars_exit);
8092     packuswb(tmp3Reg, tmp1Reg);
8093     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8094     addptr(len, 8);
8095     jccb(Assembler::lessEqual, L_copy_8_chars);
8096 
8097     bind(L_copy_8_chars_exit);
8098     subptr(len, 8);
8099     jccb(Assembler::zero, L_done);
8100   }
8101 
8102   bind(L_copy_1_char);
8103   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8104   testl(tmp5, 0xff00);      // check if Unicode char
8105   jccb(Assembler::notZero, L_copy_1_char_exit);
8106   movb(Address(dst, len, Address::times_1, 0), tmp5);
8107   addptr(len, 1);
8108   jccb(Assembler::less, L_copy_1_char);
8109 
8110   bind(L_copy_1_char_exit);
8111   addptr(result, len); // len is negative count of not processed elements
8112 
8113   bind(L_done);
8114 }
8115 
8116 #ifdef _LP64
8117 /**
8118  * Helper for multiply_to_len().
8119  */
8120 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8121   addq(dest_lo, src1);
8122   adcq(dest_hi, 0);
8123   addq(dest_lo, src2);
8124   adcq(dest_hi, 0);
8125 }
8126 
8127 /**
8128  * Multiply 64 bit by 64 bit first loop.
8129  */
8130 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8131                                            Register y, Register y_idx, Register z,
8132                                            Register carry, Register product,
8133                                            Register idx, Register kdx) {
8134   //
8135   //  jlong carry, x[], y[], z[];
8136   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8137   //    huge_128 product = y[idx] * x[xstart] + carry;
8138   //    z[kdx] = (jlong)product;
8139   //    carry  = (jlong)(product >>> 64);
8140   //  }
8141   //  z[xstart] = carry;
8142   //
8143 
8144   Label L_first_loop, L_first_loop_exit;
8145   Label L_one_x, L_one_y, L_multiply;
8146 
8147   decrementl(xstart);
8148   jcc(Assembler::negative, L_one_x);
8149 
8150   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8151   rorq(x_xstart, 32); // convert big-endian to little-endian
8152 
8153   bind(L_first_loop);
8154   decrementl(idx);
8155   jcc(Assembler::negative, L_first_loop_exit);
8156   decrementl(idx);
8157   jcc(Assembler::negative, L_one_y);
8158   movq(y_idx, Address(y, idx, Address::times_4,  0));
8159   rorq(y_idx, 32); // convert big-endian to little-endian
8160   bind(L_multiply);
8161   movq(product, x_xstart);
8162   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8163   addq(product, carry);
8164   adcq(rdx, 0);
8165   subl(kdx, 2);
8166   movl(Address(z, kdx, Address::times_4,  4), product);
8167   shrq(product, 32);
8168   movl(Address(z, kdx, Address::times_4,  0), product);
8169   movq(carry, rdx);
8170   jmp(L_first_loop);
8171 
8172   bind(L_one_y);
8173   movl(y_idx, Address(y,  0));
8174   jmp(L_multiply);
8175 
8176   bind(L_one_x);
8177   movl(x_xstart, Address(x,  0));
8178   jmp(L_first_loop);
8179 
8180   bind(L_first_loop_exit);
8181 }
8182 
8183 /**
8184  * Multiply 64 bit by 64 bit and add 128 bit.
8185  */
8186 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8187                                             Register yz_idx, Register idx,
8188                                             Register carry, Register product, int offset) {
8189   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8190   //     z[kdx] = (jlong)product;
8191 
8192   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8193   rorq(yz_idx, 32); // convert big-endian to little-endian
8194   movq(product, x_xstart);
8195   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8196   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8197   rorq(yz_idx, 32); // convert big-endian to little-endian
8198 
8199   add2_with_carry(rdx, product, carry, yz_idx);
8200 
8201   movl(Address(z, idx, Address::times_4,  offset+4), product);
8202   shrq(product, 32);
8203   movl(Address(z, idx, Address::times_4,  offset), product);
8204 
8205 }
8206 
8207 /**
8208  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8209  */
8210 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8211                                              Register yz_idx, Register idx, Register jdx,
8212                                              Register carry, Register product,
8213                                              Register carry2) {
8214   //   jlong carry, x[], y[], z[];
8215   //   int kdx = ystart+1;
8216   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8217   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8218   //     z[kdx+idx+1] = (jlong)product;
8219   //     jlong carry2  = (jlong)(product >>> 64);
8220   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8221   //     z[kdx+idx] = (jlong)product;
8222   //     carry  = (jlong)(product >>> 64);
8223   //   }
8224   //   idx += 2;
8225   //   if (idx > 0) {
8226   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8227   //     z[kdx+idx] = (jlong)product;
8228   //     carry  = (jlong)(product >>> 64);
8229   //   }
8230   //
8231 
8232   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8233 
8234   movl(jdx, idx);
8235   andl(jdx, 0xFFFFFFFC);
8236   shrl(jdx, 2);
8237 
8238   bind(L_third_loop);
8239   subl(jdx, 1);
8240   jcc(Assembler::negative, L_third_loop_exit);
8241   subl(idx, 4);
8242 
8243   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8244   movq(carry2, rdx);
8245 
8246   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8247   movq(carry, rdx);
8248   jmp(L_third_loop);
8249 
8250   bind (L_third_loop_exit);
8251 
8252   andl (idx, 0x3);
8253   jcc(Assembler::zero, L_post_third_loop_done);
8254 
8255   Label L_check_1;
8256   subl(idx, 2);
8257   jcc(Assembler::negative, L_check_1);
8258 
8259   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8260   movq(carry, rdx);
8261 
8262   bind (L_check_1);
8263   addl (idx, 0x2);
8264   andl (idx, 0x1);
8265   subl(idx, 1);
8266   jcc(Assembler::negative, L_post_third_loop_done);
8267 
8268   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8269   movq(product, x_xstart);
8270   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8271   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8272 
8273   add2_with_carry(rdx, product, yz_idx, carry);
8274 
8275   movl(Address(z, idx, Address::times_4,  0), product);
8276   shrq(product, 32);
8277 
8278   shlq(rdx, 32);
8279   orq(product, rdx);
8280   movq(carry, product);
8281 
8282   bind(L_post_third_loop_done);
8283 }
8284 
8285 /**
8286  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8287  *
8288  */
8289 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8290                                                   Register carry, Register carry2,
8291                                                   Register idx, Register jdx,
8292                                                   Register yz_idx1, Register yz_idx2,
8293                                                   Register tmp, Register tmp3, Register tmp4) {
8294   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8295 
8296   //   jlong carry, x[], y[], z[];
8297   //   int kdx = ystart+1;
8298   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8299   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8300   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8301   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8302   //     carry  = (jlong)(tmp4 >>> 64);
8303   //     z[kdx+idx+1] = (jlong)tmp3;
8304   //     z[kdx+idx] = (jlong)tmp4;
8305   //   }
8306   //   idx += 2;
8307   //   if (idx > 0) {
8308   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8309   //     z[kdx+idx] = (jlong)yz_idx1;
8310   //     carry  = (jlong)(yz_idx1 >>> 64);
8311   //   }
8312   //
8313 
8314   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8315 
8316   movl(jdx, idx);
8317   andl(jdx, 0xFFFFFFFC);
8318   shrl(jdx, 2);
8319 
8320   bind(L_third_loop);
8321   subl(jdx, 1);
8322   jcc(Assembler::negative, L_third_loop_exit);
8323   subl(idx, 4);
8324 
8325   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8326   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8327   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8328   rorxq(yz_idx2, yz_idx2, 32);
8329 
8330   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8331   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8332 
8333   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8334   rorxq(yz_idx1, yz_idx1, 32);
8335   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8336   rorxq(yz_idx2, yz_idx2, 32);
8337 
8338   if (VM_Version::supports_adx()) {
8339     adcxq(tmp3, carry);
8340     adoxq(tmp3, yz_idx1);
8341 
8342     adcxq(tmp4, tmp);
8343     adoxq(tmp4, yz_idx2);
8344 
8345     movl(carry, 0); // does not affect flags
8346     adcxq(carry2, carry);
8347     adoxq(carry2, carry);
8348   } else {
8349     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8350     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8351   }
8352   movq(carry, carry2);
8353 
8354   movl(Address(z, idx, Address::times_4, 12), tmp3);
8355   shrq(tmp3, 32);
8356   movl(Address(z, idx, Address::times_4,  8), tmp3);
8357 
8358   movl(Address(z, idx, Address::times_4,  4), tmp4);
8359   shrq(tmp4, 32);
8360   movl(Address(z, idx, Address::times_4,  0), tmp4);
8361 
8362   jmp(L_third_loop);
8363 
8364   bind (L_third_loop_exit);
8365 
8366   andl (idx, 0x3);
8367   jcc(Assembler::zero, L_post_third_loop_done);
8368 
8369   Label L_check_1;
8370   subl(idx, 2);
8371   jcc(Assembler::negative, L_check_1);
8372 
8373   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8374   rorxq(yz_idx1, yz_idx1, 32);
8375   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8376   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8377   rorxq(yz_idx2, yz_idx2, 32);
8378 
8379   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8380 
8381   movl(Address(z, idx, Address::times_4,  4), tmp3);
8382   shrq(tmp3, 32);
8383   movl(Address(z, idx, Address::times_4,  0), tmp3);
8384   movq(carry, tmp4);
8385 
8386   bind (L_check_1);
8387   addl (idx, 0x2);
8388   andl (idx, 0x1);
8389   subl(idx, 1);
8390   jcc(Assembler::negative, L_post_third_loop_done);
8391   movl(tmp4, Address(y, idx, Address::times_4,  0));
8392   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8393   movl(tmp4, Address(z, idx, Address::times_4,  0));
8394 
8395   add2_with_carry(carry2, tmp3, tmp4, carry);
8396 
8397   movl(Address(z, idx, Address::times_4,  0), tmp3);
8398   shrq(tmp3, 32);
8399 
8400   shlq(carry2, 32);
8401   orq(tmp3, carry2);
8402   movq(carry, tmp3);
8403 
8404   bind(L_post_third_loop_done);
8405 }
8406 
8407 /**
8408  * Code for BigInteger::multiplyToLen() instrinsic.
8409  *
8410  * rdi: x
8411  * rax: xlen
8412  * rsi: y
8413  * rcx: ylen
8414  * r8:  z
8415  * r11: zlen
8416  * r12: tmp1
8417  * r13: tmp2
8418  * r14: tmp3
8419  * r15: tmp4
8420  * rbx: tmp5
8421  *
8422  */
8423 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8424                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8425   ShortBranchVerifier sbv(this);
8426   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8427 
8428   push(tmp1);
8429   push(tmp2);
8430   push(tmp3);
8431   push(tmp4);
8432   push(tmp5);
8433 
8434   push(xlen);
8435   push(zlen);
8436 
8437   const Register idx = tmp1;
8438   const Register kdx = tmp2;
8439   const Register xstart = tmp3;
8440 
8441   const Register y_idx = tmp4;
8442   const Register carry = tmp5;
8443   const Register product  = xlen;
8444   const Register x_xstart = zlen;  // reuse register
8445 
8446   // First Loop.
8447   //
8448   //  final static long LONG_MASK = 0xffffffffL;
8449   //  int xstart = xlen - 1;
8450   //  int ystart = ylen - 1;
8451   //  long carry = 0;
8452   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8453   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8454   //    z[kdx] = (int)product;
8455   //    carry = product >>> 32;
8456   //  }
8457   //  z[xstart] = (int)carry;
8458   //
8459 
8460   movl(idx, ylen);      // idx = ylen;
8461   movl(kdx, zlen);      // kdx = xlen+ylen;
8462   xorq(carry, carry);   // carry = 0;
8463 
8464   Label L_done;
8465 
8466   movl(xstart, xlen);
8467   decrementl(xstart);
8468   jcc(Assembler::negative, L_done);
8469 
8470   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8471 
8472   Label L_second_loop;
8473   testl(kdx, kdx);
8474   jcc(Assembler::zero, L_second_loop);
8475 
8476   Label L_carry;
8477   subl(kdx, 1);
8478   jcc(Assembler::zero, L_carry);
8479 
8480   movl(Address(z, kdx, Address::times_4,  0), carry);
8481   shrq(carry, 32);
8482   subl(kdx, 1);
8483 
8484   bind(L_carry);
8485   movl(Address(z, kdx, Address::times_4,  0), carry);
8486 
8487   // Second and third (nested) loops.
8488   //
8489   // for (int i = xstart-1; i >= 0; i--) { // Second loop
8490   //   carry = 0;
8491   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
8492   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
8493   //                    (z[k] & LONG_MASK) + carry;
8494   //     z[k] = (int)product;
8495   //     carry = product >>> 32;
8496   //   }
8497   //   z[i] = (int)carry;
8498   // }
8499   //
8500   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
8501 
8502   const Register jdx = tmp1;
8503 
8504   bind(L_second_loop);
8505   xorl(carry, carry);    // carry = 0;
8506   movl(jdx, ylen);       // j = ystart+1
8507 
8508   subl(xstart, 1);       // i = xstart-1;
8509   jcc(Assembler::negative, L_done);
8510 
8511   push (z);
8512 
8513   Label L_last_x;
8514   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
8515   subl(xstart, 1);       // i = xstart-1;
8516   jcc(Assembler::negative, L_last_x);
8517 
8518   if (UseBMI2Instructions) {
8519     movq(rdx,  Address(x, xstart, Address::times_4,  0));
8520     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
8521   } else {
8522     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8523     rorq(x_xstart, 32);  // convert big-endian to little-endian
8524   }
8525 
8526   Label L_third_loop_prologue;
8527   bind(L_third_loop_prologue);
8528 
8529   push (x);
8530   push (xstart);
8531   push (ylen);
8532 
8533 
8534   if (UseBMI2Instructions) {
8535     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
8536   } else { // !UseBMI2Instructions
8537     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
8538   }
8539 
8540   pop(ylen);
8541   pop(xlen);
8542   pop(x);
8543   pop(z);
8544 
8545   movl(tmp3, xlen);
8546   addl(tmp3, 1);
8547   movl(Address(z, tmp3, Address::times_4,  0), carry);
8548   subl(tmp3, 1);
8549   jccb(Assembler::negative, L_done);
8550 
8551   shrq(carry, 32);
8552   movl(Address(z, tmp3, Address::times_4,  0), carry);
8553   jmp(L_second_loop);
8554 
8555   // Next infrequent code is moved outside loops.
8556   bind(L_last_x);
8557   if (UseBMI2Instructions) {
8558     movl(rdx, Address(x,  0));
8559   } else {
8560     movl(x_xstart, Address(x,  0));
8561   }
8562   jmp(L_third_loop_prologue);
8563 
8564   bind(L_done);
8565 
8566   pop(zlen);
8567   pop(xlen);
8568 
8569   pop(tmp5);
8570   pop(tmp4);
8571   pop(tmp3);
8572   pop(tmp2);
8573   pop(tmp1);
8574 }
8575 
8576 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
8577   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
8578   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
8579   Label VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
8580   Label VECTOR8_TAIL, VECTOR4_TAIL;
8581   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
8582   Label SAME_TILL_END, DONE;
8583   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
8584 
8585   //scale is in rcx in both Win64 and Unix
8586   ShortBranchVerifier sbv(this);
8587 
8588   shlq(length);
8589   xorq(result, result);
8590 
8591   if ((UseAVX > 2) &&
8592       VM_Version::supports_avx512vlbw()) {
8593     Label VECTOR64_LOOP, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
8594 
8595     cmpq(length, 64);
8596     jcc(Assembler::less, VECTOR32_TAIL);
8597     movq(tmp1, length);
8598     andq(tmp1, 0x3F);      // tail count
8599     andq(length, ~(0x3F)); //vector count
8600 
8601     bind(VECTOR64_LOOP);
8602     // AVX512 code to compare 64 byte vectors.
8603     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
8604     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
8605     kortestql(k7, k7);
8606     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
8607     addq(result, 64);
8608     subq(length, 64);
8609     jccb(Assembler::notZero, VECTOR64_LOOP);
8610 
8611     //bind(VECTOR64_TAIL);
8612     testq(tmp1, tmp1);
8613     jcc(Assembler::zero, SAME_TILL_END);
8614 
8615     //bind(VECTOR64_TAIL);
8616     // AVX512 code to compare upto 63 byte vectors.
8617     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
8618     shlxq(tmp2, tmp2, tmp1);
8619     notq(tmp2);
8620     kmovql(k3, tmp2);
8621 
8622     evmovdqub(rymm0, k3, Address(obja, result), Assembler::AVX_512bit);
8623     evpcmpeqb(k7, k3, rymm0, Address(objb, result), Assembler::AVX_512bit);
8624 
8625     ktestql(k7, k3);
8626     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
8627 
8628     bind(VECTOR64_NOT_EQUAL);
8629     kmovql(tmp1, k7);
8630     notq(tmp1);
8631     tzcntq(tmp1, tmp1);
8632     addq(result, tmp1);
8633     shrq(result);
8634     jmp(DONE);
8635     bind(VECTOR32_TAIL);
8636   }
8637 
8638   cmpq(length, 8);
8639   jcc(Assembler::equal, VECTOR8_LOOP);
8640   jcc(Assembler::less, VECTOR4_TAIL);
8641 
8642   if (UseAVX >= 2) {
8643     Label VECTOR16_TAIL, VECTOR32_LOOP;
8644 
8645     cmpq(length, 16);
8646     jcc(Assembler::equal, VECTOR16_LOOP);
8647     jcc(Assembler::less, VECTOR8_LOOP);
8648 
8649     cmpq(length, 32);
8650     jccb(Assembler::less, VECTOR16_TAIL);
8651 
8652     subq(length, 32);
8653     bind(VECTOR32_LOOP);
8654     vmovdqu(rymm0, Address(obja, result));
8655     vmovdqu(rymm1, Address(objb, result));
8656     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
8657     vptest(rymm2, rymm2);
8658     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
8659     addq(result, 32);
8660     subq(length, 32);
8661     jcc(Assembler::greaterEqual, VECTOR32_LOOP);
8662     addq(length, 32);
8663     jcc(Assembler::equal, SAME_TILL_END);
8664     //falling through if less than 32 bytes left //close the branch here.
8665 
8666     bind(VECTOR16_TAIL);
8667     cmpq(length, 16);
8668     jccb(Assembler::less, VECTOR8_TAIL);
8669     bind(VECTOR16_LOOP);
8670     movdqu(rymm0, Address(obja, result));
8671     movdqu(rymm1, Address(objb, result));
8672     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
8673     ptest(rymm2, rymm2);
8674     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8675     addq(result, 16);
8676     subq(length, 16);
8677     jcc(Assembler::equal, SAME_TILL_END);
8678     //falling through if less than 16 bytes left
8679   } else {//regular intrinsics
8680 
8681     cmpq(length, 16);
8682     jccb(Assembler::less, VECTOR8_TAIL);
8683 
8684     subq(length, 16);
8685     bind(VECTOR16_LOOP);
8686     movdqu(rymm0, Address(obja, result));
8687     movdqu(rymm1, Address(objb, result));
8688     pxor(rymm0, rymm1);
8689     ptest(rymm0, rymm0);
8690     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
8691     addq(result, 16);
8692     subq(length, 16);
8693     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
8694     addq(length, 16);
8695     jcc(Assembler::equal, SAME_TILL_END);
8696     //falling through if less than 16 bytes left
8697   }
8698 
8699   bind(VECTOR8_TAIL);
8700   cmpq(length, 8);
8701   jccb(Assembler::less, VECTOR4_TAIL);
8702   bind(VECTOR8_LOOP);
8703   movq(tmp1, Address(obja, result));
8704   movq(tmp2, Address(objb, result));
8705   xorq(tmp1, tmp2);
8706   testq(tmp1, tmp1);
8707   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
8708   addq(result, 8);
8709   subq(length, 8);
8710   jcc(Assembler::equal, SAME_TILL_END);
8711   //falling through if less than 8 bytes left
8712 
8713   bind(VECTOR4_TAIL);
8714   cmpq(length, 4);
8715   jccb(Assembler::less, BYTES_TAIL);
8716   bind(VECTOR4_LOOP);
8717   movl(tmp1, Address(obja, result));
8718   xorl(tmp1, Address(objb, result));
8719   testl(tmp1, tmp1);
8720   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
8721   addq(result, 4);
8722   subq(length, 4);
8723   jcc(Assembler::equal, SAME_TILL_END);
8724   //falling through if less than 4 bytes left
8725 
8726   bind(BYTES_TAIL);
8727   bind(BYTES_LOOP);
8728   load_unsigned_byte(tmp1, Address(obja, result));
8729   load_unsigned_byte(tmp2, Address(objb, result));
8730   xorl(tmp1, tmp2);
8731   testl(tmp1, tmp1);
8732   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8733   decq(length);
8734   jcc(Assembler::zero, SAME_TILL_END);
8735   incq(result);
8736   load_unsigned_byte(tmp1, Address(obja, result));
8737   load_unsigned_byte(tmp2, Address(objb, result));
8738   xorl(tmp1, tmp2);
8739   testl(tmp1, tmp1);
8740   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8741   decq(length);
8742   jcc(Assembler::zero, SAME_TILL_END);
8743   incq(result);
8744   load_unsigned_byte(tmp1, Address(obja, result));
8745   load_unsigned_byte(tmp2, Address(objb, result));
8746   xorl(tmp1, tmp2);
8747   testl(tmp1, tmp1);
8748   jcc(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
8749   jmp(SAME_TILL_END);
8750 
8751   if (UseAVX >= 2) {
8752     bind(VECTOR32_NOT_EQUAL);
8753     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
8754     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
8755     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
8756     vpmovmskb(tmp1, rymm0);
8757     bsfq(tmp1, tmp1);
8758     addq(result, tmp1);
8759     shrq(result);
8760     jmp(DONE);
8761   }
8762 
8763   bind(VECTOR16_NOT_EQUAL);
8764   if (UseAVX >= 2) {
8765     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
8766     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
8767     pxor(rymm0, rymm2);
8768   } else {
8769     pcmpeqb(rymm2, rymm2);
8770     pxor(rymm0, rymm1);
8771     pcmpeqb(rymm0, rymm1);
8772     pxor(rymm0, rymm2);
8773   }
8774   pmovmskb(tmp1, rymm0);
8775   bsfq(tmp1, tmp1);
8776   addq(result, tmp1);
8777   shrq(result);
8778   jmpb(DONE);
8779 
8780   bind(VECTOR8_NOT_EQUAL);
8781   bind(VECTOR4_NOT_EQUAL);
8782   bsfq(tmp1, tmp1);
8783   shrq(tmp1, 3);
8784   addq(result, tmp1);
8785   bind(BYTES_NOT_EQUAL);
8786   shrq(result);
8787   jmpb(DONE);
8788 
8789   bind(SAME_TILL_END);
8790   mov64(result, -1);
8791 
8792   bind(DONE);
8793 }
8794 
8795 //Helper functions for square_to_len()
8796 
8797 /**
8798  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
8799  * Preserves x and z and modifies rest of the registers.
8800  */
8801 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8802   // Perform square and right shift by 1
8803   // Handle odd xlen case first, then for even xlen do the following
8804   // jlong carry = 0;
8805   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
8806   //     huge_128 product = x[j:j+1] * x[j:j+1];
8807   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
8808   //     z[i+2:i+3] = (jlong)(product >>> 1);
8809   //     carry = (jlong)product;
8810   // }
8811 
8812   xorq(tmp5, tmp5);     // carry
8813   xorq(rdxReg, rdxReg);
8814   xorl(tmp1, tmp1);     // index for x
8815   xorl(tmp4, tmp4);     // index for z
8816 
8817   Label L_first_loop, L_first_loop_exit;
8818 
8819   testl(xlen, 1);
8820   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
8821 
8822   // Square and right shift by 1 the odd element using 32 bit multiply
8823   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
8824   imulq(raxReg, raxReg);
8825   shrq(raxReg, 1);
8826   adcq(tmp5, 0);
8827   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
8828   incrementl(tmp1);
8829   addl(tmp4, 2);
8830 
8831   // Square and  right shift by 1 the rest using 64 bit multiply
8832   bind(L_first_loop);
8833   cmpptr(tmp1, xlen);
8834   jccb(Assembler::equal, L_first_loop_exit);
8835 
8836   // Square
8837   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
8838   rorq(raxReg, 32);    // convert big-endian to little-endian
8839   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
8840 
8841   // Right shift by 1 and save carry
8842   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
8843   rcrq(rdxReg, 1);
8844   rcrq(raxReg, 1);
8845   adcq(tmp5, 0);
8846 
8847   // Store result in z
8848   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
8849   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
8850 
8851   // Update indices for x and z
8852   addl(tmp1, 2);
8853   addl(tmp4, 4);
8854   jmp(L_first_loop);
8855 
8856   bind(L_first_loop_exit);
8857 }
8858 
8859 
8860 /**
8861  * Perform the following multiply add operation using BMI2 instructions
8862  * carry:sum = sum + op1*op2 + carry
8863  * op2 should be in rdx
8864  * op2 is preserved, all other registers are modified
8865  */
8866 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
8867   // assert op2 is rdx
8868   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
8869   addq(sum, carry);
8870   adcq(tmp2, 0);
8871   addq(sum, op1);
8872   adcq(tmp2, 0);
8873   movq(carry, tmp2);
8874 }
8875 
8876 /**
8877  * Perform the following multiply add operation:
8878  * carry:sum = sum + op1*op2 + carry
8879  * Preserves op1, op2 and modifies rest of registers
8880  */
8881 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
8882   // rdx:rax = op1 * op2
8883   movq(raxReg, op2);
8884   mulq(op1);
8885 
8886   //  rdx:rax = sum + carry + rdx:rax
8887   addq(sum, carry);
8888   adcq(rdxReg, 0);
8889   addq(sum, raxReg);
8890   adcq(rdxReg, 0);
8891 
8892   // carry:sum = rdx:sum
8893   movq(carry, rdxReg);
8894 }
8895 
8896 /**
8897  * Add 64 bit long carry into z[] with carry propogation.
8898  * Preserves z and carry register values and modifies rest of registers.
8899  *
8900  */
8901 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
8902   Label L_fourth_loop, L_fourth_loop_exit;
8903 
8904   movl(tmp1, 1);
8905   subl(zlen, 2);
8906   addq(Address(z, zlen, Address::times_4, 0), carry);
8907 
8908   bind(L_fourth_loop);
8909   jccb(Assembler::carryClear, L_fourth_loop_exit);
8910   subl(zlen, 2);
8911   jccb(Assembler::negative, L_fourth_loop_exit);
8912   addq(Address(z, zlen, Address::times_4, 0), tmp1);
8913   jmp(L_fourth_loop);
8914   bind(L_fourth_loop_exit);
8915 }
8916 
8917 /**
8918  * Shift z[] left by 1 bit.
8919  * Preserves x, len, z and zlen registers and modifies rest of the registers.
8920  *
8921  */
8922 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
8923 
8924   Label L_fifth_loop, L_fifth_loop_exit;
8925 
8926   // Fifth loop
8927   // Perform primitiveLeftShift(z, zlen, 1)
8928 
8929   const Register prev_carry = tmp1;
8930   const Register new_carry = tmp4;
8931   const Register value = tmp2;
8932   const Register zidx = tmp3;
8933 
8934   // int zidx, carry;
8935   // long value;
8936   // carry = 0;
8937   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
8938   //    (carry:value)  = (z[i] << 1) | carry ;
8939   //    z[i] = value;
8940   // }
8941 
8942   movl(zidx, zlen);
8943   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
8944 
8945   bind(L_fifth_loop);
8946   decl(zidx);  // Use decl to preserve carry flag
8947   decl(zidx);
8948   jccb(Assembler::negative, L_fifth_loop_exit);
8949 
8950   if (UseBMI2Instructions) {
8951      movq(value, Address(z, zidx, Address::times_4, 0));
8952      rclq(value, 1);
8953      rorxq(value, value, 32);
8954      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8955   }
8956   else {
8957     // clear new_carry
8958     xorl(new_carry, new_carry);
8959 
8960     // Shift z[i] by 1, or in previous carry and save new carry
8961     movq(value, Address(z, zidx, Address::times_4, 0));
8962     shlq(value, 1);
8963     adcl(new_carry, 0);
8964 
8965     orq(value, prev_carry);
8966     rorq(value, 0x20);
8967     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8968 
8969     // Set previous carry = new carry
8970     movl(prev_carry, new_carry);
8971   }
8972   jmp(L_fifth_loop);
8973 
8974   bind(L_fifth_loop_exit);
8975 }
8976 
8977 
8978 /**
8979  * Code for BigInteger::squareToLen() intrinsic
8980  *
8981  * rdi: x
8982  * rsi: len
8983  * r8:  z
8984  * rcx: zlen
8985  * r12: tmp1
8986  * r13: tmp2
8987  * r14: tmp3
8988  * r15: tmp4
8989  * rbx: tmp5
8990  *
8991  */
8992 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) {
8993 
8994   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, L_last_x, L_multiply;
8995   push(tmp1);
8996   push(tmp2);
8997   push(tmp3);
8998   push(tmp4);
8999   push(tmp5);
9000 
9001   // First loop
9002   // Store the squares, right shifted one bit (i.e., divided by 2).
9003   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9004 
9005   // Add in off-diagonal sums.
9006   //
9007   // Second, third (nested) and fourth loops.
9008   // zlen +=2;
9009   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9010   //    carry = 0;
9011   //    long op2 = x[xidx:xidx+1];
9012   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9013   //       k -= 2;
9014   //       long op1 = x[j:j+1];
9015   //       long sum = z[k:k+1];
9016   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9017   //       z[k:k+1] = sum;
9018   //    }
9019   //    add_one_64(z, k, carry, tmp_regs);
9020   // }
9021 
9022   const Register carry = tmp5;
9023   const Register sum = tmp3;
9024   const Register op1 = tmp4;
9025   Register op2 = tmp2;
9026 
9027   push(zlen);
9028   push(len);
9029   addl(zlen,2);
9030   bind(L_second_loop);
9031   xorq(carry, carry);
9032   subl(zlen, 4);
9033   subl(len, 2);
9034   push(zlen);
9035   push(len);
9036   cmpl(len, 0);
9037   jccb(Assembler::lessEqual, L_second_loop_exit);
9038 
9039   // Multiply an array by one 64 bit long.
9040   if (UseBMI2Instructions) {
9041     op2 = rdxReg;
9042     movq(op2, Address(x, len, Address::times_4,  0));
9043     rorxq(op2, op2, 32);
9044   }
9045   else {
9046     movq(op2, Address(x, len, Address::times_4,  0));
9047     rorq(op2, 32);
9048   }
9049 
9050   bind(L_third_loop);
9051   decrementl(len);
9052   jccb(Assembler::negative, L_third_loop_exit);
9053   decrementl(len);
9054   jccb(Assembler::negative, L_last_x);
9055 
9056   movq(op1, Address(x, len, Address::times_4,  0));
9057   rorq(op1, 32);
9058 
9059   bind(L_multiply);
9060   subl(zlen, 2);
9061   movq(sum, Address(z, zlen, Address::times_4,  0));
9062 
9063   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9064   if (UseBMI2Instructions) {
9065     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9066   }
9067   else {
9068     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9069   }
9070 
9071   movq(Address(z, zlen, Address::times_4, 0), sum);
9072 
9073   jmp(L_third_loop);
9074   bind(L_third_loop_exit);
9075 
9076   // Fourth loop
9077   // Add 64 bit long carry into z with carry propogation.
9078   // Uses offsetted zlen.
9079   add_one_64(z, zlen, carry, tmp1);
9080 
9081   pop(len);
9082   pop(zlen);
9083   jmp(L_second_loop);
9084 
9085   // Next infrequent code is moved outside loops.
9086   bind(L_last_x);
9087   movl(op1, Address(x, 0));
9088   jmp(L_multiply);
9089 
9090   bind(L_second_loop_exit);
9091   pop(len);
9092   pop(zlen);
9093   pop(len);
9094   pop(zlen);
9095 
9096   // Fifth loop
9097   // Shift z left 1 bit.
9098   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9099 
9100   // z[zlen-1] |= x[len-1] & 1;
9101   movl(tmp3, Address(x, len, Address::times_4, -4));
9102   andl(tmp3, 1);
9103   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9104 
9105   pop(tmp5);
9106   pop(tmp4);
9107   pop(tmp3);
9108   pop(tmp2);
9109   pop(tmp1);
9110 }
9111 
9112 /**
9113  * Helper function for mul_add()
9114  * Multiply the in[] by int k and add to out[] starting at offset offs using
9115  * 128 bit by 32 bit multiply and return the carry in tmp5.
9116  * Only quad int aligned length of in[] is operated on in this function.
9117  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9118  * This function preserves out, in and k registers.
9119  * len and offset point to the appropriate index in "in" & "out" correspondingly
9120  * tmp5 has the carry.
9121  * other registers are temporary and are modified.
9122  *
9123  */
9124 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9125   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9126   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9127 
9128   Label L_first_loop, L_first_loop_exit;
9129 
9130   movl(tmp1, len);
9131   shrl(tmp1, 2);
9132 
9133   bind(L_first_loop);
9134   subl(tmp1, 1);
9135   jccb(Assembler::negative, L_first_loop_exit);
9136 
9137   subl(len, 4);
9138   subl(offset, 4);
9139 
9140   Register op2 = tmp2;
9141   const Register sum = tmp3;
9142   const Register op1 = tmp4;
9143   const Register carry = tmp5;
9144 
9145   if (UseBMI2Instructions) {
9146     op2 = rdxReg;
9147   }
9148 
9149   movq(op1, Address(in, len, Address::times_4,  8));
9150   rorq(op1, 32);
9151   movq(sum, Address(out, offset, Address::times_4,  8));
9152   rorq(sum, 32);
9153   if (UseBMI2Instructions) {
9154     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9155   }
9156   else {
9157     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9158   }
9159   // Store back in big endian from little endian
9160   rorq(sum, 0x20);
9161   movq(Address(out, offset, Address::times_4,  8), sum);
9162 
9163   movq(op1, Address(in, len, Address::times_4,  0));
9164   rorq(op1, 32);
9165   movq(sum, Address(out, offset, Address::times_4,  0));
9166   rorq(sum, 32);
9167   if (UseBMI2Instructions) {
9168     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9169   }
9170   else {
9171     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9172   }
9173   // Store back in big endian from little endian
9174   rorq(sum, 0x20);
9175   movq(Address(out, offset, Address::times_4,  0), sum);
9176 
9177   jmp(L_first_loop);
9178   bind(L_first_loop_exit);
9179 }
9180 
9181 /**
9182  * Code for BigInteger::mulAdd() intrinsic
9183  *
9184  * rdi: out
9185  * rsi: in
9186  * r11: offs (out.length - offset)
9187  * rcx: len
9188  * r8:  k
9189  * r12: tmp1
9190  * r13: tmp2
9191  * r14: tmp3
9192  * r15: tmp4
9193  * rbx: tmp5
9194  * Multiply the in[] by word k and add to out[], return the carry in rax
9195  */
9196 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9197    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9198    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9199 
9200   Label L_carry, L_last_in, L_done;
9201 
9202 // carry = 0;
9203 // for (int j=len-1; j >= 0; j--) {
9204 //    long product = (in[j] & LONG_MASK) * kLong +
9205 //                   (out[offs] & LONG_MASK) + carry;
9206 //    out[offs--] = (int)product;
9207 //    carry = product >>> 32;
9208 // }
9209 //
9210   push(tmp1);
9211   push(tmp2);
9212   push(tmp3);
9213   push(tmp4);
9214   push(tmp5);
9215 
9216   Register op2 = tmp2;
9217   const Register sum = tmp3;
9218   const Register op1 = tmp4;
9219   const Register carry =  tmp5;
9220 
9221   if (UseBMI2Instructions) {
9222     op2 = rdxReg;
9223     movl(op2, k);
9224   }
9225   else {
9226     movl(op2, k);
9227   }
9228 
9229   xorq(carry, carry);
9230 
9231   //First loop
9232 
9233   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9234   //The carry is in tmp5
9235   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9236 
9237   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9238   decrementl(len);
9239   jccb(Assembler::negative, L_carry);
9240   decrementl(len);
9241   jccb(Assembler::negative, L_last_in);
9242 
9243   movq(op1, Address(in, len, Address::times_4,  0));
9244   rorq(op1, 32);
9245 
9246   subl(offs, 2);
9247   movq(sum, Address(out, offs, Address::times_4,  0));
9248   rorq(sum, 32);
9249 
9250   if (UseBMI2Instructions) {
9251     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9252   }
9253   else {
9254     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9255   }
9256 
9257   // Store back in big endian from little endian
9258   rorq(sum, 0x20);
9259   movq(Address(out, offs, Address::times_4,  0), sum);
9260 
9261   testl(len, len);
9262   jccb(Assembler::zero, L_carry);
9263 
9264   //Multiply the last in[] entry, if any
9265   bind(L_last_in);
9266   movl(op1, Address(in, 0));
9267   movl(sum, Address(out, offs, Address::times_4,  -4));
9268 
9269   movl(raxReg, k);
9270   mull(op1); //tmp4 * eax -> edx:eax
9271   addl(sum, carry);
9272   adcl(rdxReg, 0);
9273   addl(sum, raxReg);
9274   adcl(rdxReg, 0);
9275   movl(carry, rdxReg);
9276 
9277   movl(Address(out, offs, Address::times_4,  -4), sum);
9278 
9279   bind(L_carry);
9280   //return tmp5/carry as carry in rax
9281   movl(rax, carry);
9282 
9283   bind(L_done);
9284   pop(tmp5);
9285   pop(tmp4);
9286   pop(tmp3);
9287   pop(tmp2);
9288   pop(tmp1);
9289 }
9290 #endif
9291 
9292 /**
9293  * Emits code to update CRC-32 with a byte value according to constants in table
9294  *
9295  * @param [in,out]crc   Register containing the crc.
9296  * @param [in]val       Register containing the byte to fold into the CRC.
9297  * @param [in]table     Register containing the table of crc constants.
9298  *
9299  * uint32_t crc;
9300  * val = crc_table[(val ^ crc) & 0xFF];
9301  * crc = val ^ (crc >> 8);
9302  *
9303  */
9304 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9305   xorl(val, crc);
9306   andl(val, 0xFF);
9307   shrl(crc, 8); // unsigned shift
9308   xorl(crc, Address(table, val, Address::times_4, 0));
9309 }
9310 
9311 /**
9312 * Fold four 128-bit data chunks
9313 */
9314 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9315   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9316   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9317   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9318   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9319 }
9320 
9321 /**
9322  * Fold 128-bit data chunk
9323  */
9324 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9325   if (UseAVX > 0) {
9326     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9327     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9328     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9329     pxor(xcrc, xtmp);
9330   } else {
9331     movdqa(xtmp, xcrc);
9332     pclmulhdq(xtmp, xK);   // [123:64]
9333     pclmulldq(xcrc, xK);   // [63:0]
9334     pxor(xcrc, xtmp);
9335     movdqu(xtmp, Address(buf, offset));
9336     pxor(xcrc, xtmp);
9337   }
9338 }
9339 
9340 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9341   if (UseAVX > 0) {
9342     vpclmulhdq(xtmp, xK, xcrc);
9343     vpclmulldq(xcrc, xK, xcrc);
9344     pxor(xcrc, xbuf);
9345     pxor(xcrc, xtmp);
9346   } else {
9347     movdqa(xtmp, xcrc);
9348     pclmulhdq(xtmp, xK);
9349     pclmulldq(xcrc, xK);
9350     pxor(xcrc, xbuf);
9351     pxor(xcrc, xtmp);
9352   }
9353 }
9354 
9355 /**
9356  * 8-bit folds to compute 32-bit CRC
9357  *
9358  * uint64_t xcrc;
9359  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9360  */
9361 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9362   movdl(tmp, xcrc);
9363   andl(tmp, 0xFF);
9364   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9365   psrldq(xcrc, 1); // unsigned shift one byte
9366   pxor(xcrc, xtmp);
9367 }
9368 
9369 /**
9370  * uint32_t crc;
9371  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9372  */
9373 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9374   movl(tmp, crc);
9375   andl(tmp, 0xFF);
9376   shrl(crc, 8);
9377   xorl(crc, Address(table, tmp, Address::times_4, 0));
9378 }
9379 
9380 /**
9381  * @param crc   register containing existing CRC (32-bit)
9382  * @param buf   register pointing to input byte buffer (byte*)
9383  * @param len   register containing number of bytes
9384  * @param table register that will contain address of CRC table
9385  * @param tmp   scratch register
9386  */
9387 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9388   assert_different_registers(crc, buf, len, table, tmp, rax);
9389 
9390   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9391   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9392 
9393   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9394   // context for the registers used, where all instructions below are using 128-bit mode
9395   // On EVEX without VL and BW, these instructions will all be AVX.
9396   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9397   notl(crc); // ~crc
9398   cmpl(len, 16);
9399   jcc(Assembler::less, L_tail);
9400 
9401   // Align buffer to 16 bytes
9402   movl(tmp, buf);
9403   andl(tmp, 0xF);
9404   jccb(Assembler::zero, L_aligned);
9405   subl(tmp,  16);
9406   addl(len, tmp);
9407 
9408   align(4);
9409   BIND(L_align_loop);
9410   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9411   update_byte_crc32(crc, rax, table);
9412   increment(buf);
9413   incrementl(tmp);
9414   jccb(Assembler::less, L_align_loop);
9415 
9416   BIND(L_aligned);
9417   movl(tmp, len); // save
9418   shrl(len, 4);
9419   jcc(Assembler::zero, L_tail_restore);
9420 
9421   // Fold total 512 bits of polynomial on each iteration
9422   if (VM_Version::supports_vpclmulqdq()) {
9423     Label Parallel_loop, L_No_Parallel;
9424 
9425     cmpl(len, 8);
9426     jccb(Assembler::less, L_No_Parallel);
9427 
9428     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9429     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9430     movdl(xmm5, crc);
9431     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9432     addptr(buf, 64);
9433     subl(len, 7);
9434     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9435 
9436     BIND(Parallel_loop);
9437     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9438     addptr(buf, 64);
9439     subl(len, 4);
9440     jcc(Assembler::greater, Parallel_loop);
9441 
9442     vextracti64x2(xmm2, xmm1, 0x01);
9443     vextracti64x2(xmm3, xmm1, 0x02);
9444     vextracti64x2(xmm4, xmm1, 0x03);
9445     jmp(L_fold_512b);
9446 
9447     BIND(L_No_Parallel);
9448   }
9449   // Fold crc into first bytes of vector
9450   movdqa(xmm1, Address(buf, 0));
9451   movdl(rax, xmm1);
9452   xorl(crc, rax);
9453   if (VM_Version::supports_sse4_1()) {
9454     pinsrd(xmm1, crc, 0);
9455   } else {
9456     pinsrw(xmm1, crc, 0);
9457     shrl(crc, 16);
9458     pinsrw(xmm1, crc, 1);
9459   }
9460   addptr(buf, 16);
9461   subl(len, 4); // len > 0
9462   jcc(Assembler::less, L_fold_tail);
9463 
9464   movdqa(xmm2, Address(buf,  0));
9465   movdqa(xmm3, Address(buf, 16));
9466   movdqa(xmm4, Address(buf, 32));
9467   addptr(buf, 48);
9468   subl(len, 3);
9469   jcc(Assembler::lessEqual, L_fold_512b);
9470 
9471   // Fold total 512 bits of polynomial on each iteration,
9472   // 128 bits per each of 4 parallel streams.
9473   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9474 
9475   align(32);
9476   BIND(L_fold_512b_loop);
9477   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9478   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9479   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9480   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9481   addptr(buf, 64);
9482   subl(len, 4);
9483   jcc(Assembler::greater, L_fold_512b_loop);
9484 
9485   // Fold 512 bits to 128 bits.
9486   BIND(L_fold_512b);
9487   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9488   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
9489   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
9490   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
9491 
9492   // Fold the rest of 128 bits data chunks
9493   BIND(L_fold_tail);
9494   addl(len, 3);
9495   jccb(Assembler::lessEqual, L_fold_128b);
9496   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9497 
9498   BIND(L_fold_tail_loop);
9499   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9500   addptr(buf, 16);
9501   decrementl(len);
9502   jccb(Assembler::greater, L_fold_tail_loop);
9503 
9504   // Fold 128 bits in xmm1 down into 32 bits in crc register.
9505   BIND(L_fold_128b);
9506   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
9507   if (UseAVX > 0) {
9508     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
9509     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
9510     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
9511   } else {
9512     movdqa(xmm2, xmm0);
9513     pclmulqdq(xmm2, xmm1, 0x1);
9514     movdqa(xmm3, xmm0);
9515     pand(xmm3, xmm2);
9516     pclmulqdq(xmm0, xmm3, 0x1);
9517   }
9518   psrldq(xmm1, 8);
9519   psrldq(xmm2, 4);
9520   pxor(xmm0, xmm1);
9521   pxor(xmm0, xmm2);
9522 
9523   // 8 8-bit folds to compute 32-bit CRC.
9524   for (int j = 0; j < 4; j++) {
9525     fold_8bit_crc32(xmm0, table, xmm1, rax);
9526   }
9527   movdl(crc, xmm0); // mov 32 bits to general register
9528   for (int j = 0; j < 4; j++) {
9529     fold_8bit_crc32(crc, table, rax);
9530   }
9531 
9532   BIND(L_tail_restore);
9533   movl(len, tmp); // restore
9534   BIND(L_tail);
9535   andl(len, 0xf);
9536   jccb(Assembler::zero, L_exit);
9537 
9538   // Fold the rest of bytes
9539   align(4);
9540   BIND(L_tail_loop);
9541   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9542   update_byte_crc32(crc, rax, table);
9543   increment(buf);
9544   decrementl(len);
9545   jccb(Assembler::greater, L_tail_loop);
9546 
9547   BIND(L_exit);
9548   notl(crc); // ~c
9549 }
9550 
9551 #ifdef _LP64
9552 // S. Gueron / Information Processing Letters 112 (2012) 184
9553 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
9554 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
9555 // Output: the 64-bit carry-less product of B * CONST
9556 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
9557                                      Register tmp1, Register tmp2, Register tmp3) {
9558   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9559   if (n > 0) {
9560     addq(tmp3, n * 256 * 8);
9561   }
9562   //    Q1 = TABLEExt[n][B & 0xFF];
9563   movl(tmp1, in);
9564   andl(tmp1, 0x000000FF);
9565   shll(tmp1, 3);
9566   addq(tmp1, tmp3);
9567   movq(tmp1, Address(tmp1, 0));
9568 
9569   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9570   movl(tmp2, in);
9571   shrl(tmp2, 8);
9572   andl(tmp2, 0x000000FF);
9573   shll(tmp2, 3);
9574   addq(tmp2, tmp3);
9575   movq(tmp2, Address(tmp2, 0));
9576 
9577   shlq(tmp2, 8);
9578   xorq(tmp1, tmp2);
9579 
9580   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9581   movl(tmp2, in);
9582   shrl(tmp2, 16);
9583   andl(tmp2, 0x000000FF);
9584   shll(tmp2, 3);
9585   addq(tmp2, tmp3);
9586   movq(tmp2, Address(tmp2, 0));
9587 
9588   shlq(tmp2, 16);
9589   xorq(tmp1, tmp2);
9590 
9591   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9592   shrl(in, 24);
9593   andl(in, 0x000000FF);
9594   shll(in, 3);
9595   addq(in, tmp3);
9596   movq(in, Address(in, 0));
9597 
9598   shlq(in, 24);
9599   xorq(in, tmp1);
9600   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9601 }
9602 
9603 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9604                                       Register in_out,
9605                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9606                                       XMMRegister w_xtmp2,
9607                                       Register tmp1,
9608                                       Register n_tmp2, Register n_tmp3) {
9609   if (is_pclmulqdq_supported) {
9610     movdl(w_xtmp1, in_out); // modified blindly
9611 
9612     movl(tmp1, const_or_pre_comp_const_index);
9613     movdl(w_xtmp2, tmp1);
9614     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9615 
9616     movdq(in_out, w_xtmp1);
9617   } else {
9618     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
9619   }
9620 }
9621 
9622 // Recombination Alternative 2: No bit-reflections
9623 // T1 = (CRC_A * U1) << 1
9624 // T2 = (CRC_B * U2) << 1
9625 // C1 = T1 >> 32
9626 // C2 = T2 >> 32
9627 // T1 = T1 & 0xFFFFFFFF
9628 // T2 = T2 & 0xFFFFFFFF
9629 // T1 = CRC32(0, T1)
9630 // T2 = CRC32(0, T2)
9631 // C1 = C1 ^ T1
9632 // C2 = C2 ^ T2
9633 // CRC = C1 ^ C2 ^ CRC_C
9634 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,
9635                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9636                                      Register tmp1, Register tmp2,
9637                                      Register n_tmp3) {
9638   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9639   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9640   shlq(in_out, 1);
9641   movl(tmp1, in_out);
9642   shrq(in_out, 32);
9643   xorl(tmp2, tmp2);
9644   crc32(tmp2, tmp1, 4);
9645   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
9646   shlq(in1, 1);
9647   movl(tmp1, in1);
9648   shrq(in1, 32);
9649   xorl(tmp2, tmp2);
9650   crc32(tmp2, tmp1, 4);
9651   xorl(in1, tmp2);
9652   xorl(in_out, in1);
9653   xorl(in_out, in2);
9654 }
9655 
9656 // Set N to predefined value
9657 // Subtract from a lenght of a buffer
9658 // execute in a loop:
9659 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
9660 // for i = 1 to N do
9661 //  CRC_A = CRC32(CRC_A, A[i])
9662 //  CRC_B = CRC32(CRC_B, B[i])
9663 //  CRC_C = CRC32(CRC_C, C[i])
9664 // end for
9665 // Recombine
9666 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,
9667                                        Register in_out1, Register in_out2, Register in_out3,
9668                                        Register tmp1, Register tmp2, Register tmp3,
9669                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9670                                        Register tmp4, Register tmp5,
9671                                        Register n_tmp6) {
9672   Label L_processPartitions;
9673   Label L_processPartition;
9674   Label L_exit;
9675 
9676   bind(L_processPartitions);
9677   cmpl(in_out1, 3 * size);
9678   jcc(Assembler::less, L_exit);
9679     xorl(tmp1, tmp1);
9680     xorl(tmp2, tmp2);
9681     movq(tmp3, in_out2);
9682     addq(tmp3, size);
9683 
9684     bind(L_processPartition);
9685       crc32(in_out3, Address(in_out2, 0), 8);
9686       crc32(tmp1, Address(in_out2, size), 8);
9687       crc32(tmp2, Address(in_out2, size * 2), 8);
9688       addq(in_out2, 8);
9689       cmpq(in_out2, tmp3);
9690       jcc(Assembler::less, L_processPartition);
9691     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9692             w_xtmp1, w_xtmp2, w_xtmp3,
9693             tmp4, tmp5,
9694             n_tmp6);
9695     addq(in_out2, 2 * size);
9696     subl(in_out1, 3 * size);
9697     jmp(L_processPartitions);
9698 
9699   bind(L_exit);
9700 }
9701 #else
9702 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
9703                                      Register tmp1, Register tmp2, Register tmp3,
9704                                      XMMRegister xtmp1, XMMRegister xtmp2) {
9705   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9706   if (n > 0) {
9707     addl(tmp3, n * 256 * 8);
9708   }
9709   //    Q1 = TABLEExt[n][B & 0xFF];
9710   movl(tmp1, in_out);
9711   andl(tmp1, 0x000000FF);
9712   shll(tmp1, 3);
9713   addl(tmp1, tmp3);
9714   movq(xtmp1, Address(tmp1, 0));
9715 
9716   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9717   movl(tmp2, in_out);
9718   shrl(tmp2, 8);
9719   andl(tmp2, 0x000000FF);
9720   shll(tmp2, 3);
9721   addl(tmp2, tmp3);
9722   movq(xtmp2, Address(tmp2, 0));
9723 
9724   psllq(xtmp2, 8);
9725   pxor(xtmp1, xtmp2);
9726 
9727   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9728   movl(tmp2, in_out);
9729   shrl(tmp2, 16);
9730   andl(tmp2, 0x000000FF);
9731   shll(tmp2, 3);
9732   addl(tmp2, tmp3);
9733   movq(xtmp2, Address(tmp2, 0));
9734 
9735   psllq(xtmp2, 16);
9736   pxor(xtmp1, xtmp2);
9737 
9738   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9739   shrl(in_out, 24);
9740   andl(in_out, 0x000000FF);
9741   shll(in_out, 3);
9742   addl(in_out, tmp3);
9743   movq(xtmp2, Address(in_out, 0));
9744 
9745   psllq(xtmp2, 24);
9746   pxor(xtmp1, xtmp2); // Result in CXMM
9747   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9748 }
9749 
9750 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9751                                       Register in_out,
9752                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9753                                       XMMRegister w_xtmp2,
9754                                       Register tmp1,
9755                                       Register n_tmp2, Register n_tmp3) {
9756   if (is_pclmulqdq_supported) {
9757     movdl(w_xtmp1, in_out);
9758 
9759     movl(tmp1, const_or_pre_comp_const_index);
9760     movdl(w_xtmp2, tmp1);
9761     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9762     // Keep result in XMM since GPR is 32 bit in length
9763   } else {
9764     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
9765   }
9766 }
9767 
9768 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,
9769                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9770                                      Register tmp1, Register tmp2,
9771                                      Register n_tmp3) {
9772   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9773   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9774 
9775   psllq(w_xtmp1, 1);
9776   movdl(tmp1, w_xtmp1);
9777   psrlq(w_xtmp1, 32);
9778   movdl(in_out, w_xtmp1);
9779 
9780   xorl(tmp2, tmp2);
9781   crc32(tmp2, tmp1, 4);
9782   xorl(in_out, tmp2);
9783 
9784   psllq(w_xtmp2, 1);
9785   movdl(tmp1, w_xtmp2);
9786   psrlq(w_xtmp2, 32);
9787   movdl(in1, w_xtmp2);
9788 
9789   xorl(tmp2, tmp2);
9790   crc32(tmp2, tmp1, 4);
9791   xorl(in1, tmp2);
9792   xorl(in_out, in1);
9793   xorl(in_out, in2);
9794 }
9795 
9796 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,
9797                                        Register in_out1, Register in_out2, Register in_out3,
9798                                        Register tmp1, Register tmp2, Register tmp3,
9799                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9800                                        Register tmp4, Register tmp5,
9801                                        Register n_tmp6) {
9802   Label L_processPartitions;
9803   Label L_processPartition;
9804   Label L_exit;
9805 
9806   bind(L_processPartitions);
9807   cmpl(in_out1, 3 * size);
9808   jcc(Assembler::less, L_exit);
9809     xorl(tmp1, tmp1);
9810     xorl(tmp2, tmp2);
9811     movl(tmp3, in_out2);
9812     addl(tmp3, size);
9813 
9814     bind(L_processPartition);
9815       crc32(in_out3, Address(in_out2, 0), 4);
9816       crc32(tmp1, Address(in_out2, size), 4);
9817       crc32(tmp2, Address(in_out2, size*2), 4);
9818       crc32(in_out3, Address(in_out2, 0+4), 4);
9819       crc32(tmp1, Address(in_out2, size+4), 4);
9820       crc32(tmp2, Address(in_out2, size*2+4), 4);
9821       addl(in_out2, 8);
9822       cmpl(in_out2, tmp3);
9823       jcc(Assembler::less, L_processPartition);
9824 
9825         push(tmp3);
9826         push(in_out1);
9827         push(in_out2);
9828         tmp4 = tmp3;
9829         tmp5 = in_out1;
9830         n_tmp6 = in_out2;
9831 
9832       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9833             w_xtmp1, w_xtmp2, w_xtmp3,
9834             tmp4, tmp5,
9835             n_tmp6);
9836 
9837         pop(in_out2);
9838         pop(in_out1);
9839         pop(tmp3);
9840 
9841     addl(in_out2, 2 * size);
9842     subl(in_out1, 3 * size);
9843     jmp(L_processPartitions);
9844 
9845   bind(L_exit);
9846 }
9847 #endif //LP64
9848 
9849 #ifdef _LP64
9850 // Algorithm 2: Pipelined usage of the CRC32 instruction.
9851 // Input: A buffer I of L bytes.
9852 // Output: the CRC32C value of the buffer.
9853 // Notations:
9854 // Write L = 24N + r, with N = floor (L/24).
9855 // r = L mod 24 (0 <= r < 24).
9856 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
9857 // N quadwords, and R consists of r bytes.
9858 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
9859 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
9860 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
9861 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
9862 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9863                                           Register tmp1, Register tmp2, Register tmp3,
9864                                           Register tmp4, Register tmp5, Register tmp6,
9865                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9866                                           bool is_pclmulqdq_supported) {
9867   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9868   Label L_wordByWord;
9869   Label L_byteByByteProlog;
9870   Label L_byteByByte;
9871   Label L_exit;
9872 
9873   if (is_pclmulqdq_supported ) {
9874     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9875     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
9876 
9877     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9878     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9879 
9880     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9881     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9882     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
9883   } else {
9884     const_or_pre_comp_const_index[0] = 1;
9885     const_or_pre_comp_const_index[1] = 0;
9886 
9887     const_or_pre_comp_const_index[2] = 3;
9888     const_or_pre_comp_const_index[3] = 2;
9889 
9890     const_or_pre_comp_const_index[4] = 5;
9891     const_or_pre_comp_const_index[5] = 4;
9892    }
9893   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9894                     in2, in1, in_out,
9895                     tmp1, tmp2, tmp3,
9896                     w_xtmp1, w_xtmp2, w_xtmp3,
9897                     tmp4, tmp5,
9898                     tmp6);
9899   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9900                     in2, in1, in_out,
9901                     tmp1, tmp2, tmp3,
9902                     w_xtmp1, w_xtmp2, w_xtmp3,
9903                     tmp4, tmp5,
9904                     tmp6);
9905   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9906                     in2, in1, in_out,
9907                     tmp1, tmp2, tmp3,
9908                     w_xtmp1, w_xtmp2, w_xtmp3,
9909                     tmp4, tmp5,
9910                     tmp6);
9911   movl(tmp1, in2);
9912   andl(tmp1, 0x00000007);
9913   negl(tmp1);
9914   addl(tmp1, in2);
9915   addq(tmp1, in1);
9916 
9917   BIND(L_wordByWord);
9918   cmpq(in1, tmp1);
9919   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9920     crc32(in_out, Address(in1, 0), 4);
9921     addq(in1, 4);
9922     jmp(L_wordByWord);
9923 
9924   BIND(L_byteByByteProlog);
9925   andl(in2, 0x00000007);
9926   movl(tmp2, 1);
9927 
9928   BIND(L_byteByByte);
9929   cmpl(tmp2, in2);
9930   jccb(Assembler::greater, L_exit);
9931     crc32(in_out, Address(in1, 0), 1);
9932     incq(in1);
9933     incl(tmp2);
9934     jmp(L_byteByByte);
9935 
9936   BIND(L_exit);
9937 }
9938 #else
9939 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9940                                           Register tmp1, Register  tmp2, Register tmp3,
9941                                           Register tmp4, Register  tmp5, Register tmp6,
9942                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9943                                           bool is_pclmulqdq_supported) {
9944   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9945   Label L_wordByWord;
9946   Label L_byteByByteProlog;
9947   Label L_byteByByte;
9948   Label L_exit;
9949 
9950   if (is_pclmulqdq_supported) {
9951     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9952     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
9953 
9954     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9955     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9956 
9957     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9958     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9959   } else {
9960     const_or_pre_comp_const_index[0] = 1;
9961     const_or_pre_comp_const_index[1] = 0;
9962 
9963     const_or_pre_comp_const_index[2] = 3;
9964     const_or_pre_comp_const_index[3] = 2;
9965 
9966     const_or_pre_comp_const_index[4] = 5;
9967     const_or_pre_comp_const_index[5] = 4;
9968   }
9969   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9970                     in2, in1, in_out,
9971                     tmp1, tmp2, tmp3,
9972                     w_xtmp1, w_xtmp2, w_xtmp3,
9973                     tmp4, tmp5,
9974                     tmp6);
9975   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9976                     in2, in1, in_out,
9977                     tmp1, tmp2, tmp3,
9978                     w_xtmp1, w_xtmp2, w_xtmp3,
9979                     tmp4, tmp5,
9980                     tmp6);
9981   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9982                     in2, in1, in_out,
9983                     tmp1, tmp2, tmp3,
9984                     w_xtmp1, w_xtmp2, w_xtmp3,
9985                     tmp4, tmp5,
9986                     tmp6);
9987   movl(tmp1, in2);
9988   andl(tmp1, 0x00000007);
9989   negl(tmp1);
9990   addl(tmp1, in2);
9991   addl(tmp1, in1);
9992 
9993   BIND(L_wordByWord);
9994   cmpl(in1, tmp1);
9995   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9996     crc32(in_out, Address(in1,0), 4);
9997     addl(in1, 4);
9998     jmp(L_wordByWord);
9999 
10000   BIND(L_byteByByteProlog);
10001   andl(in2, 0x00000007);
10002   movl(tmp2, 1);
10003 
10004   BIND(L_byteByByte);
10005   cmpl(tmp2, in2);
10006   jccb(Assembler::greater, L_exit);
10007     movb(tmp1, Address(in1, 0));
10008     crc32(in_out, tmp1, 1);
10009     incl(in1);
10010     incl(tmp2);
10011     jmp(L_byteByByte);
10012 
10013   BIND(L_exit);
10014 }
10015 #endif // LP64
10016 #undef BIND
10017 #undef BLOCK_COMMENT
10018 
10019 // Compress char[] array to byte[].
10020 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10021 //   @HotSpotIntrinsicCandidate
10022 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10023 //     for (int i = 0; i < len; i++) {
10024 //       int c = src[srcOff++];
10025 //       if (c >>> 8 != 0) {
10026 //         return 0;
10027 //       }
10028 //       dst[dstOff++] = (byte)c;
10029 //     }
10030 //     return len;
10031 //   }
10032 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10033   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10034   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10035   Register tmp5, Register result) {
10036   Label copy_chars_loop, return_length, return_zero, done;
10037 
10038   // rsi: src
10039   // rdi: dst
10040   // rdx: len
10041   // rcx: tmp5
10042   // rax: result
10043 
10044   // rsi holds start addr of source char[] to be compressed
10045   // rdi holds start addr of destination byte[]
10046   // rdx holds length
10047 
10048   assert(len != result, "");
10049 
10050   // save length for return
10051   push(len);
10052 
10053   if ((UseAVX > 2) && // AVX512
10054     VM_Version::supports_avx512vlbw() &&
10055     VM_Version::supports_bmi2()) {
10056 
10057     Label copy_32_loop, copy_loop_tail, below_threshold;
10058 
10059     // alignment
10060     Label post_alignment;
10061 
10062     // if length of the string is less than 16, handle it in an old fashioned way
10063     testl(len, -32);
10064     jcc(Assembler::zero, below_threshold);
10065 
10066     // First check whether a character is compressable ( <= 0xFF).
10067     // Create mask to test for Unicode chars inside zmm vector
10068     movl(result, 0x00FF);
10069     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10070 
10071     testl(len, -64);
10072     jcc(Assembler::zero, post_alignment);
10073 
10074     movl(tmp5, dst);
10075     andl(tmp5, (32 - 1));
10076     negl(tmp5);
10077     andl(tmp5, (32 - 1));
10078 
10079     // bail out when there is nothing to be done
10080     testl(tmp5, 0xFFFFFFFF);
10081     jcc(Assembler::zero, post_alignment);
10082 
10083     // ~(~0 << len), where len is the # of remaining elements to process
10084     movl(result, 0xFFFFFFFF);
10085     shlxl(result, result, tmp5);
10086     notl(result);
10087     kmovdl(k3, result);
10088 
10089     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
10090     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10091     ktestd(k2, k3);
10092     jcc(Assembler::carryClear, return_zero);
10093 
10094     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
10095 
10096     addptr(src, tmp5);
10097     addptr(src, tmp5);
10098     addptr(dst, tmp5);
10099     subl(len, tmp5);
10100 
10101     bind(post_alignment);
10102     // end of alignment
10103 
10104     movl(tmp5, len);
10105     andl(tmp5, (32 - 1));    // tail count (in chars)
10106     andl(len, ~(32 - 1));    // vector count (in chars)
10107     jcc(Assembler::zero, copy_loop_tail);
10108 
10109     lea(src, Address(src, len, Address::times_2));
10110     lea(dst, Address(dst, len, Address::times_1));
10111     negptr(len);
10112 
10113     bind(copy_32_loop);
10114     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10115     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10116     kortestdl(k2, k2);
10117     jcc(Assembler::carryClear, return_zero);
10118 
10119     // All elements in current processed chunk are valid candidates for
10120     // compression. Write a truncated byte elements to the memory.
10121     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10122     addptr(len, 32);
10123     jcc(Assembler::notZero, copy_32_loop);
10124 
10125     bind(copy_loop_tail);
10126     // bail out when there is nothing to be done
10127     testl(tmp5, 0xFFFFFFFF);
10128     jcc(Assembler::zero, return_length);
10129 
10130     movl(len, tmp5);
10131 
10132     // ~(~0 << len), where len is the # of remaining elements to process
10133     movl(result, 0xFFFFFFFF);
10134     shlxl(result, result, len);
10135     notl(result);
10136 
10137     kmovdl(k3, result);
10138 
10139     evmovdquw(tmp1Reg, k3, Address(src, 0), Assembler::AVX_512bit);
10140     evpcmpuw(k2, k3, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10141     ktestd(k2, k3);
10142     jcc(Assembler::carryClear, return_zero);
10143 
10144     evpmovwb(Address(dst, 0), k3, tmp1Reg, Assembler::AVX_512bit);
10145     jmp(return_length);
10146 
10147     bind(below_threshold);
10148   }
10149 
10150   if (UseSSE42Intrinsics) {
10151     Label copy_32_loop, copy_16, copy_tail;
10152 
10153     movl(result, len);
10154 
10155     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10156 
10157     // vectored compression
10158     andl(len, 0xfffffff0);    // vector count (in chars)
10159     andl(result, 0x0000000f);    // tail count (in chars)
10160     testl(len, len);
10161     jcc(Assembler::zero, copy_16);
10162 
10163     // compress 16 chars per iter
10164     movdl(tmp1Reg, tmp5);
10165     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10166     pxor(tmp4Reg, tmp4Reg);
10167 
10168     lea(src, Address(src, len, Address::times_2));
10169     lea(dst, Address(dst, len, Address::times_1));
10170     negptr(len);
10171 
10172     bind(copy_32_loop);
10173     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10174     por(tmp4Reg, tmp2Reg);
10175     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10176     por(tmp4Reg, tmp3Reg);
10177     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10178     jcc(Assembler::notZero, return_zero);
10179     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10180     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10181     addptr(len, 16);
10182     jcc(Assembler::notZero, copy_32_loop);
10183 
10184     // compress next vector of 8 chars (if any)
10185     bind(copy_16);
10186     movl(len, result);
10187     andl(len, 0xfffffff8);    // vector count (in chars)
10188     andl(result, 0x00000007);    // tail count (in chars)
10189     testl(len, len);
10190     jccb(Assembler::zero, copy_tail);
10191 
10192     movdl(tmp1Reg, tmp5);
10193     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10194     pxor(tmp3Reg, tmp3Reg);
10195 
10196     movdqu(tmp2Reg, Address(src, 0));
10197     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10198     jccb(Assembler::notZero, return_zero);
10199     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10200     movq(Address(dst, 0), tmp2Reg);
10201     addptr(src, 16);
10202     addptr(dst, 8);
10203 
10204     bind(copy_tail);
10205     movl(len, result);
10206   }
10207   // compress 1 char per iter
10208   testl(len, len);
10209   jccb(Assembler::zero, return_length);
10210   lea(src, Address(src, len, Address::times_2));
10211   lea(dst, Address(dst, len, Address::times_1));
10212   negptr(len);
10213 
10214   bind(copy_chars_loop);
10215   load_unsigned_short(result, Address(src, len, Address::times_2));
10216   testl(result, 0xff00);      // check if Unicode char
10217   jccb(Assembler::notZero, return_zero);
10218   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10219   increment(len);
10220   jcc(Assembler::notZero, copy_chars_loop);
10221 
10222   // if compression succeeded, return length
10223   bind(return_length);
10224   pop(result);
10225   jmpb(done);
10226 
10227   // if compression failed, return 0
10228   bind(return_zero);
10229   xorl(result, result);
10230   addptr(rsp, wordSize);
10231 
10232   bind(done);
10233 }
10234 
10235 // Inflate byte[] array to char[].
10236 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10237 //   @HotSpotIntrinsicCandidate
10238 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10239 //     for (int i = 0; i < len; i++) {
10240 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10241 //     }
10242 //   }
10243 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10244   XMMRegister tmp1, Register tmp2) {
10245   Label copy_chars_loop, done, below_threshold;
10246   // rsi: src
10247   // rdi: dst
10248   // rdx: len
10249   // rcx: tmp2
10250 
10251   // rsi holds start addr of source byte[] to be inflated
10252   // rdi holds start addr of destination char[]
10253   // rdx holds length
10254   assert_different_registers(src, dst, len, tmp2);
10255 
10256   if ((UseAVX > 2) && // AVX512
10257     VM_Version::supports_avx512vlbw() &&
10258     VM_Version::supports_bmi2()) {
10259 
10260     Label copy_32_loop, copy_tail;
10261     Register tmp3_aliased = len;
10262 
10263     // if length of the string is less than 16, handle it in an old fashioned way
10264     testl(len, -16);
10265     jcc(Assembler::zero, below_threshold);
10266 
10267     // In order to use only one arithmetic operation for the main loop we use
10268     // this pre-calculation
10269     movl(tmp2, len);
10270     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10271     andl(len, -32);     // vector count
10272     jccb(Assembler::zero, copy_tail);
10273 
10274     lea(src, Address(src, len, Address::times_1));
10275     lea(dst, Address(dst, len, Address::times_2));
10276     negptr(len);
10277 
10278 
10279     // inflate 32 chars per iter
10280     bind(copy_32_loop);
10281     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10282     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10283     addptr(len, 32);
10284     jcc(Assembler::notZero, copy_32_loop);
10285 
10286     bind(copy_tail);
10287     // bail out when there is nothing to be done
10288     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10289     jcc(Assembler::zero, done);
10290 
10291     // ~(~0 << length), where length is the # of remaining elements to process
10292     movl(tmp3_aliased, -1);
10293     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10294     notl(tmp3_aliased);
10295     kmovdl(k2, tmp3_aliased);
10296     evpmovzxbw(tmp1, k2, Address(src, 0), Assembler::AVX_512bit);
10297     evmovdquw(Address(dst, 0), k2, tmp1, Assembler::AVX_512bit);
10298 
10299     jmp(done);
10300   }
10301   if (UseSSE42Intrinsics) {
10302     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10303 
10304     movl(tmp2, len);
10305 
10306     if (UseAVX > 1) {
10307       andl(tmp2, (16 - 1));
10308       andl(len, -16);
10309       jccb(Assembler::zero, copy_new_tail);
10310     } else {
10311       andl(tmp2, 0x00000007);   // tail count (in chars)
10312       andl(len, 0xfffffff8);    // vector count (in chars)
10313       jccb(Assembler::zero, copy_tail);
10314     }
10315 
10316     // vectored inflation
10317     lea(src, Address(src, len, Address::times_1));
10318     lea(dst, Address(dst, len, Address::times_2));
10319     negptr(len);
10320 
10321     if (UseAVX > 1) {
10322       bind(copy_16_loop);
10323       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10324       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10325       addptr(len, 16);
10326       jcc(Assembler::notZero, copy_16_loop);
10327 
10328       bind(below_threshold);
10329       bind(copy_new_tail);
10330       if ((UseAVX > 2) &&
10331         VM_Version::supports_avx512vlbw() &&
10332         VM_Version::supports_bmi2()) {
10333         movl(tmp2, len);
10334       } else {
10335         movl(len, tmp2);
10336       }
10337       andl(tmp2, 0x00000007);
10338       andl(len, 0xFFFFFFF8);
10339       jccb(Assembler::zero, copy_tail);
10340 
10341       pmovzxbw(tmp1, Address(src, 0));
10342       movdqu(Address(dst, 0), tmp1);
10343       addptr(src, 8);
10344       addptr(dst, 2 * 8);
10345 
10346       jmp(copy_tail, true);
10347     }
10348 
10349     // inflate 8 chars per iter
10350     bind(copy_8_loop);
10351     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10352     movdqu(Address(dst, len, Address::times_2), tmp1);
10353     addptr(len, 8);
10354     jcc(Assembler::notZero, copy_8_loop);
10355 
10356     bind(copy_tail);
10357     movl(len, tmp2);
10358 
10359     cmpl(len, 4);
10360     jccb(Assembler::less, copy_bytes);
10361 
10362     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10363     pmovzxbw(tmp1, tmp1);
10364     movq(Address(dst, 0), tmp1);
10365     subptr(len, 4);
10366     addptr(src, 4);
10367     addptr(dst, 8);
10368 
10369     bind(copy_bytes);
10370   } else {
10371     bind(below_threshold);
10372   }
10373 
10374   testl(len, len);
10375   jccb(Assembler::zero, done);
10376   lea(src, Address(src, len, Address::times_1));
10377   lea(dst, Address(dst, len, Address::times_2));
10378   negptr(len);
10379 
10380   // inflate 1 char per iter
10381   bind(copy_chars_loop);
10382   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10383   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10384   increment(len);
10385   jcc(Assembler::notZero, copy_chars_loop);
10386 
10387   bind(done);
10388 }
10389 
10390 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10391   switch (cond) {
10392     // Note some conditions are synonyms for others
10393     case Assembler::zero:         return Assembler::notZero;
10394     case Assembler::notZero:      return Assembler::zero;
10395     case Assembler::less:         return Assembler::greaterEqual;
10396     case Assembler::lessEqual:    return Assembler::greater;
10397     case Assembler::greater:      return Assembler::lessEqual;
10398     case Assembler::greaterEqual: return Assembler::less;
10399     case Assembler::below:        return Assembler::aboveEqual;
10400     case Assembler::belowEqual:   return Assembler::above;
10401     case Assembler::above:        return Assembler::belowEqual;
10402     case Assembler::aboveEqual:   return Assembler::below;
10403     case Assembler::overflow:     return Assembler::noOverflow;
10404     case Assembler::noOverflow:   return Assembler::overflow;
10405     case Assembler::negative:     return Assembler::positive;
10406     case Assembler::positive:     return Assembler::negative;
10407     case Assembler::parity:       return Assembler::noParity;
10408     case Assembler::noParity:     return Assembler::parity;
10409   }
10410   ShouldNotReachHere(); return Assembler::overflow;
10411 }
10412 
10413 SkipIfEqual::SkipIfEqual(
10414     MacroAssembler* masm, const bool* flag_addr, bool value) {
10415   _masm = masm;
10416   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10417   _masm->jcc(Assembler::equal, _label);
10418 }
10419 
10420 SkipIfEqual::~SkipIfEqual() {
10421   _masm->bind(_label);
10422 }
10423 
10424 // 32-bit Windows has its own fast-path implementation
10425 // of get_thread
10426 #if !defined(WIN32) || defined(_LP64)
10427 
10428 // This is simply a call to Thread::current()
10429 void MacroAssembler::get_thread(Register thread) {
10430   if (thread != rax) {
10431     push(rax);
10432   }
10433   LP64_ONLY(push(rdi);)
10434   LP64_ONLY(push(rsi);)
10435   push(rdx);
10436   push(rcx);
10437 #ifdef _LP64
10438   push(r8);
10439   push(r9);
10440   push(r10);
10441   push(r11);
10442 #endif
10443 
10444   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10445 
10446 #ifdef _LP64
10447   pop(r11);
10448   pop(r10);
10449   pop(r9);
10450   pop(r8);
10451 #endif
10452   pop(rcx);
10453   pop(rdx);
10454   LP64_ONLY(pop(rsi);)
10455   LP64_ONLY(pop(rdi);)
10456   if (thread != rax) {
10457     mov(thread, rax);
10458     pop(rax);
10459   }
10460 }
10461 
10462 #endif