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