1 /*
   2  * Copyright (c) 1997, 2017, 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 "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "runtime/thread.hpp"
  43 #include "utilities/macros.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1CollectedHeap.inline.hpp"
  46 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  47 #include "gc/g1/heapRegion.hpp"
  48 #endif // INCLUDE_ALL_GCS
  49 #include "crc32c.h"
  50 #ifdef COMPILER2
  51 #include "opto/intrinsicnode.hpp"
  52 #endif
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #define STOP(error) stop(error)
  57 #else
  58 #define BLOCK_COMMENT(str) block_comment(str)
  59 #define STOP(error) block_comment(error); stop(error)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 #ifdef ASSERT
  65 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  66 #endif
  67 
  68 static Assembler::Condition reverse[] = {
  69     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  70     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  71     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  72     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  73     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  74     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  75     Assembler::above          /* belowEqual    = 0x6 */ ,
  76     Assembler::belowEqual     /* above         = 0x7 */ ,
  77     Assembler::positive       /* negative      = 0x8 */ ,
  78     Assembler::negative       /* positive      = 0x9 */ ,
  79     Assembler::noParity       /* parity        = 0xa */ ,
  80     Assembler::parity         /* noParity      = 0xb */ ,
  81     Assembler::greaterEqual   /* less          = 0xc */ ,
  82     Assembler::less           /* greaterEqual  = 0xd */ ,
  83     Assembler::greater        /* lessEqual     = 0xe */ ,
  84     Assembler::lessEqual      /* greater       = 0xf, */
  85 
  86 };
  87 
  88 
  89 // Implementation of MacroAssembler
  90 
  91 // First all the versions that have distinct versions depending on 32/64 bit
  92 // Unless the difference is trivial (1 line or so).
  93 
  94 #ifndef _LP64
  95 
  96 // 32bit versions
  97 
  98 Address MacroAssembler::as_Address(AddressLiteral adr) {
  99   return Address(adr.target(), adr.rspec());
 100 }
 101 
 102 Address MacroAssembler::as_Address(ArrayAddress adr) {
 103   return Address::make_array(adr);
 104 }
 105 
 106 void MacroAssembler::call_VM_leaf_base(address entry_point,
 107                                        int number_of_arguments) {
 108   call(RuntimeAddress(entry_point));
 109   increment(rsp, number_of_arguments * wordSize);
 110 }
 111 
 112 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 113   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 114 }
 115 
 116 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 117   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 121   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 125   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 126 }
 127 
 128 void MacroAssembler::extend_sign(Register hi, Register lo) {
 129   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 130   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 131     cdql();
 132   } else {
 133     movl(hi, lo);
 134     sarl(hi, 31);
 135   }
 136 }
 137 
 138 void MacroAssembler::jC2(Register tmp, Label& L) {
 139   // set parity bit if FPU flag C2 is set (via rax)
 140   save_rax(tmp);
 141   fwait(); fnstsw_ax();
 142   sahf();
 143   restore_rax(tmp);
 144   // branch
 145   jcc(Assembler::parity, L);
 146 }
 147 
 148 void MacroAssembler::jnC2(Register tmp, Label& L) {
 149   // set parity bit if FPU flag C2 is set (via rax)
 150   save_rax(tmp);
 151   fwait(); fnstsw_ax();
 152   sahf();
 153   restore_rax(tmp);
 154   // branch
 155   jcc(Assembler::noParity, L);
 156 }
 157 
 158 // 32bit can do a case table jump in one instruction but we no longer allow the base
 159 // to be installed in the Address class
 160 void MacroAssembler::jump(ArrayAddress entry) {
 161   jmp(as_Address(entry));
 162 }
 163 
 164 // Note: y_lo will be destroyed
 165 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 166   // Long compare for Java (semantics as described in JVM spec.)
 167   Label high, low, done;
 168 
 169   cmpl(x_hi, y_hi);
 170   jcc(Assembler::less, low);
 171   jcc(Assembler::greater, high);
 172   // x_hi is the return register
 173   xorl(x_hi, x_hi);
 174   cmpl(x_lo, y_lo);
 175   jcc(Assembler::below, low);
 176   jcc(Assembler::equal, done);
 177 
 178   bind(high);
 179   xorl(x_hi, x_hi);
 180   increment(x_hi);
 181   jmp(done);
 182 
 183   bind(low);
 184   xorl(x_hi, x_hi);
 185   decrementl(x_hi);
 186 
 187   bind(done);
 188 }
 189 
 190 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 191     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 192 }
 193 
 194 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 195   // leal(dst, as_Address(adr));
 196   // see note in movl as to why we must use a move
 197   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 198 }
 199 
 200 void MacroAssembler::leave() {
 201   mov(rsp, rbp);
 202   pop(rbp);
 203 }
 204 
 205 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 206   // Multiplication of two Java long values stored on the stack
 207   // as illustrated below. Result is in rdx:rax.
 208   //
 209   // rsp ---> [  ??  ] \               \
 210   //            ....    | y_rsp_offset  |
 211   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 212   //          [ y_hi ]                  | (in bytes)
 213   //            ....                    |
 214   //          [ x_lo ]                 /
 215   //          [ x_hi ]
 216   //            ....
 217   //
 218   // Basic idea: lo(result) = lo(x_lo * y_lo)
 219   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 220   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 221   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 222   Label quick;
 223   // load x_hi, y_hi and check if quick
 224   // multiplication is possible
 225   movl(rbx, x_hi);
 226   movl(rcx, y_hi);
 227   movl(rax, rbx);
 228   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 229   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 230   // do full multiplication
 231   // 1st step
 232   mull(y_lo);                                    // x_hi * y_lo
 233   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 234   // 2nd step
 235   movl(rax, x_lo);
 236   mull(rcx);                                     // x_lo * y_hi
 237   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 238   // 3rd step
 239   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 240   movl(rax, x_lo);
 241   mull(y_lo);                                    // x_lo * y_lo
 242   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 243 }
 244 
 245 void MacroAssembler::lneg(Register hi, Register lo) {
 246   negl(lo);
 247   adcl(hi, 0);
 248   negl(hi);
 249 }
 250 
 251 void MacroAssembler::lshl(Register hi, Register lo) {
 252   // Java shift left long support (semantics as described in JVM spec., p.305)
 253   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 254   // shift value is in rcx !
 255   assert(hi != rcx, "must not use rcx");
 256   assert(lo != rcx, "must not use rcx");
 257   const Register s = rcx;                        // shift count
 258   const int      n = BitsPerWord;
 259   Label L;
 260   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 261   cmpl(s, n);                                    // if (s < n)
 262   jcc(Assembler::less, L);                       // else (s >= n)
 263   movl(hi, lo);                                  // x := x << n
 264   xorl(lo, lo);
 265   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 266   bind(L);                                       // s (mod n) < n
 267   shldl(hi, lo);                                 // x := x << s
 268   shll(lo);
 269 }
 270 
 271 
 272 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 273   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 274   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 275   assert(hi != rcx, "must not use rcx");
 276   assert(lo != rcx, "must not use rcx");
 277   const Register s = rcx;                        // shift count
 278   const int      n = BitsPerWord;
 279   Label L;
 280   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 281   cmpl(s, n);                                    // if (s < n)
 282   jcc(Assembler::less, L);                       // else (s >= n)
 283   movl(lo, hi);                                  // x := x >> n
 284   if (sign_extension) sarl(hi, 31);
 285   else                xorl(hi, hi);
 286   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 287   bind(L);                                       // s (mod n) < n
 288   shrdl(lo, hi);                                 // x := x >> s
 289   if (sign_extension) sarl(hi);
 290   else                shrl(hi);
 291 }
 292 
 293 void MacroAssembler::movoop(Register dst, jobject obj) {
 294   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 295 }
 296 
 297 void MacroAssembler::movoop(Address dst, jobject obj) {
 298   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 302   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 306   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 307 }
 308 
 309 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 310   // scratch register is not used,
 311   // it is defined to match parameters of 64-bit version of this method.
 312   if (src.is_lval()) {
 313     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 314   } else {
 315     movl(dst, as_Address(src));
 316   }
 317 }
 318 
 319 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 320   movl(as_Address(dst), src);
 321 }
 322 
 323 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 324   movl(dst, as_Address(src));
 325 }
 326 
 327 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 328 void MacroAssembler::movptr(Address dst, intptr_t src) {
 329   movl(dst, src);
 330 }
 331 
 332 
 333 void MacroAssembler::pop_callee_saved_registers() {
 334   pop(rcx);
 335   pop(rdx);
 336   pop(rdi);
 337   pop(rsi);
 338 }
 339 
 340 void MacroAssembler::pop_fTOS() {
 341   fld_d(Address(rsp, 0));
 342   addl(rsp, 2 * wordSize);
 343 }
 344 
 345 void MacroAssembler::push_callee_saved_registers() {
 346   push(rsi);
 347   push(rdi);
 348   push(rdx);
 349   push(rcx);
 350 }
 351 
 352 void MacroAssembler::push_fTOS() {
 353   subl(rsp, 2 * wordSize);
 354   fstp_d(Address(rsp, 0));
 355 }
 356 
 357 
 358 void MacroAssembler::pushoop(jobject obj) {
 359   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 360 }
 361 
 362 void MacroAssembler::pushklass(Metadata* obj) {
 363   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 364 }
 365 
 366 void MacroAssembler::pushptr(AddressLiteral src) {
 367   if (src.is_lval()) {
 368     push_literal32((int32_t)src.target(), src.rspec());
 369   } else {
 370     pushl(as_Address(src));
 371   }
 372 }
 373 
 374 void MacroAssembler::set_word_if_not_zero(Register dst) {
 375   xorl(dst, dst);
 376   set_byte_if_not_zero(dst);
 377 }
 378 
 379 static void pass_arg0(MacroAssembler* masm, Register arg) {
 380   masm->push(arg);
 381 }
 382 
 383 static void pass_arg1(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg2(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 static void pass_arg3(MacroAssembler* masm, Register arg) {
 392   masm->push(arg);
 393 }
 394 
 395 #ifndef PRODUCT
 396 extern "C" void findpc(intptr_t x);
 397 #endif
 398 
 399 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 400   // In order to get locks to work, we need to fake a in_VM state
 401   JavaThread* thread = JavaThread::current();
 402   JavaThreadState saved_state = thread->thread_state();
 403   thread->set_thread_state(_thread_in_vm);
 404   if (ShowMessageBoxOnError) {
 405     JavaThread* thread = JavaThread::current();
 406     JavaThreadState saved_state = thread->thread_state();
 407     thread->set_thread_state(_thread_in_vm);
 408     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 409       ttyLocker ttyl;
 410       BytecodeCounter::print();
 411     }
 412     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 413     // This is the value of eip which points to where verify_oop will return.
 414     if (os::message_box(msg, "Execution stopped, print registers?")) {
 415       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 416       BREAKPOINT;
 417     }
 418   } else {
 419     ttyLocker ttyl;
 420     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 421   }
 422   // Don't assert holding the ttyLock
 423     assert(false, "DEBUG MESSAGE: %s", msg);
 424   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 425 }
 426 
 427 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 428   ttyLocker ttyl;
 429   FlagSetting fs(Debugging, true);
 430   tty->print_cr("eip = 0x%08x", eip);
 431 #ifndef PRODUCT
 432   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 433     tty->cr();
 434     findpc(eip);
 435     tty->cr();
 436   }
 437 #endif
 438 #define PRINT_REG(rax) \
 439   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 440   PRINT_REG(rax);
 441   PRINT_REG(rbx);
 442   PRINT_REG(rcx);
 443   PRINT_REG(rdx);
 444   PRINT_REG(rdi);
 445   PRINT_REG(rsi);
 446   PRINT_REG(rbp);
 447   PRINT_REG(rsp);
 448 #undef PRINT_REG
 449   // Print some words near top of staack.
 450   int* dump_sp = (int*) rsp;
 451   for (int col1 = 0; col1 < 8; col1++) {
 452     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 453     os::print_location(tty, *dump_sp++);
 454   }
 455   for (int row = 0; row < 16; row++) {
 456     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 457     for (int col = 0; col < 8; col++) {
 458       tty->print(" 0x%08x", *dump_sp++);
 459     }
 460     tty->cr();
 461   }
 462   // Print some instructions around pc:
 463   Disassembler::decode((address)eip-64, (address)eip);
 464   tty->print_cr("--------");
 465   Disassembler::decode((address)eip, (address)eip+32);
 466 }
 467 
 468 void MacroAssembler::stop(const char* msg) {
 469   ExternalAddress message((address)msg);
 470   // push address of message
 471   pushptr(message.addr());
 472   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 473   pusha();                                            // push registers
 474   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 475   hlt();
 476 }
 477 
 478 void MacroAssembler::warn(const char* msg) {
 479   push_CPU_state();
 480 
 481   ExternalAddress message((address) msg);
 482   // push address of message
 483   pushptr(message.addr());
 484 
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 486   addl(rsp, wordSize);       // discard argument
 487   pop_CPU_state();
 488 }
 489 
 490 void MacroAssembler::print_state() {
 491   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 492   pusha();                                            // push registers
 493 
 494   push_CPU_state();
 495   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 496   pop_CPU_state();
 497 
 498   popa();
 499   addl(rsp, wordSize);
 500 }
 501 
 502 #else // _LP64
 503 
 504 // 64 bit versions
 505 
 506 Address MacroAssembler::as_Address(AddressLiteral adr) {
 507   // amd64 always does this as a pc-rel
 508   // we can be absolute or disp based on the instruction type
 509   // jmp/call are displacements others are absolute
 510   assert(!adr.is_lval(), "must be rval");
 511   assert(reachable(adr), "must be");
 512   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 513 
 514 }
 515 
 516 Address MacroAssembler::as_Address(ArrayAddress adr) {
 517   AddressLiteral base = adr.base();
 518   lea(rscratch1, base);
 519   Address index = adr.index();
 520   assert(index._disp == 0, "must not have disp"); // maybe it can?
 521   Address array(rscratch1, index._index, index._scale, index._disp);
 522   return array;
 523 }
 524 
 525 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 526   Label L, E;
 527 
 528 #ifdef _WIN64
 529   // Windows always allocates space for it's register args
 530   assert(num_args <= 4, "only register arguments supported");
 531   subq(rsp,  frame::arg_reg_save_area_bytes);
 532 #endif
 533 
 534   // Align stack if necessary
 535   testl(rsp, 15);
 536   jcc(Assembler::zero, L);
 537 
 538   subq(rsp, 8);
 539   {
 540     call(RuntimeAddress(entry_point));
 541   }
 542   addq(rsp, 8);
 543   jmp(E);
 544 
 545   bind(L);
 546   {
 547     call(RuntimeAddress(entry_point));
 548   }
 549 
 550   bind(E);
 551 
 552 #ifdef _WIN64
 553   // restore stack pointer
 554   addq(rsp, frame::arg_reg_save_area_bytes);
 555 #endif
 556 
 557 }
 558 
 559 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 560   assert(!src2.is_lval(), "should use cmpptr");
 561 
 562   if (reachable(src2)) {
 563     cmpq(src1, as_Address(src2));
 564   } else {
 565     lea(rscratch1, src2);
 566     Assembler::cmpq(src1, Address(rscratch1, 0));
 567   }
 568 }
 569 
 570 int MacroAssembler::corrected_idivq(Register reg) {
 571   // Full implementation of Java ldiv and lrem; checks for special
 572   // case as described in JVM spec., p.243 & p.271.  The function
 573   // returns the (pc) offset of the idivl instruction - may be needed
 574   // for implicit exceptions.
 575   //
 576   //         normal case                           special case
 577   //
 578   // input : rax: dividend                         min_long
 579   //         reg: divisor   (may not be eax/edx)   -1
 580   //
 581   // output: rax: quotient  (= rax idiv reg)       min_long
 582   //         rdx: remainder (= rax irem reg)       0
 583   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 584   static const int64_t min_long = 0x8000000000000000;
 585   Label normal_case, special_case;
 586 
 587   // check for special case
 588   cmp64(rax, ExternalAddress((address) &min_long));
 589   jcc(Assembler::notEqual, normal_case);
 590   xorl(rdx, rdx); // prepare rdx for possible special case (where
 591                   // remainder = 0)
 592   cmpq(reg, -1);
 593   jcc(Assembler::equal, special_case);
 594 
 595   // handle normal case
 596   bind(normal_case);
 597   cdqq();
 598   int idivq_offset = offset();
 599   idivq(reg);
 600 
 601   // normal and special case exit
 602   bind(special_case);
 603 
 604   return idivq_offset;
 605 }
 606 
 607 void MacroAssembler::decrementq(Register reg, int value) {
 608   if (value == min_jint) { subq(reg, value); return; }
 609   if (value <  0) { incrementq(reg, -value); return; }
 610   if (value == 0) {                        ; return; }
 611   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 612   /* else */      { subq(reg, value)       ; return; }
 613 }
 614 
 615 void MacroAssembler::decrementq(Address dst, int value) {
 616   if (value == min_jint) { subq(dst, value); return; }
 617   if (value <  0) { incrementq(dst, -value); return; }
 618   if (value == 0) {                        ; return; }
 619   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 620   /* else */      { subq(dst, value)       ; return; }
 621 }
 622 
 623 void MacroAssembler::incrementq(AddressLiteral dst) {
 624   if (reachable(dst)) {
 625     incrementq(as_Address(dst));
 626   } else {
 627     lea(rscratch1, dst);
 628     incrementq(Address(rscratch1, 0));
 629   }
 630 }
 631 
 632 void MacroAssembler::incrementq(Register reg, int value) {
 633   if (value == min_jint) { addq(reg, value); return; }
 634   if (value <  0) { decrementq(reg, -value); return; }
 635   if (value == 0) {                        ; return; }
 636   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 637   /* else */      { addq(reg, value)       ; return; }
 638 }
 639 
 640 void MacroAssembler::incrementq(Address dst, int value) {
 641   if (value == min_jint) { addq(dst, value); return; }
 642   if (value <  0) { decrementq(dst, -value); return; }
 643   if (value == 0) {                        ; return; }
 644   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 645   /* else */      { addq(dst, value)       ; return; }
 646 }
 647 
 648 // 32bit can do a case table jump in one instruction but we no longer allow the base
 649 // to be installed in the Address class
 650 void MacroAssembler::jump(ArrayAddress entry) {
 651   lea(rscratch1, entry.base());
 652   Address dispatch = entry.index();
 653   assert(dispatch._base == noreg, "must be");
 654   dispatch._base = rscratch1;
 655   jmp(dispatch);
 656 }
 657 
 658 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 659   ShouldNotReachHere(); // 64bit doesn't use two regs
 660   cmpq(x_lo, y_lo);
 661 }
 662 
 663 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 664     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 665 }
 666 
 667 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 668   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 669   movptr(dst, rscratch1);
 670 }
 671 
 672 void MacroAssembler::leave() {
 673   // %%% is this really better? Why not on 32bit too?
 674   emit_int8((unsigned char)0xC9); // LEAVE
 675 }
 676 
 677 void MacroAssembler::lneg(Register hi, Register lo) {
 678   ShouldNotReachHere(); // 64bit doesn't use two regs
 679   negq(lo);
 680 }
 681 
 682 void MacroAssembler::movoop(Register dst, jobject obj) {
 683   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 684 }
 685 
 686 void MacroAssembler::movoop(Address dst, jobject obj) {
 687   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 688   movq(dst, rscratch1);
 689 }
 690 
 691 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 692   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 693 }
 694 
 695 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 696   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 697   movq(dst, rscratch1);
 698 }
 699 
 700 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 701   if (src.is_lval()) {
 702     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 703   } else {
 704     if (reachable(src)) {
 705       movq(dst, as_Address(src));
 706     } else {
 707       lea(scratch, src);
 708       movq(dst, Address(scratch, 0));
 709     }
 710   }
 711 }
 712 
 713 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 714   movq(as_Address(dst), src);
 715 }
 716 
 717 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 718   movq(dst, as_Address(src));
 719 }
 720 
 721 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 722 void MacroAssembler::movptr(Address dst, intptr_t src) {
 723   mov64(rscratch1, src);
 724   movq(dst, rscratch1);
 725 }
 726 
 727 // These are mostly for initializing NULL
 728 void MacroAssembler::movptr(Address dst, int32_t src) {
 729   movslq(dst, src);
 730 }
 731 
 732 void MacroAssembler::movptr(Register dst, int32_t src) {
 733   mov64(dst, (intptr_t)src);
 734 }
 735 
 736 void MacroAssembler::pushoop(jobject obj) {
 737   movoop(rscratch1, obj);
 738   push(rscratch1);
 739 }
 740 
 741 void MacroAssembler::pushklass(Metadata* obj) {
 742   mov_metadata(rscratch1, obj);
 743   push(rscratch1);
 744 }
 745 
 746 void MacroAssembler::pushptr(AddressLiteral src) {
 747   lea(rscratch1, src);
 748   if (src.is_lval()) {
 749     push(rscratch1);
 750   } else {
 751     pushq(Address(rscratch1, 0));
 752   }
 753 }
 754 
 755 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 756   // we must set sp to zero to clear frame
 757   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 758   // must clear fp, so that compiled frames are not confused; it is
 759   // possible that we need it only for debugging
 760   if (clear_fp) {
 761     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 762   }
 763 
 764   // Always clear the pc because it could have been set by make_walkable()
 765   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 766   vzeroupper();
 767 }
 768 
 769 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 770                                          Register last_java_fp,
 771                                          address  last_java_pc) {
 772   vzeroupper();
 773   // determine last_java_sp register
 774   if (!last_java_sp->is_valid()) {
 775     last_java_sp = rsp;
 776   }
 777 
 778   // last_java_fp is optional
 779   if (last_java_fp->is_valid()) {
 780     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 781            last_java_fp);
 782   }
 783 
 784   // last_java_pc is optional
 785   if (last_java_pc != NULL) {
 786     Address java_pc(r15_thread,
 787                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 788     lea(rscratch1, InternalAddress(last_java_pc));
 789     movptr(java_pc, rscratch1);
 790   }
 791 
 792   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 793 }
 794 
 795 static void pass_arg0(MacroAssembler* masm, Register arg) {
 796   if (c_rarg0 != arg ) {
 797     masm->mov(c_rarg0, arg);
 798   }
 799 }
 800 
 801 static void pass_arg1(MacroAssembler* masm, Register arg) {
 802   if (c_rarg1 != arg ) {
 803     masm->mov(c_rarg1, arg);
 804   }
 805 }
 806 
 807 static void pass_arg2(MacroAssembler* masm, Register arg) {
 808   if (c_rarg2 != arg ) {
 809     masm->mov(c_rarg2, arg);
 810   }
 811 }
 812 
 813 static void pass_arg3(MacroAssembler* masm, Register arg) {
 814   if (c_rarg3 != arg ) {
 815     masm->mov(c_rarg3, arg);
 816   }
 817 }
 818 
 819 void MacroAssembler::stop(const char* msg) {
 820   address rip = pc();
 821   pusha(); // get regs on stack
 822   lea(c_rarg0, ExternalAddress((address) msg));
 823   lea(c_rarg1, InternalAddress(rip));
 824   movq(c_rarg2, rsp); // pass pointer to regs array
 825   andq(rsp, -16); // align stack as required by ABI
 826   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 827   hlt();
 828 }
 829 
 830 void MacroAssembler::warn(const char* msg) {
 831   push(rbp);
 832   movq(rbp, rsp);
 833   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 834   push_CPU_state();   // keeps alignment at 16 bytes
 835   lea(c_rarg0, ExternalAddress((address) msg));
 836   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 837   pop_CPU_state();
 838   mov(rsp, rbp);
 839   pop(rbp);
 840 }
 841 
 842 void MacroAssembler::print_state() {
 843   address rip = pc();
 844   pusha();            // get regs on stack
 845   push(rbp);
 846   movq(rbp, rsp);
 847   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 848   push_CPU_state();   // keeps alignment at 16 bytes
 849 
 850   lea(c_rarg0, InternalAddress(rip));
 851   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 852   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 853 
 854   pop_CPU_state();
 855   mov(rsp, rbp);
 856   pop(rbp);
 857   popa();
 858 }
 859 
 860 #ifndef PRODUCT
 861 extern "C" void findpc(intptr_t x);
 862 #endif
 863 
 864 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 865   // In order to get locks to work, we need to fake a in_VM state
 866   if (ShowMessageBoxOnError) {
 867     JavaThread* thread = JavaThread::current();
 868     JavaThreadState saved_state = thread->thread_state();
 869     thread->set_thread_state(_thread_in_vm);
 870 #ifndef PRODUCT
 871     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 872       ttyLocker ttyl;
 873       BytecodeCounter::print();
 874     }
 875 #endif
 876     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 877     // XXX correct this offset for amd64
 878     // This is the value of eip which points to where verify_oop will return.
 879     if (os::message_box(msg, "Execution stopped, print registers?")) {
 880       print_state64(pc, regs);
 881       BREAKPOINT;
 882       assert(false, "start up GDB");
 883     }
 884     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 885   } else {
 886     ttyLocker ttyl;
 887     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 888                     msg);
 889     assert(false, "DEBUG MESSAGE: %s", msg);
 890   }
 891 }
 892 
 893 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 894   ttyLocker ttyl;
 895   FlagSetting fs(Debugging, true);
 896   tty->print_cr("rip = 0x%016lx", pc);
 897 #ifndef PRODUCT
 898   tty->cr();
 899   findpc(pc);
 900   tty->cr();
 901 #endif
 902 #define PRINT_REG(rax, value) \
 903   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 904   PRINT_REG(rax, regs[15]);
 905   PRINT_REG(rbx, regs[12]);
 906   PRINT_REG(rcx, regs[14]);
 907   PRINT_REG(rdx, regs[13]);
 908   PRINT_REG(rdi, regs[8]);
 909   PRINT_REG(rsi, regs[9]);
 910   PRINT_REG(rbp, regs[10]);
 911   PRINT_REG(rsp, regs[11]);
 912   PRINT_REG(r8 , regs[7]);
 913   PRINT_REG(r9 , regs[6]);
 914   PRINT_REG(r10, regs[5]);
 915   PRINT_REG(r11, regs[4]);
 916   PRINT_REG(r12, regs[3]);
 917   PRINT_REG(r13, regs[2]);
 918   PRINT_REG(r14, regs[1]);
 919   PRINT_REG(r15, regs[0]);
 920 #undef PRINT_REG
 921   // Print some words near top of staack.
 922   int64_t* rsp = (int64_t*) regs[11];
 923   int64_t* dump_sp = rsp;
 924   for (int col1 = 0; col1 < 8; col1++) {
 925     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 926     os::print_location(tty, *dump_sp++);
 927   }
 928   for (int row = 0; row < 25; row++) {
 929     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 930     for (int col = 0; col < 4; col++) {
 931       tty->print(" 0x%016lx", *dump_sp++);
 932     }
 933     tty->cr();
 934   }
 935   // Print some instructions around pc:
 936   Disassembler::decode((address)pc-64, (address)pc);
 937   tty->print_cr("--------");
 938   Disassembler::decode((address)pc, (address)pc+32);
 939 }
 940 
 941 #endif // _LP64
 942 
 943 // Now versions that are common to 32/64 bit
 944 
 945 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 946   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 947 }
 948 
 949 void MacroAssembler::addptr(Register dst, Register src) {
 950   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 951 }
 952 
 953 void MacroAssembler::addptr(Address dst, Register src) {
 954   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 955 }
 956 
 957 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 958   if (reachable(src)) {
 959     Assembler::addsd(dst, as_Address(src));
 960   } else {
 961     lea(rscratch1, src);
 962     Assembler::addsd(dst, Address(rscratch1, 0));
 963   }
 964 }
 965 
 966 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 967   if (reachable(src)) {
 968     addss(dst, as_Address(src));
 969   } else {
 970     lea(rscratch1, src);
 971     addss(dst, Address(rscratch1, 0));
 972   }
 973 }
 974 
 975 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 976   if (reachable(src)) {
 977     Assembler::addpd(dst, as_Address(src));
 978   } else {
 979     lea(rscratch1, src);
 980     Assembler::addpd(dst, Address(rscratch1, 0));
 981   }
 982 }
 983 
 984 void MacroAssembler::align(int modulus) {
 985   align(modulus, offset());
 986 }
 987 
 988 void MacroAssembler::align(int modulus, int target) {
 989   if (target % modulus != 0) {
 990     nop(modulus - (target % modulus));
 991   }
 992 }
 993 
 994 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 995   // Used in sign-masking with aligned address.
 996   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 997   if (reachable(src)) {
 998     Assembler::andpd(dst, as_Address(src));
 999   } else {
1000     lea(rscratch1, src);
1001     Assembler::andpd(dst, Address(rscratch1, 0));
1002   }
1003 }
1004 
1005 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1006   // Used in sign-masking with aligned address.
1007   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1008   if (reachable(src)) {
1009     Assembler::andps(dst, as_Address(src));
1010   } else {
1011     lea(rscratch1, src);
1012     Assembler::andps(dst, Address(rscratch1, 0));
1013   }
1014 }
1015 
1016 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1017   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1018 }
1019 
1020 void MacroAssembler::atomic_incl(Address counter_addr) {
1021   if (os::is_MP())
1022     lock();
1023   incrementl(counter_addr);
1024 }
1025 
1026 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1027   if (reachable(counter_addr)) {
1028     atomic_incl(as_Address(counter_addr));
1029   } else {
1030     lea(scr, counter_addr);
1031     atomic_incl(Address(scr, 0));
1032   }
1033 }
1034 
1035 #ifdef _LP64
1036 void MacroAssembler::atomic_incq(Address counter_addr) {
1037   if (os::is_MP())
1038     lock();
1039   incrementq(counter_addr);
1040 }
1041 
1042 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1043   if (reachable(counter_addr)) {
1044     atomic_incq(as_Address(counter_addr));
1045   } else {
1046     lea(scr, counter_addr);
1047     atomic_incq(Address(scr, 0));
1048   }
1049 }
1050 #endif
1051 
1052 // Writes to stack successive pages until offset reached to check for
1053 // stack overflow + shadow pages.  This clobbers tmp.
1054 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1055   movptr(tmp, rsp);
1056   // Bang stack for total size given plus shadow page size.
1057   // Bang one page at a time because large size can bang beyond yellow and
1058   // red zones.
1059   Label loop;
1060   bind(loop);
1061   movl(Address(tmp, (-os::vm_page_size())), size );
1062   subptr(tmp, os::vm_page_size());
1063   subl(size, os::vm_page_size());
1064   jcc(Assembler::greater, loop);
1065 
1066   // Bang down shadow pages too.
1067   // At this point, (tmp-0) is the last address touched, so don't
1068   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1069   // was post-decremented.)  Skip this address by starting at i=1, and
1070   // touch a few more pages below.  N.B.  It is important to touch all
1071   // the way down including all pages in the shadow zone.
1072   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1073     // this could be any sized move but this is can be a debugging crumb
1074     // so the bigger the better.
1075     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1076   }
1077 }
1078 
1079 void MacroAssembler::reserved_stack_check() {
1080     // testing if reserved zone needs to be enabled
1081     Label no_reserved_zone_enabling;
1082     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1083     NOT_LP64(get_thread(rsi);)
1084 
1085     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1086     jcc(Assembler::below, no_reserved_zone_enabling);
1087 
1088     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1089     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1090     should_not_reach_here();
1091 
1092     bind(no_reserved_zone_enabling);
1093 }
1094 
1095 int MacroAssembler::biased_locking_enter(Register lock_reg,
1096                                          Register obj_reg,
1097                                          Register swap_reg,
1098                                          Register tmp_reg,
1099                                          bool swap_reg_contains_mark,
1100                                          Label& done,
1101                                          Label* slow_case,
1102                                          BiasedLockingCounters* counters) {
1103   assert(UseBiasedLocking, "why call this otherwise?");
1104   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1105   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1106   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1107   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1108   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1109   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1110 
1111   if (PrintBiasedLockingStatistics && counters == NULL) {
1112     counters = BiasedLocking::counters();
1113   }
1114   // Biased locking
1115   // See whether the lock is currently biased toward our thread and
1116   // whether the epoch is still valid
1117   // Note that the runtime guarantees sufficient alignment of JavaThread
1118   // pointers to allow age to be placed into low bits
1119   // First check to see whether biasing is even enabled for this object
1120   Label cas_label;
1121   int null_check_offset = -1;
1122   if (!swap_reg_contains_mark) {
1123     null_check_offset = offset();
1124     movptr(swap_reg, mark_addr);
1125   }
1126   movptr(tmp_reg, swap_reg);
1127   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1128   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1129   jcc(Assembler::notEqual, cas_label);
1130   // The bias pattern is present in the object's header. Need to check
1131   // whether the bias owner and the epoch are both still current.
1132 #ifndef _LP64
1133   // Note that because there is no current thread register on x86_32 we
1134   // need to store off the mark word we read out of the object to
1135   // avoid reloading it and needing to recheck invariants below. This
1136   // store is unfortunate but it makes the overall code shorter and
1137   // simpler.
1138   movptr(saved_mark_addr, swap_reg);
1139 #endif
1140   if (swap_reg_contains_mark) {
1141     null_check_offset = offset();
1142   }
1143   load_prototype_header(tmp_reg, obj_reg);
1144 #ifdef _LP64
1145   orptr(tmp_reg, r15_thread);
1146   xorptr(tmp_reg, swap_reg);
1147   Register header_reg = tmp_reg;
1148 #else
1149   xorptr(tmp_reg, swap_reg);
1150   get_thread(swap_reg);
1151   xorptr(swap_reg, tmp_reg);
1152   Register header_reg = swap_reg;
1153 #endif
1154   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1155   if (counters != NULL) {
1156     cond_inc32(Assembler::zero,
1157                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1158   }
1159   jcc(Assembler::equal, done);
1160 
1161   Label try_revoke_bias;
1162   Label try_rebias;
1163 
1164   // At this point we know that the header has the bias pattern and
1165   // that we are not the bias owner in the current epoch. We need to
1166   // figure out more details about the state of the header in order to
1167   // know what operations can be legally performed on the object's
1168   // header.
1169 
1170   // If the low three bits in the xor result aren't clear, that means
1171   // the prototype header is no longer biased and we have to revoke
1172   // the bias on this object.
1173   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1174   jccb(Assembler::notZero, try_revoke_bias);
1175 
1176   // Biasing is still enabled for this data type. See whether the
1177   // epoch of the current bias is still valid, meaning that the epoch
1178   // bits of the mark word are equal to the epoch bits of the
1179   // prototype header. (Note that the prototype header's epoch bits
1180   // only change at a safepoint.) If not, attempt to rebias the object
1181   // toward the current thread. Note that we must be absolutely sure
1182   // that the current epoch is invalid in order to do this because
1183   // otherwise the manipulations it performs on the mark word are
1184   // illegal.
1185   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1186   jccb(Assembler::notZero, try_rebias);
1187 
1188   // The epoch of the current bias is still valid but we know nothing
1189   // about the owner; it might be set or it might be clear. Try to
1190   // acquire the bias of the object using an atomic operation. If this
1191   // fails we will go in to the runtime to revoke the object's bias.
1192   // Note that we first construct the presumed unbiased header so we
1193   // don't accidentally blow away another thread's valid bias.
1194   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1195   andptr(swap_reg,
1196          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1197 #ifdef _LP64
1198   movptr(tmp_reg, swap_reg);
1199   orptr(tmp_reg, r15_thread);
1200 #else
1201   get_thread(tmp_reg);
1202   orptr(tmp_reg, swap_reg);
1203 #endif
1204   if (os::is_MP()) {
1205     lock();
1206   }
1207   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1208   // If the biasing toward our thread failed, this means that
1209   // another thread succeeded in biasing it toward itself and we
1210   // need to revoke that bias. The revocation will occur in the
1211   // interpreter runtime in the slow case.
1212   if (counters != NULL) {
1213     cond_inc32(Assembler::zero,
1214                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1215   }
1216   if (slow_case != NULL) {
1217     jcc(Assembler::notZero, *slow_case);
1218   }
1219   jmp(done);
1220 
1221   bind(try_rebias);
1222   // At this point we know the epoch has expired, meaning that the
1223   // current "bias owner", if any, is actually invalid. Under these
1224   // circumstances _only_, we are allowed to use the current header's
1225   // value as the comparison value when doing the cas to acquire the
1226   // bias in the current epoch. In other words, we allow transfer of
1227   // the bias from one thread to another directly in this situation.
1228   //
1229   // FIXME: due to a lack of registers we currently blow away the age
1230   // bits in this situation. Should attempt to preserve them.
1231   load_prototype_header(tmp_reg, obj_reg);
1232 #ifdef _LP64
1233   orptr(tmp_reg, r15_thread);
1234 #else
1235   get_thread(swap_reg);
1236   orptr(tmp_reg, swap_reg);
1237   movptr(swap_reg, saved_mark_addr);
1238 #endif
1239   if (os::is_MP()) {
1240     lock();
1241   }
1242   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1243   // If the biasing toward our thread failed, then another thread
1244   // succeeded in biasing it toward itself and we need to revoke that
1245   // bias. The revocation will occur in the runtime in the slow case.
1246   if (counters != NULL) {
1247     cond_inc32(Assembler::zero,
1248                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1249   }
1250   if (slow_case != NULL) {
1251     jcc(Assembler::notZero, *slow_case);
1252   }
1253   jmp(done);
1254 
1255   bind(try_revoke_bias);
1256   // The prototype mark in the klass doesn't have the bias bit set any
1257   // more, indicating that objects of this data type are not supposed
1258   // to be biased any more. We are going to try to reset the mark of
1259   // this object to the prototype value and fall through to the
1260   // CAS-based locking scheme. Note that if our CAS fails, it means
1261   // that another thread raced us for the privilege of revoking the
1262   // bias of this particular object, so it's okay to continue in the
1263   // normal locking code.
1264   //
1265   // FIXME: due to a lack of registers we currently blow away the age
1266   // bits in this situation. Should attempt to preserve them.
1267   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1268   load_prototype_header(tmp_reg, obj_reg);
1269   if (os::is_MP()) {
1270     lock();
1271   }
1272   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1273   // Fall through to the normal CAS-based lock, because no matter what
1274   // the result of the above CAS, some thread must have succeeded in
1275   // removing the bias bit from the object's header.
1276   if (counters != NULL) {
1277     cond_inc32(Assembler::zero,
1278                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1279   }
1280 
1281   bind(cas_label);
1282 
1283   return null_check_offset;
1284 }
1285 
1286 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1287   assert(UseBiasedLocking, "why call this otherwise?");
1288 
1289   // Check for biased locking unlock case, which is a no-op
1290   // Note: we do not have to check the thread ID for two reasons.
1291   // First, the interpreter checks for IllegalMonitorStateException at
1292   // a higher level. Second, if the bias was revoked while we held the
1293   // lock, the object could not be rebiased toward another thread, so
1294   // the bias bit would be clear.
1295   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1296   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1297   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1298   jcc(Assembler::equal, done);
1299 }
1300 
1301 #ifdef COMPILER2
1302 
1303 #if INCLUDE_RTM_OPT
1304 
1305 // Update rtm_counters based on abort status
1306 // input: abort_status
1307 //        rtm_counters (RTMLockingCounters*)
1308 // flags are killed
1309 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1310 
1311   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1312   if (PrintPreciseRTMLockingStatistics) {
1313     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1314       Label check_abort;
1315       testl(abort_status, (1<<i));
1316       jccb(Assembler::equal, check_abort);
1317       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1318       bind(check_abort);
1319     }
1320   }
1321 }
1322 
1323 // Branch if (random & (count-1) != 0), count is 2^n
1324 // tmp, scr and flags are killed
1325 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1326   assert(tmp == rax, "");
1327   assert(scr == rdx, "");
1328   rdtsc(); // modifies EDX:EAX
1329   andptr(tmp, count-1);
1330   jccb(Assembler::notZero, brLabel);
1331 }
1332 
1333 // Perform abort ratio calculation, set no_rtm bit if high ratio
1334 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1335 // tmpReg, rtm_counters_Reg and flags are killed
1336 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1337                                                  Register rtm_counters_Reg,
1338                                                  RTMLockingCounters* rtm_counters,
1339                                                  Metadata* method_data) {
1340   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1341 
1342   if (RTMLockingCalculationDelay > 0) {
1343     // Delay calculation
1344     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1345     testptr(tmpReg, tmpReg);
1346     jccb(Assembler::equal, L_done);
1347   }
1348   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1349   //   Aborted transactions = abort_count * 100
1350   //   All transactions = total_count *  RTMTotalCountIncrRate
1351   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1352 
1353   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1354   cmpptr(tmpReg, RTMAbortThreshold);
1355   jccb(Assembler::below, L_check_always_rtm2);
1356   imulptr(tmpReg, tmpReg, 100);
1357 
1358   Register scrReg = rtm_counters_Reg;
1359   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1360   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1361   imulptr(scrReg, scrReg, RTMAbortRatio);
1362   cmpptr(tmpReg, scrReg);
1363   jccb(Assembler::below, L_check_always_rtm1);
1364   if (method_data != NULL) {
1365     // set rtm_state to "no rtm" in MDO
1366     mov_metadata(tmpReg, method_data);
1367     if (os::is_MP()) {
1368       lock();
1369     }
1370     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1371   }
1372   jmpb(L_done);
1373   bind(L_check_always_rtm1);
1374   // Reload RTMLockingCounters* address
1375   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1376   bind(L_check_always_rtm2);
1377   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1378   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1379   jccb(Assembler::below, L_done);
1380   if (method_data != NULL) {
1381     // set rtm_state to "always rtm" in MDO
1382     mov_metadata(tmpReg, method_data);
1383     if (os::is_MP()) {
1384       lock();
1385     }
1386     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1387   }
1388   bind(L_done);
1389 }
1390 
1391 // Update counters and perform abort ratio calculation
1392 // input:  abort_status_Reg
1393 // rtm_counters_Reg, flags are killed
1394 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1395                                    Register rtm_counters_Reg,
1396                                    RTMLockingCounters* rtm_counters,
1397                                    Metadata* method_data,
1398                                    bool profile_rtm) {
1399 
1400   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1401   // update rtm counters based on rax value at abort
1402   // reads abort_status_Reg, updates flags
1403   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1404   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1405   if (profile_rtm) {
1406     // Save abort status because abort_status_Reg is used by following code.
1407     if (RTMRetryCount > 0) {
1408       push(abort_status_Reg);
1409     }
1410     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1411     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1412     // restore abort status
1413     if (RTMRetryCount > 0) {
1414       pop(abort_status_Reg);
1415     }
1416   }
1417 }
1418 
1419 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1420 // inputs: retry_count_Reg
1421 //       : abort_status_Reg
1422 // output: retry_count_Reg decremented by 1
1423 // flags are killed
1424 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1425   Label doneRetry;
1426   assert(abort_status_Reg == rax, "");
1427   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1428   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1429   // if reason is in 0x6 and retry count != 0 then retry
1430   andptr(abort_status_Reg, 0x6);
1431   jccb(Assembler::zero, doneRetry);
1432   testl(retry_count_Reg, retry_count_Reg);
1433   jccb(Assembler::zero, doneRetry);
1434   pause();
1435   decrementl(retry_count_Reg);
1436   jmp(retryLabel);
1437   bind(doneRetry);
1438 }
1439 
1440 // Spin and retry if lock is busy,
1441 // inputs: box_Reg (monitor address)
1442 //       : retry_count_Reg
1443 // output: retry_count_Reg decremented by 1
1444 //       : clear z flag if retry count exceeded
1445 // tmp_Reg, scr_Reg, flags are killed
1446 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1447                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1448   Label SpinLoop, SpinExit, doneRetry;
1449   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1450 
1451   testl(retry_count_Reg, retry_count_Reg);
1452   jccb(Assembler::zero, doneRetry);
1453   decrementl(retry_count_Reg);
1454   movptr(scr_Reg, RTMSpinLoopCount);
1455 
1456   bind(SpinLoop);
1457   pause();
1458   decrementl(scr_Reg);
1459   jccb(Assembler::lessEqual, SpinExit);
1460   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1461   testptr(tmp_Reg, tmp_Reg);
1462   jccb(Assembler::notZero, SpinLoop);
1463 
1464   bind(SpinExit);
1465   jmp(retryLabel);
1466   bind(doneRetry);
1467   incrementl(retry_count_Reg); // clear z flag
1468 }
1469 
1470 // Use RTM for normal stack locks
1471 // Input: objReg (object to lock)
1472 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1473                                        Register retry_on_abort_count_Reg,
1474                                        RTMLockingCounters* stack_rtm_counters,
1475                                        Metadata* method_data, bool profile_rtm,
1476                                        Label& DONE_LABEL, Label& IsInflated) {
1477   assert(UseRTMForStackLocks, "why call this otherwise?");
1478   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1479   assert(tmpReg == rax, "");
1480   assert(scrReg == rdx, "");
1481   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1482 
1483   if (RTMRetryCount > 0) {
1484     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1485     bind(L_rtm_retry);
1486   }
1487   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1488   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1489   jcc(Assembler::notZero, IsInflated);
1490 
1491   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1492     Label L_noincrement;
1493     if (RTMTotalCountIncrRate > 1) {
1494       // tmpReg, scrReg and flags are killed
1495       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1496     }
1497     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1498     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1499     bind(L_noincrement);
1500   }
1501   xbegin(L_on_abort);
1502   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1503   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1504   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1505   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1506 
1507   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1508   if (UseRTMXendForLockBusy) {
1509     xend();
1510     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1511     jmp(L_decrement_retry);
1512   }
1513   else {
1514     xabort(0);
1515   }
1516   bind(L_on_abort);
1517   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1518     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1519   }
1520   bind(L_decrement_retry);
1521   if (RTMRetryCount > 0) {
1522     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1523     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1524   }
1525 }
1526 
1527 // Use RTM for inflating locks
1528 // inputs: objReg (object to lock)
1529 //         boxReg (on-stack box address (displaced header location) - KILLED)
1530 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1531 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1532                                           Register scrReg, Register retry_on_busy_count_Reg,
1533                                           Register retry_on_abort_count_Reg,
1534                                           RTMLockingCounters* rtm_counters,
1535                                           Metadata* method_data, bool profile_rtm,
1536                                           Label& DONE_LABEL) {
1537   assert(UseRTMLocking, "why call this otherwise?");
1538   assert(tmpReg == rax, "");
1539   assert(scrReg == rdx, "");
1540   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1541   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1542 
1543   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1544   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1545   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1546 
1547   if (RTMRetryCount > 0) {
1548     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1549     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1550     bind(L_rtm_retry);
1551   }
1552   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1553     Label L_noincrement;
1554     if (RTMTotalCountIncrRate > 1) {
1555       // tmpReg, scrReg and flags are killed
1556       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1557     }
1558     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1559     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1560     bind(L_noincrement);
1561   }
1562   xbegin(L_on_abort);
1563   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1564   movptr(tmpReg, Address(tmpReg, owner_offset));
1565   testptr(tmpReg, tmpReg);
1566   jcc(Assembler::zero, DONE_LABEL);
1567   if (UseRTMXendForLockBusy) {
1568     xend();
1569     jmp(L_decrement_retry);
1570   }
1571   else {
1572     xabort(0);
1573   }
1574   bind(L_on_abort);
1575   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1576   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1577     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1578   }
1579   if (RTMRetryCount > 0) {
1580     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1581     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1582   }
1583 
1584   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1585   testptr(tmpReg, tmpReg) ;
1586   jccb(Assembler::notZero, L_decrement_retry) ;
1587 
1588   // Appears unlocked - try to swing _owner from null to non-null.
1589   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1590 #ifdef _LP64
1591   Register threadReg = r15_thread;
1592 #else
1593   get_thread(scrReg);
1594   Register threadReg = scrReg;
1595 #endif
1596   if (os::is_MP()) {
1597     lock();
1598   }
1599   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1600 
1601   if (RTMRetryCount > 0) {
1602     // success done else retry
1603     jccb(Assembler::equal, DONE_LABEL) ;
1604     bind(L_decrement_retry);
1605     // Spin and retry if lock is busy.
1606     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1607   }
1608   else {
1609     bind(L_decrement_retry);
1610   }
1611 }
1612 
1613 #endif //  INCLUDE_RTM_OPT
1614 
1615 // Fast_Lock and Fast_Unlock used by C2
1616 
1617 // Because the transitions from emitted code to the runtime
1618 // monitorenter/exit helper stubs are so slow it's critical that
1619 // we inline both the stack-locking fast-path and the inflated fast path.
1620 //
1621 // See also: cmpFastLock and cmpFastUnlock.
1622 //
1623 // What follows is a specialized inline transliteration of the code
1624 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1625 // another option would be to emit TrySlowEnter and TrySlowExit methods
1626 // at startup-time.  These methods would accept arguments as
1627 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1628 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1629 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1630 // In practice, however, the # of lock sites is bounded and is usually small.
1631 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1632 // if the processor uses simple bimodal branch predictors keyed by EIP
1633 // Since the helper routines would be called from multiple synchronization
1634 // sites.
1635 //
1636 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1637 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1638 // to those specialized methods.  That'd give us a mostly platform-independent
1639 // implementation that the JITs could optimize and inline at their pleasure.
1640 // Done correctly, the only time we'd need to cross to native could would be
1641 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1642 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1643 // (b) explicit barriers or fence operations.
1644 //
1645 // TODO:
1646 //
1647 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1648 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1649 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1650 //    the lock operators would typically be faster than reifying Self.
1651 //
1652 // *  Ideally I'd define the primitives as:
1653 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1654 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1655 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1656 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1657 //    Furthermore the register assignments are overconstrained, possibly resulting in
1658 //    sub-optimal code near the synchronization site.
1659 //
1660 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1661 //    Alternately, use a better sp-proximity test.
1662 //
1663 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1664 //    Either one is sufficient to uniquely identify a thread.
1665 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1666 //
1667 // *  Intrinsify notify() and notifyAll() for the common cases where the
1668 //    object is locked by the calling thread but the waitlist is empty.
1669 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1670 //
1671 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1672 //    But beware of excessive branch density on AMD Opterons.
1673 //
1674 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1675 //    or failure of the fast-path.  If the fast-path fails then we pass
1676 //    control to the slow-path, typically in C.  In Fast_Lock and
1677 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1678 //    will emit a conditional branch immediately after the node.
1679 //    So we have branches to branches and lots of ICC.ZF games.
1680 //    Instead, it might be better to have C2 pass a "FailureLabel"
1681 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1682 //    will drop through the node.  ICC.ZF is undefined at exit.
1683 //    In the case of failure, the node will branch directly to the
1684 //    FailureLabel
1685 
1686 
1687 // obj: object to lock
1688 // box: on-stack box address (displaced header location) - KILLED
1689 // rax,: tmp -- KILLED
1690 // scr: tmp -- KILLED
1691 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1692                                Register scrReg, Register cx1Reg, Register cx2Reg,
1693                                BiasedLockingCounters* counters,
1694                                RTMLockingCounters* rtm_counters,
1695                                RTMLockingCounters* stack_rtm_counters,
1696                                Metadata* method_data,
1697                                bool use_rtm, bool profile_rtm) {
1698   // Ensure the register assignments are disjoint
1699   assert(tmpReg == rax, "");
1700 
1701   if (use_rtm) {
1702     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1703   } else {
1704     assert(cx1Reg == noreg, "");
1705     assert(cx2Reg == noreg, "");
1706     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1707   }
1708 
1709   if (counters != NULL) {
1710     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1711   }
1712   if (EmitSync & 1) {
1713       // set box->dhw = markOopDesc::unused_mark()
1714       // Force all sync thru slow-path: slow_enter() and slow_exit()
1715       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1716       cmpptr (rsp, (int32_t)NULL_WORD);
1717   } else {
1718     // Possible cases that we'll encounter in fast_lock
1719     // ------------------------------------------------
1720     // * Inflated
1721     //    -- unlocked
1722     //    -- Locked
1723     //       = by self
1724     //       = by other
1725     // * biased
1726     //    -- by Self
1727     //    -- by other
1728     // * neutral
1729     // * stack-locked
1730     //    -- by self
1731     //       = sp-proximity test hits
1732     //       = sp-proximity test generates false-negative
1733     //    -- by other
1734     //
1735 
1736     Label IsInflated, DONE_LABEL;
1737 
1738     // it's stack-locked, biased or neutral
1739     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1740     // order to reduce the number of conditional branches in the most common cases.
1741     // Beware -- there's a subtle invariant that fetch of the markword
1742     // at [FETCH], below, will never observe a biased encoding (*101b).
1743     // If this invariant is not held we risk exclusion (safety) failure.
1744     if (UseBiasedLocking && !UseOptoBiasInlining) {
1745       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1746     }
1747 
1748 #if INCLUDE_RTM_OPT
1749     if (UseRTMForStackLocks && use_rtm) {
1750       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1751                         stack_rtm_counters, method_data, profile_rtm,
1752                         DONE_LABEL, IsInflated);
1753     }
1754 #endif // INCLUDE_RTM_OPT
1755 
1756     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1757     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1758     jccb(Assembler::notZero, IsInflated);
1759 
1760     // Attempt stack-locking ...
1761     orptr (tmpReg, markOopDesc::unlocked_value);
1762     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1763     if (os::is_MP()) {
1764       lock();
1765     }
1766     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1767     if (counters != NULL) {
1768       cond_inc32(Assembler::equal,
1769                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1770     }
1771     jcc(Assembler::equal, DONE_LABEL);           // Success
1772 
1773     // Recursive locking.
1774     // The object is stack-locked: markword contains stack pointer to BasicLock.
1775     // Locked by current thread if difference with current SP is less than one page.
1776     subptr(tmpReg, rsp);
1777     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1778     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1779     movptr(Address(boxReg, 0), tmpReg);
1780     if (counters != NULL) {
1781       cond_inc32(Assembler::equal,
1782                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1783     }
1784     jmp(DONE_LABEL);
1785 
1786     bind(IsInflated);
1787     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1788 
1789 #if INCLUDE_RTM_OPT
1790     // Use the same RTM locking code in 32- and 64-bit VM.
1791     if (use_rtm) {
1792       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1793                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1794     } else {
1795 #endif // INCLUDE_RTM_OPT
1796 
1797 #ifndef _LP64
1798     // The object is inflated.
1799 
1800     // boxReg refers to the on-stack BasicLock in the current frame.
1801     // We'd like to write:
1802     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1803     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1804     // additional latency as we have another ST in the store buffer that must drain.
1805 
1806     if (EmitSync & 8192) {
1807        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1808        get_thread (scrReg);
1809        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1810        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1811        if (os::is_MP()) {
1812          lock();
1813        }
1814        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1815     } else
1816     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1817        // register juggle because we need tmpReg for cmpxchgptr below
1818        movptr(scrReg, boxReg);
1819        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1820 
1821        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1822        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1823           // prefetchw [eax + Offset(_owner)-2]
1824           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1825        }
1826 
1827        if ((EmitSync & 64) == 0) {
1828          // Optimistic form: consider XORL tmpReg,tmpReg
1829          movptr(tmpReg, NULL_WORD);
1830        } else {
1831          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1832          // Test-And-CAS instead of CAS
1833          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1834          testptr(tmpReg, tmpReg);                   // Locked ?
1835          jccb  (Assembler::notZero, DONE_LABEL);
1836        }
1837 
1838        // Appears unlocked - try to swing _owner from null to non-null.
1839        // Ideally, I'd manifest "Self" with get_thread and then attempt
1840        // to CAS the register containing Self into m->Owner.
1841        // But we don't have enough registers, so instead we can either try to CAS
1842        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1843        // we later store "Self" into m->Owner.  Transiently storing a stack address
1844        // (rsp or the address of the box) into  m->owner is harmless.
1845        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1846        if (os::is_MP()) {
1847          lock();
1848        }
1849        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1850        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1851        // If we weren't able to swing _owner from NULL to the BasicLock
1852        // then take the slow path.
1853        jccb  (Assembler::notZero, DONE_LABEL);
1854        // update _owner from BasicLock to thread
1855        get_thread (scrReg);                    // beware: clobbers ICCs
1856        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1857        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1858 
1859        // If the CAS fails we can either retry or pass control to the slow-path.
1860        // We use the latter tactic.
1861        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1862        // If the CAS was successful ...
1863        //   Self has acquired the lock
1864        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1865        // Intentional fall-through into DONE_LABEL ...
1866     } else {
1867        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1868        movptr(boxReg, tmpReg);
1869 
1870        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1871        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1872           // prefetchw [eax + Offset(_owner)-2]
1873           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1874        }
1875 
1876        if ((EmitSync & 64) == 0) {
1877          // Optimistic form
1878          xorptr  (tmpReg, tmpReg);
1879        } else {
1880          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1881          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1882          testptr(tmpReg, tmpReg);                   // Locked ?
1883          jccb  (Assembler::notZero, DONE_LABEL);
1884        }
1885 
1886        // Appears unlocked - try to swing _owner from null to non-null.
1887        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1888        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1889        get_thread (scrReg);
1890        if (os::is_MP()) {
1891          lock();
1892        }
1893        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1894 
1895        // If the CAS fails we can either retry or pass control to the slow-path.
1896        // We use the latter tactic.
1897        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1898        // If the CAS was successful ...
1899        //   Self has acquired the lock
1900        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1901        // Intentional fall-through into DONE_LABEL ...
1902     }
1903 #else // _LP64
1904     // It's inflated
1905     movq(scrReg, tmpReg);
1906     xorq(tmpReg, tmpReg);
1907 
1908     if (os::is_MP()) {
1909       lock();
1910     }
1911     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1912     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1913     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1914     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1915     // Intentional fall-through into DONE_LABEL ...
1916     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1917 #endif // _LP64
1918 #if INCLUDE_RTM_OPT
1919     } // use_rtm()
1920 #endif
1921     // DONE_LABEL is a hot target - we'd really like to place it at the
1922     // start of cache line by padding with NOPs.
1923     // See the AMD and Intel software optimization manuals for the
1924     // most efficient "long" NOP encodings.
1925     // Unfortunately none of our alignment mechanisms suffice.
1926     bind(DONE_LABEL);
1927 
1928     // At DONE_LABEL the icc ZFlag is set as follows ...
1929     // Fast_Unlock uses the same protocol.
1930     // ZFlag == 1 -> Success
1931     // ZFlag == 0 -> Failure - force control through the slow-path
1932   }
1933 }
1934 
1935 // obj: object to unlock
1936 // box: box address (displaced header location), killed.  Must be EAX.
1937 // tmp: killed, cannot be obj nor box.
1938 //
1939 // Some commentary on balanced locking:
1940 //
1941 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1942 // Methods that don't have provably balanced locking are forced to run in the
1943 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1944 // The interpreter provides two properties:
1945 // I1:  At return-time the interpreter automatically and quietly unlocks any
1946 //      objects acquired the current activation (frame).  Recall that the
1947 //      interpreter maintains an on-stack list of locks currently held by
1948 //      a frame.
1949 // I2:  If a method attempts to unlock an object that is not held by the
1950 //      the frame the interpreter throws IMSX.
1951 //
1952 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1953 // B() doesn't have provably balanced locking so it runs in the interpreter.
1954 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1955 // is still locked by A().
1956 //
1957 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1958 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1959 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1960 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1961 // Arguably given that the spec legislates the JNI case as undefined our implementation
1962 // could reasonably *avoid* checking owner in Fast_Unlock().
1963 // In the interest of performance we elide m->Owner==Self check in unlock.
1964 // A perfectly viable alternative is to elide the owner check except when
1965 // Xcheck:jni is enabled.
1966 
1967 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1968   assert(boxReg == rax, "");
1969   assert_different_registers(objReg, boxReg, tmpReg);
1970 
1971   if (EmitSync & 4) {
1972     // Disable - inhibit all inlining.  Force control through the slow-path
1973     cmpptr (rsp, 0);
1974   } else {
1975     Label DONE_LABEL, Stacked, CheckSucc;
1976 
1977     // Critically, the biased locking test must have precedence over
1978     // and appear before the (box->dhw == 0) recursive stack-lock test.
1979     if (UseBiasedLocking && !UseOptoBiasInlining) {
1980        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1981     }
1982 
1983 #if INCLUDE_RTM_OPT
1984     if (UseRTMForStackLocks && use_rtm) {
1985       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1986       Label L_regular_unlock;
1987       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1988       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1989       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1990       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1991       xend();                                       // otherwise end...
1992       jmp(DONE_LABEL);                              // ... and we're done
1993       bind(L_regular_unlock);
1994     }
1995 #endif
1996 
1997     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1998     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1999     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2000     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2001     jccb  (Assembler::zero, Stacked);
2002 
2003     // It's inflated.
2004 #if INCLUDE_RTM_OPT
2005     if (use_rtm) {
2006       Label L_regular_inflated_unlock;
2007       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2008       movptr(boxReg, Address(tmpReg, owner_offset));
2009       testptr(boxReg, boxReg);
2010       jccb(Assembler::notZero, L_regular_inflated_unlock);
2011       xend();
2012       jmpb(DONE_LABEL);
2013       bind(L_regular_inflated_unlock);
2014     }
2015 #endif
2016 
2017     // Despite our balanced locking property we still check that m->_owner == Self
2018     // as java routines or native JNI code called by this thread might
2019     // have released the lock.
2020     // Refer to the comments in synchronizer.cpp for how we might encode extra
2021     // state in _succ so we can avoid fetching EntryList|cxq.
2022     //
2023     // I'd like to add more cases in fast_lock() and fast_unlock() --
2024     // such as recursive enter and exit -- but we have to be wary of
2025     // I$ bloat, T$ effects and BP$ effects.
2026     //
2027     // If there's no contention try a 1-0 exit.  That is, exit without
2028     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2029     // we detect and recover from the race that the 1-0 exit admits.
2030     //
2031     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2032     // before it STs null into _owner, releasing the lock.  Updates
2033     // to data protected by the critical section must be visible before
2034     // we drop the lock (and thus before any other thread could acquire
2035     // the lock and observe the fields protected by the lock).
2036     // IA32's memory-model is SPO, so STs are ordered with respect to
2037     // each other and there's no need for an explicit barrier (fence).
2038     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2039 #ifndef _LP64
2040     get_thread (boxReg);
2041     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2042       // prefetchw [ebx + Offset(_owner)-2]
2043       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2044     }
2045 
2046     // Note that we could employ various encoding schemes to reduce
2047     // the number of loads below (currently 4) to just 2 or 3.
2048     // Refer to the comments in synchronizer.cpp.
2049     // In practice the chain of fetches doesn't seem to impact performance, however.
2050     xorptr(boxReg, boxReg);
2051     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2052        // Attempt to reduce branch density - AMD's branch predictor.
2053        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2054        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2056        jccb  (Assembler::notZero, DONE_LABEL);
2057        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2058        jmpb  (DONE_LABEL);
2059     } else {
2060        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2061        jccb  (Assembler::notZero, DONE_LABEL);
2062        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2064        jccb  (Assembler::notZero, CheckSucc);
2065        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2066        jmpb  (DONE_LABEL);
2067     }
2068 
2069     // The Following code fragment (EmitSync & 65536) improves the performance of
2070     // contended applications and contended synchronization microbenchmarks.
2071     // Unfortunately the emission of the code - even though not executed - causes regressions
2072     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2073     // with an equal number of never-executed NOPs results in the same regression.
2074     // We leave it off by default.
2075 
2076     if ((EmitSync & 65536) != 0) {
2077        Label LSuccess, LGoSlowPath ;
2078 
2079        bind  (CheckSucc);
2080 
2081        // Optional pre-test ... it's safe to elide this
2082        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2083        jccb(Assembler::zero, LGoSlowPath);
2084 
2085        // We have a classic Dekker-style idiom:
2086        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2087        // There are a number of ways to implement the barrier:
2088        // (1) lock:andl &m->_owner, 0
2089        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2090        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2091        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2092        // (2) If supported, an explicit MFENCE is appealing.
2093        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2094        //     particularly if the write-buffer is full as might be the case if
2095        //     if stores closely precede the fence or fence-equivalent instruction.
2096        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2097        //     as the situation has changed with Nehalem and Shanghai.
2098        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2099        //     The $lines underlying the top-of-stack should be in M-state.
2100        //     The locked add instruction is serializing, of course.
2101        // (4) Use xchg, which is serializing
2102        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2103        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2104        //     The integer condition codes will tell us if succ was 0.
2105        //     Since _succ and _owner should reside in the same $line and
2106        //     we just stored into _owner, it's likely that the $line
2107        //     remains in M-state for the lock:orl.
2108        //
2109        // We currently use (3), although it's likely that switching to (2)
2110        // is correct for the future.
2111 
2112        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2113        if (os::is_MP()) {
2114          lock(); addptr(Address(rsp, 0), 0);
2115        }
2116        // Ratify _succ remains non-null
2117        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2118        jccb  (Assembler::notZero, LSuccess);
2119 
2120        xorptr(boxReg, boxReg);                  // box is really EAX
2121        if (os::is_MP()) { lock(); }
2122        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2123        // There's no successor so we tried to regrab the lock with the
2124        // placeholder value. If that didn't work, then another thread
2125        // grabbed the lock so we're done (and exit was a success).
2126        jccb  (Assembler::notEqual, LSuccess);
2127        // Since we're low on registers we installed rsp as a placeholding in _owner.
2128        // Now install Self over rsp.  This is safe as we're transitioning from
2129        // non-null to non=null
2130        get_thread (boxReg);
2131        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2132        // Intentional fall-through into LGoSlowPath ...
2133 
2134        bind  (LGoSlowPath);
2135        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2136        jmpb  (DONE_LABEL);
2137 
2138        bind  (LSuccess);
2139        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2140        jmpb  (DONE_LABEL);
2141     }
2142 
2143     bind (Stacked);
2144     // It's not inflated and it's not recursively stack-locked and it's not biased.
2145     // It must be stack-locked.
2146     // Try to reset the header to displaced header.
2147     // The "box" value on the stack is stable, so we can reload
2148     // and be assured we observe the same value as above.
2149     movptr(tmpReg, Address(boxReg, 0));
2150     if (os::is_MP()) {
2151       lock();
2152     }
2153     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2154     // Intention fall-thru into DONE_LABEL
2155 
2156     // DONE_LABEL is a hot target - we'd really like to place it at the
2157     // start of cache line by padding with NOPs.
2158     // See the AMD and Intel software optimization manuals for the
2159     // most efficient "long" NOP encodings.
2160     // Unfortunately none of our alignment mechanisms suffice.
2161     if ((EmitSync & 65536) == 0) {
2162        bind (CheckSucc);
2163     }
2164 #else // _LP64
2165     // It's inflated
2166     if (EmitSync & 1024) {
2167       // Emit code to check that _owner == Self
2168       // We could fold the _owner test into subsequent code more efficiently
2169       // than using a stand-alone check, but since _owner checking is off by
2170       // default we don't bother. We also might consider predicating the
2171       // _owner==Self check on Xcheck:jni or running on a debug build.
2172       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2173       xorptr(boxReg, r15_thread);
2174     } else {
2175       xorptr(boxReg, boxReg);
2176     }
2177     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2178     jccb  (Assembler::notZero, DONE_LABEL);
2179     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2180     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2181     jccb  (Assembler::notZero, CheckSucc);
2182     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2183     jmpb  (DONE_LABEL);
2184 
2185     if ((EmitSync & 65536) == 0) {
2186       // Try to avoid passing control into the slow_path ...
2187       Label LSuccess, LGoSlowPath ;
2188       bind  (CheckSucc);
2189 
2190       // The following optional optimization can be elided if necessary
2191       // Effectively: if (succ == null) goto SlowPath
2192       // The code reduces the window for a race, however,
2193       // and thus benefits performance.
2194       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2195       jccb  (Assembler::zero, LGoSlowPath);
2196 
2197       xorptr(boxReg, boxReg);
2198       if ((EmitSync & 16) && os::is_MP()) {
2199         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2200       } else {
2201         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2202         if (os::is_MP()) {
2203           // Memory barrier/fence
2204           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2205           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2206           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2207           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2208           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2209           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2210           lock(); addl(Address(rsp, 0), 0);
2211         }
2212       }
2213       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2214       jccb  (Assembler::notZero, LSuccess);
2215 
2216       // Rare inopportune interleaving - race.
2217       // The successor vanished in the small window above.
2218       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2219       // We need to ensure progress and succession.
2220       // Try to reacquire the lock.
2221       // If that fails then the new owner is responsible for succession and this
2222       // thread needs to take no further action and can exit via the fast path (success).
2223       // If the re-acquire succeeds then pass control into the slow path.
2224       // As implemented, this latter mode is horrible because we generated more
2225       // coherence traffic on the lock *and* artifically extended the critical section
2226       // length while by virtue of passing control into the slow path.
2227 
2228       // box is really RAX -- the following CMPXCHG depends on that binding
2229       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2230       if (os::is_MP()) { lock(); }
2231       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2232       // There's no successor so we tried to regrab the lock.
2233       // If that didn't work, then another thread grabbed the
2234       // lock so we're done (and exit was a success).
2235       jccb  (Assembler::notEqual, LSuccess);
2236       // Intentional fall-through into slow-path
2237 
2238       bind  (LGoSlowPath);
2239       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2240       jmpb  (DONE_LABEL);
2241 
2242       bind  (LSuccess);
2243       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2244       jmpb  (DONE_LABEL);
2245     }
2246 
2247     bind  (Stacked);
2248     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2249     if (os::is_MP()) { lock(); }
2250     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2251 
2252     if (EmitSync & 65536) {
2253        bind (CheckSucc);
2254     }
2255 #endif
2256     bind(DONE_LABEL);
2257   }
2258 }
2259 #endif // COMPILER2
2260 
2261 void MacroAssembler::c2bool(Register x) {
2262   // implements x == 0 ? 0 : 1
2263   // note: must only look at least-significant byte of x
2264   //       since C-style booleans are stored in one byte
2265   //       only! (was bug)
2266   andl(x, 0xFF);
2267   setb(Assembler::notZero, x);
2268 }
2269 
2270 // Wouldn't need if AddressLiteral version had new name
2271 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2272   Assembler::call(L, rtype);
2273 }
2274 
2275 void MacroAssembler::call(Register entry) {
2276   Assembler::call(entry);
2277 }
2278 
2279 void MacroAssembler::call(AddressLiteral entry) {
2280   if (reachable(entry)) {
2281     Assembler::call_literal(entry.target(), entry.rspec());
2282   } else {
2283     lea(rscratch1, entry);
2284     Assembler::call(rscratch1);
2285   }
2286 }
2287 
2288 void MacroAssembler::ic_call(address entry, jint method_index) {
2289   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2290   movptr(rax, (intptr_t)Universe::non_oop_word());
2291   call(AddressLiteral(entry, rh));
2292 }
2293 
2294 // Implementation of call_VM versions
2295 
2296 void MacroAssembler::call_VM(Register oop_result,
2297                              address entry_point,
2298                              bool check_exceptions) {
2299   Label C, E;
2300   call(C, relocInfo::none);
2301   jmp(E);
2302 
2303   bind(C);
2304   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2305   ret(0);
2306 
2307   bind(E);
2308 }
2309 
2310 void MacroAssembler::call_VM(Register oop_result,
2311                              address entry_point,
2312                              Register arg_1,
2313                              bool check_exceptions) {
2314   Label C, E;
2315   call(C, relocInfo::none);
2316   jmp(E);
2317 
2318   bind(C);
2319   pass_arg1(this, arg_1);
2320   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2321   ret(0);
2322 
2323   bind(E);
2324 }
2325 
2326 void MacroAssembler::call_VM(Register oop_result,
2327                              address entry_point,
2328                              Register arg_1,
2329                              Register arg_2,
2330                              bool check_exceptions) {
2331   Label C, E;
2332   call(C, relocInfo::none);
2333   jmp(E);
2334 
2335   bind(C);
2336 
2337   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2338 
2339   pass_arg2(this, arg_2);
2340   pass_arg1(this, arg_1);
2341   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2342   ret(0);
2343 
2344   bind(E);
2345 }
2346 
2347 void MacroAssembler::call_VM(Register oop_result,
2348                              address entry_point,
2349                              Register arg_1,
2350                              Register arg_2,
2351                              Register arg_3,
2352                              bool check_exceptions) {
2353   Label C, E;
2354   call(C, relocInfo::none);
2355   jmp(E);
2356 
2357   bind(C);
2358 
2359   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2360   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2361   pass_arg3(this, arg_3);
2362 
2363   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2364   pass_arg2(this, arg_2);
2365 
2366   pass_arg1(this, arg_1);
2367   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2368   ret(0);
2369 
2370   bind(E);
2371 }
2372 
2373 void MacroAssembler::call_VM(Register oop_result,
2374                              Register last_java_sp,
2375                              address entry_point,
2376                              int number_of_arguments,
2377                              bool check_exceptions) {
2378   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2379   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2380 }
2381 
2382 void MacroAssembler::call_VM(Register oop_result,
2383                              Register last_java_sp,
2384                              address entry_point,
2385                              Register arg_1,
2386                              bool check_exceptions) {
2387   pass_arg1(this, arg_1);
2388   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2389 }
2390 
2391 void MacroAssembler::call_VM(Register oop_result,
2392                              Register last_java_sp,
2393                              address entry_point,
2394                              Register arg_1,
2395                              Register arg_2,
2396                              bool check_exceptions) {
2397 
2398   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2399   pass_arg2(this, arg_2);
2400   pass_arg1(this, arg_1);
2401   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2402 }
2403 
2404 void MacroAssembler::call_VM(Register oop_result,
2405                              Register last_java_sp,
2406                              address entry_point,
2407                              Register arg_1,
2408                              Register arg_2,
2409                              Register arg_3,
2410                              bool check_exceptions) {
2411   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2412   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2413   pass_arg3(this, arg_3);
2414   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2415   pass_arg2(this, arg_2);
2416   pass_arg1(this, arg_1);
2417   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2418 }
2419 
2420 void MacroAssembler::super_call_VM(Register oop_result,
2421                                    Register last_java_sp,
2422                                    address entry_point,
2423                                    int number_of_arguments,
2424                                    bool check_exceptions) {
2425   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2426   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2427 }
2428 
2429 void MacroAssembler::super_call_VM(Register oop_result,
2430                                    Register last_java_sp,
2431                                    address entry_point,
2432                                    Register arg_1,
2433                                    bool check_exceptions) {
2434   pass_arg1(this, arg_1);
2435   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2436 }
2437 
2438 void MacroAssembler::super_call_VM(Register oop_result,
2439                                    Register last_java_sp,
2440                                    address entry_point,
2441                                    Register arg_1,
2442                                    Register arg_2,
2443                                    bool check_exceptions) {
2444 
2445   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2446   pass_arg2(this, arg_2);
2447   pass_arg1(this, arg_1);
2448   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2449 }
2450 
2451 void MacroAssembler::super_call_VM(Register oop_result,
2452                                    Register last_java_sp,
2453                                    address entry_point,
2454                                    Register arg_1,
2455                                    Register arg_2,
2456                                    Register arg_3,
2457                                    bool check_exceptions) {
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_1 != c_rarg2, "smashed arg"));
2462   pass_arg2(this, arg_2);
2463   pass_arg1(this, arg_1);
2464   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2465 }
2466 
2467 void MacroAssembler::call_VM_base(Register oop_result,
2468                                   Register java_thread,
2469                                   Register last_java_sp,
2470                                   address  entry_point,
2471                                   int      number_of_arguments,
2472                                   bool     check_exceptions) {
2473   // determine java_thread register
2474   if (!java_thread->is_valid()) {
2475 #ifdef _LP64
2476     java_thread = r15_thread;
2477 #else
2478     java_thread = rdi;
2479     get_thread(java_thread);
2480 #endif // LP64
2481   }
2482   // determine last_java_sp register
2483   if (!last_java_sp->is_valid()) {
2484     last_java_sp = rsp;
2485   }
2486   // debugging support
2487   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2488   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2489 #ifdef ASSERT
2490   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2491   // r12 is the heapbase.
2492   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2493 #endif // ASSERT
2494 
2495   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2496   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2497 
2498   // push java thread (becomes first argument of C function)
2499 
2500   NOT_LP64(push(java_thread); number_of_arguments++);
2501   LP64_ONLY(mov(c_rarg0, r15_thread));
2502 
2503   // set last Java frame before call
2504   assert(last_java_sp != rbp, "can't use ebp/rbp");
2505 
2506   // Only interpreter should have to set fp
2507   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2508 
2509   // do the call, remove parameters
2510   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2511 
2512   // restore the thread (cannot use the pushed argument since arguments
2513   // may be overwritten by C code generated by an optimizing compiler);
2514   // however can use the register value directly if it is callee saved.
2515   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2516     // rdi & rsi (also r15) are callee saved -> nothing to do
2517 #ifdef ASSERT
2518     guarantee(java_thread != rax, "change this code");
2519     push(rax);
2520     { Label L;
2521       get_thread(rax);
2522       cmpptr(java_thread, rax);
2523       jcc(Assembler::equal, L);
2524       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2525       bind(L);
2526     }
2527     pop(rax);
2528 #endif
2529   } else {
2530     get_thread(java_thread);
2531   }
2532   // reset last Java frame
2533   // Only interpreter should have to clear fp
2534   reset_last_Java_frame(java_thread, true);
2535 
2536    // C++ interp handles this in the interpreter
2537   check_and_handle_popframe(java_thread);
2538   check_and_handle_earlyret(java_thread);
2539 
2540   if (check_exceptions) {
2541     // check for pending exceptions (java_thread is set upon return)
2542     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2543 #ifndef _LP64
2544     jump_cc(Assembler::notEqual,
2545             RuntimeAddress(StubRoutines::forward_exception_entry()));
2546 #else
2547     // This used to conditionally jump to forward_exception however it is
2548     // possible if we relocate that the branch will not reach. So we must jump
2549     // around so we can always reach
2550 
2551     Label ok;
2552     jcc(Assembler::equal, ok);
2553     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2554     bind(ok);
2555 #endif // LP64
2556   }
2557 
2558   // get oop result if there is one and reset the value in the thread
2559   if (oop_result->is_valid()) {
2560     get_vm_result(oop_result, java_thread);
2561   }
2562 }
2563 
2564 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2565 
2566   // Calculate the value for last_Java_sp
2567   // somewhat subtle. call_VM does an intermediate call
2568   // which places a return address on the stack just under the
2569   // stack pointer as the user finsihed with it. This allows
2570   // use to retrieve last_Java_pc from last_Java_sp[-1].
2571   // On 32bit we then have to push additional args on the stack to accomplish
2572   // the actual requested call. On 64bit call_VM only can use register args
2573   // so the only extra space is the return address that call_VM created.
2574   // This hopefully explains the calculations here.
2575 
2576 #ifdef _LP64
2577   // We've pushed one address, correct last_Java_sp
2578   lea(rax, Address(rsp, wordSize));
2579 #else
2580   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2581 #endif // LP64
2582 
2583   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2584 
2585 }
2586 
2587 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2588 void MacroAssembler::call_VM_leaf0(address entry_point) {
2589   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2590 }
2591 
2592 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2593   call_VM_leaf_base(entry_point, number_of_arguments);
2594 }
2595 
2596 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2597   pass_arg0(this, arg_0);
2598   call_VM_leaf(entry_point, 1);
2599 }
2600 
2601 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2602 
2603   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2604   pass_arg1(this, arg_1);
2605   pass_arg0(this, arg_0);
2606   call_VM_leaf(entry_point, 2);
2607 }
2608 
2609 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2610   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2611   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2612   pass_arg2(this, arg_2);
2613   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2614   pass_arg1(this, arg_1);
2615   pass_arg0(this, arg_0);
2616   call_VM_leaf(entry_point, 3);
2617 }
2618 
2619 void MacroAssembler::super_call_VM_leaf(address entry_point) {
2620   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2621 }
2622 
2623 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2624   pass_arg0(this, arg_0);
2625   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2626 }
2627 
2628 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2629 
2630   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2631   pass_arg1(this, arg_1);
2632   pass_arg0(this, arg_0);
2633   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2634 }
2635 
2636 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2637   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2638   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2639   pass_arg2(this, arg_2);
2640   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2641   pass_arg1(this, arg_1);
2642   pass_arg0(this, arg_0);
2643   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2644 }
2645 
2646 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2647   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2648   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2649   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2650   pass_arg3(this, arg_3);
2651   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2652   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2653   pass_arg2(this, arg_2);
2654   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2655   pass_arg1(this, arg_1);
2656   pass_arg0(this, arg_0);
2657   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2658 }
2659 
2660 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2661   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2662   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2663   verify_oop(oop_result, "broken oop in call_VM_base");
2664 }
2665 
2666 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2667   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2668   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2669 }
2670 
2671 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2672 }
2673 
2674 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2675 }
2676 
2677 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2678   if (reachable(src1)) {
2679     cmpl(as_Address(src1), imm);
2680   } else {
2681     lea(rscratch1, src1);
2682     cmpl(Address(rscratch1, 0), imm);
2683   }
2684 }
2685 
2686 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2687   assert(!src2.is_lval(), "use cmpptr");
2688   if (reachable(src2)) {
2689     cmpl(src1, as_Address(src2));
2690   } else {
2691     lea(rscratch1, src2);
2692     cmpl(src1, Address(rscratch1, 0));
2693   }
2694 }
2695 
2696 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2697   Assembler::cmpl(src1, imm);
2698 }
2699 
2700 void MacroAssembler::cmp32(Register src1, Address src2) {
2701   Assembler::cmpl(src1, src2);
2702 }
2703 
2704 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2705   ucomisd(opr1, opr2);
2706 
2707   Label L;
2708   if (unordered_is_less) {
2709     movl(dst, -1);
2710     jcc(Assembler::parity, L);
2711     jcc(Assembler::below , L);
2712     movl(dst, 0);
2713     jcc(Assembler::equal , L);
2714     increment(dst);
2715   } else { // unordered is greater
2716     movl(dst, 1);
2717     jcc(Assembler::parity, L);
2718     jcc(Assembler::above , L);
2719     movl(dst, 0);
2720     jcc(Assembler::equal , L);
2721     decrementl(dst);
2722   }
2723   bind(L);
2724 }
2725 
2726 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2727   ucomiss(opr1, opr2);
2728 
2729   Label L;
2730   if (unordered_is_less) {
2731     movl(dst, -1);
2732     jcc(Assembler::parity, L);
2733     jcc(Assembler::below , L);
2734     movl(dst, 0);
2735     jcc(Assembler::equal , L);
2736     increment(dst);
2737   } else { // unordered is greater
2738     movl(dst, 1);
2739     jcc(Assembler::parity, L);
2740     jcc(Assembler::above , L);
2741     movl(dst, 0);
2742     jcc(Assembler::equal , L);
2743     decrementl(dst);
2744   }
2745   bind(L);
2746 }
2747 
2748 
2749 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2750   if (reachable(src1)) {
2751     cmpb(as_Address(src1), imm);
2752   } else {
2753     lea(rscratch1, src1);
2754     cmpb(Address(rscratch1, 0), imm);
2755   }
2756 }
2757 
2758 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2759 #ifdef _LP64
2760   if (src2.is_lval()) {
2761     movptr(rscratch1, src2);
2762     Assembler::cmpq(src1, rscratch1);
2763   } else if (reachable(src2)) {
2764     cmpq(src1, as_Address(src2));
2765   } else {
2766     lea(rscratch1, src2);
2767     Assembler::cmpq(src1, Address(rscratch1, 0));
2768   }
2769 #else
2770   if (src2.is_lval()) {
2771     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2772   } else {
2773     cmpl(src1, as_Address(src2));
2774   }
2775 #endif // _LP64
2776 }
2777 
2778 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2779   assert(src2.is_lval(), "not a mem-mem compare");
2780 #ifdef _LP64
2781   // moves src2's literal address
2782   movptr(rscratch1, src2);
2783   Assembler::cmpq(src1, rscratch1);
2784 #else
2785   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2786 #endif // _LP64
2787 }
2788 
2789 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2790   if (reachable(adr)) {
2791     if (os::is_MP())
2792       lock();
2793     cmpxchgptr(reg, as_Address(adr));
2794   } else {
2795     lea(rscratch1, adr);
2796     if (os::is_MP())
2797       lock();
2798     cmpxchgptr(reg, Address(rscratch1, 0));
2799   }
2800 }
2801 
2802 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2803   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2804 }
2805 
2806 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2807   if (reachable(src)) {
2808     Assembler::comisd(dst, as_Address(src));
2809   } else {
2810     lea(rscratch1, src);
2811     Assembler::comisd(dst, Address(rscratch1, 0));
2812   }
2813 }
2814 
2815 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2816   if (reachable(src)) {
2817     Assembler::comiss(dst, as_Address(src));
2818   } else {
2819     lea(rscratch1, src);
2820     Assembler::comiss(dst, Address(rscratch1, 0));
2821   }
2822 }
2823 
2824 
2825 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2826   Condition negated_cond = negate_condition(cond);
2827   Label L;
2828   jcc(negated_cond, L);
2829   pushf(); // Preserve flags
2830   atomic_incl(counter_addr);
2831   popf();
2832   bind(L);
2833 }
2834 
2835 int MacroAssembler::corrected_idivl(Register reg) {
2836   // Full implementation of Java idiv and irem; checks for
2837   // special case as described in JVM spec., p.243 & p.271.
2838   // The function returns the (pc) offset of the idivl
2839   // instruction - may be needed for implicit exceptions.
2840   //
2841   //         normal case                           special case
2842   //
2843   // input : rax,: dividend                         min_int
2844   //         reg: divisor   (may not be rax,/rdx)   -1
2845   //
2846   // output: rax,: quotient  (= rax, idiv reg)       min_int
2847   //         rdx: remainder (= rax, irem reg)       0
2848   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2849   const int min_int = 0x80000000;
2850   Label normal_case, special_case;
2851 
2852   // check for special case
2853   cmpl(rax, min_int);
2854   jcc(Assembler::notEqual, normal_case);
2855   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2856   cmpl(reg, -1);
2857   jcc(Assembler::equal, special_case);
2858 
2859   // handle normal case
2860   bind(normal_case);
2861   cdql();
2862   int idivl_offset = offset();
2863   idivl(reg);
2864 
2865   // normal and special case exit
2866   bind(special_case);
2867 
2868   return idivl_offset;
2869 }
2870 
2871 
2872 
2873 void MacroAssembler::decrementl(Register reg, int value) {
2874   if (value == min_jint) {subl(reg, value) ; return; }
2875   if (value <  0) { incrementl(reg, -value); return; }
2876   if (value == 0) {                        ; return; }
2877   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2878   /* else */      { subl(reg, value)       ; return; }
2879 }
2880 
2881 void MacroAssembler::decrementl(Address dst, int value) {
2882   if (value == min_jint) {subl(dst, value) ; return; }
2883   if (value <  0) { incrementl(dst, -value); return; }
2884   if (value == 0) {                        ; return; }
2885   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2886   /* else */      { subl(dst, value)       ; return; }
2887 }
2888 
2889 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2890   assert (shift_value > 0, "illegal shift value");
2891   Label _is_positive;
2892   testl (reg, reg);
2893   jcc (Assembler::positive, _is_positive);
2894   int offset = (1 << shift_value) - 1 ;
2895 
2896   if (offset == 1) {
2897     incrementl(reg);
2898   } else {
2899     addl(reg, offset);
2900   }
2901 
2902   bind (_is_positive);
2903   sarl(reg, shift_value);
2904 }
2905 
2906 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2907   if (reachable(src)) {
2908     Assembler::divsd(dst, as_Address(src));
2909   } else {
2910     lea(rscratch1, src);
2911     Assembler::divsd(dst, Address(rscratch1, 0));
2912   }
2913 }
2914 
2915 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2916   if (reachable(src)) {
2917     Assembler::divss(dst, as_Address(src));
2918   } else {
2919     lea(rscratch1, src);
2920     Assembler::divss(dst, Address(rscratch1, 0));
2921   }
2922 }
2923 
2924 // !defined(COMPILER2) is because of stupid core builds
2925 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2926 void MacroAssembler::empty_FPU_stack() {
2927   if (VM_Version::supports_mmx()) {
2928     emms();
2929   } else {
2930     for (int i = 8; i-- > 0; ) ffree(i);
2931   }
2932 }
2933 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2934 
2935 
2936 // Defines obj, preserves var_size_in_bytes
2937 void MacroAssembler::eden_allocate(Register obj,
2938                                    Register var_size_in_bytes,
2939                                    int con_size_in_bytes,
2940                                    Register t1,
2941                                    Label& slow_case) {
2942   assert(obj == rax, "obj must be in rax, for cmpxchg");
2943   assert_different_registers(obj, var_size_in_bytes, t1);
2944   if (!Universe::heap()->supports_inline_contig_alloc()) {
2945     jmp(slow_case);
2946   } else {
2947     Register end = t1;
2948     Label retry;
2949     bind(retry);
2950     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2951     movptr(obj, heap_top);
2952     if (var_size_in_bytes == noreg) {
2953       lea(end, Address(obj, con_size_in_bytes));
2954     } else {
2955       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2956     }
2957     // if end < obj then we wrapped around => object too long => slow case
2958     cmpptr(end, obj);
2959     jcc(Assembler::below, slow_case);
2960     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2961     jcc(Assembler::above, slow_case);
2962     // Compare obj with the top addr, and if still equal, store the new top addr in
2963     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2964     // it otherwise. Use lock prefix for atomicity on MPs.
2965     locked_cmpxchgptr(end, heap_top);
2966     jcc(Assembler::notEqual, retry);
2967   }
2968 }
2969 
2970 void MacroAssembler::enter() {
2971   push(rbp);
2972   mov(rbp, rsp);
2973 }
2974 
2975 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2976 void MacroAssembler::fat_nop() {
2977   if (UseAddressNop) {
2978     addr_nop_5();
2979   } else {
2980     emit_int8(0x26); // es:
2981     emit_int8(0x2e); // cs:
2982     emit_int8(0x64); // fs:
2983     emit_int8(0x65); // gs:
2984     emit_int8((unsigned char)0x90);
2985   }
2986 }
2987 
2988 void MacroAssembler::fcmp(Register tmp) {
2989   fcmp(tmp, 1, true, true);
2990 }
2991 
2992 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2993   assert(!pop_right || pop_left, "usage error");
2994   if (VM_Version::supports_cmov()) {
2995     assert(tmp == noreg, "unneeded temp");
2996     if (pop_left) {
2997       fucomip(index);
2998     } else {
2999       fucomi(index);
3000     }
3001     if (pop_right) {
3002       fpop();
3003     }
3004   } else {
3005     assert(tmp != noreg, "need temp");
3006     if (pop_left) {
3007       if (pop_right) {
3008         fcompp();
3009       } else {
3010         fcomp(index);
3011       }
3012     } else {
3013       fcom(index);
3014     }
3015     // convert FPU condition into eflags condition via rax,
3016     save_rax(tmp);
3017     fwait(); fnstsw_ax();
3018     sahf();
3019     restore_rax(tmp);
3020   }
3021   // condition codes set as follows:
3022   //
3023   // CF (corresponds to C0) if x < y
3024   // PF (corresponds to C2) if unordered
3025   // ZF (corresponds to C3) if x = y
3026 }
3027 
3028 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3029   fcmp2int(dst, unordered_is_less, 1, true, true);
3030 }
3031 
3032 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3033   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3034   Label L;
3035   if (unordered_is_less) {
3036     movl(dst, -1);
3037     jcc(Assembler::parity, L);
3038     jcc(Assembler::below , L);
3039     movl(dst, 0);
3040     jcc(Assembler::equal , L);
3041     increment(dst);
3042   } else { // unordered is greater
3043     movl(dst, 1);
3044     jcc(Assembler::parity, L);
3045     jcc(Assembler::above , L);
3046     movl(dst, 0);
3047     jcc(Assembler::equal , L);
3048     decrementl(dst);
3049   }
3050   bind(L);
3051 }
3052 
3053 void MacroAssembler::fld_d(AddressLiteral src) {
3054   fld_d(as_Address(src));
3055 }
3056 
3057 void MacroAssembler::fld_s(AddressLiteral src) {
3058   fld_s(as_Address(src));
3059 }
3060 
3061 void MacroAssembler::fld_x(AddressLiteral src) {
3062   Assembler::fld_x(as_Address(src));
3063 }
3064 
3065 void MacroAssembler::fldcw(AddressLiteral src) {
3066   Assembler::fldcw(as_Address(src));
3067 }
3068 
3069 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3070   if (reachable(src)) {
3071     Assembler::mulpd(dst, as_Address(src));
3072   } else {
3073     lea(rscratch1, src);
3074     Assembler::mulpd(dst, Address(rscratch1, 0));
3075   }
3076 }
3077 
3078 void MacroAssembler::increase_precision() {
3079   subptr(rsp, BytesPerWord);
3080   fnstcw(Address(rsp, 0));
3081   movl(rax, Address(rsp, 0));
3082   orl(rax, 0x300);
3083   push(rax);
3084   fldcw(Address(rsp, 0));
3085   pop(rax);
3086 }
3087 
3088 void MacroAssembler::restore_precision() {
3089   fldcw(Address(rsp, 0));
3090   addptr(rsp, BytesPerWord);
3091 }
3092 
3093 void MacroAssembler::fpop() {
3094   ffree();
3095   fincstp();
3096 }
3097 
3098 void MacroAssembler::load_float(Address src) {
3099   if (UseSSE >= 1) {
3100     movflt(xmm0, src);
3101   } else {
3102     LP64_ONLY(ShouldNotReachHere());
3103     NOT_LP64(fld_s(src));
3104   }
3105 }
3106 
3107 void MacroAssembler::store_float(Address dst) {
3108   if (UseSSE >= 1) {
3109     movflt(dst, xmm0);
3110   } else {
3111     LP64_ONLY(ShouldNotReachHere());
3112     NOT_LP64(fstp_s(dst));
3113   }
3114 }
3115 
3116 void MacroAssembler::load_double(Address src) {
3117   if (UseSSE >= 2) {
3118     movdbl(xmm0, src);
3119   } else {
3120     LP64_ONLY(ShouldNotReachHere());
3121     NOT_LP64(fld_d(src));
3122   }
3123 }
3124 
3125 void MacroAssembler::store_double(Address dst) {
3126   if (UseSSE >= 2) {
3127     movdbl(dst, xmm0);
3128   } else {
3129     LP64_ONLY(ShouldNotReachHere());
3130     NOT_LP64(fstp_d(dst));
3131   }
3132 }
3133 
3134 void MacroAssembler::fremr(Register tmp) {
3135   save_rax(tmp);
3136   { Label L;
3137     bind(L);
3138     fprem();
3139     fwait(); fnstsw_ax();
3140 #ifdef _LP64
3141     testl(rax, 0x400);
3142     jcc(Assembler::notEqual, L);
3143 #else
3144     sahf();
3145     jcc(Assembler::parity, L);
3146 #endif // _LP64
3147   }
3148   restore_rax(tmp);
3149   // Result is in ST0.
3150   // Note: fxch & fpop to get rid of ST1
3151   // (otherwise FPU stack could overflow eventually)
3152   fxch(1);
3153   fpop();
3154 }
3155 
3156 // dst = c = a * b + c
3157 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3158   Assembler::vfmadd231sd(c, a, b);
3159   if (dst != c) {
3160     movdbl(dst, c);
3161   }
3162 }
3163 
3164 // dst = c = a * b + c
3165 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3166   Assembler::vfmadd231ss(c, a, b);
3167   if (dst != c) {
3168     movflt(dst, c);
3169   }
3170 }
3171 
3172 
3173 
3174 
3175 void MacroAssembler::incrementl(AddressLiteral dst) {
3176   if (reachable(dst)) {
3177     incrementl(as_Address(dst));
3178   } else {
3179     lea(rscratch1, dst);
3180     incrementl(Address(rscratch1, 0));
3181   }
3182 }
3183 
3184 void MacroAssembler::incrementl(ArrayAddress dst) {
3185   incrementl(as_Address(dst));
3186 }
3187 
3188 void MacroAssembler::incrementl(Register reg, int value) {
3189   if (value == min_jint) {addl(reg, value) ; return; }
3190   if (value <  0) { decrementl(reg, -value); return; }
3191   if (value == 0) {                        ; return; }
3192   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3193   /* else */      { addl(reg, value)       ; return; }
3194 }
3195 
3196 void MacroAssembler::incrementl(Address dst, int value) {
3197   if (value == min_jint) {addl(dst, value) ; return; }
3198   if (value <  0) { decrementl(dst, -value); return; }
3199   if (value == 0) {                        ; return; }
3200   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3201   /* else */      { addl(dst, value)       ; return; }
3202 }
3203 
3204 void MacroAssembler::jump(AddressLiteral dst) {
3205   if (reachable(dst)) {
3206     jmp_literal(dst.target(), dst.rspec());
3207   } else {
3208     lea(rscratch1, dst);
3209     jmp(rscratch1);
3210   }
3211 }
3212 
3213 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3214   if (reachable(dst)) {
3215     InstructionMark im(this);
3216     relocate(dst.reloc());
3217     const int short_size = 2;
3218     const int long_size = 6;
3219     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3220     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3221       // 0111 tttn #8-bit disp
3222       emit_int8(0x70 | cc);
3223       emit_int8((offs - short_size) & 0xFF);
3224     } else {
3225       // 0000 1111 1000 tttn #32-bit disp
3226       emit_int8(0x0F);
3227       emit_int8((unsigned char)(0x80 | cc));
3228       emit_int32(offs - long_size);
3229     }
3230   } else {
3231 #ifdef ASSERT
3232     warning("reversing conditional branch");
3233 #endif /* ASSERT */
3234     Label skip;
3235     jccb(reverse[cc], skip);
3236     lea(rscratch1, dst);
3237     Assembler::jmp(rscratch1);
3238     bind(skip);
3239   }
3240 }
3241 
3242 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3243   if (reachable(src)) {
3244     Assembler::ldmxcsr(as_Address(src));
3245   } else {
3246     lea(rscratch1, src);
3247     Assembler::ldmxcsr(Address(rscratch1, 0));
3248   }
3249 }
3250 
3251 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3252   int off;
3253   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3254     off = offset();
3255     movsbl(dst, src); // movsxb
3256   } else {
3257     off = load_unsigned_byte(dst, src);
3258     shll(dst, 24);
3259     sarl(dst, 24);
3260   }
3261   return off;
3262 }
3263 
3264 // Note: load_signed_short used to be called load_signed_word.
3265 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3266 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3267 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3268 int MacroAssembler::load_signed_short(Register dst, Address src) {
3269   int off;
3270   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3271     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3272     // version but this is what 64bit has always done. This seems to imply
3273     // that users are only using 32bits worth.
3274     off = offset();
3275     movswl(dst, src); // movsxw
3276   } else {
3277     off = load_unsigned_short(dst, src);
3278     shll(dst, 16);
3279     sarl(dst, 16);
3280   }
3281   return off;
3282 }
3283 
3284 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3285   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3286   // and "3.9 Partial Register Penalties", p. 22).
3287   int off;
3288   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3289     off = offset();
3290     movzbl(dst, src); // movzxb
3291   } else {
3292     xorl(dst, dst);
3293     off = offset();
3294     movb(dst, src);
3295   }
3296   return off;
3297 }
3298 
3299 // Note: load_unsigned_short used to be called load_unsigned_word.
3300 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3301   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3302   // and "3.9 Partial Register Penalties", p. 22).
3303   int off;
3304   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3305     off = offset();
3306     movzwl(dst, src); // movzxw
3307   } else {
3308     xorl(dst, dst);
3309     off = offset();
3310     movw(dst, src);
3311   }
3312   return off;
3313 }
3314 
3315 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3316   switch (size_in_bytes) {
3317 #ifndef _LP64
3318   case  8:
3319     assert(dst2 != noreg, "second dest register required");
3320     movl(dst,  src);
3321     movl(dst2, src.plus_disp(BytesPerInt));
3322     break;
3323 #else
3324   case  8:  movq(dst, src); break;
3325 #endif
3326   case  4:  movl(dst, src); break;
3327   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3328   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3329   default:  ShouldNotReachHere();
3330   }
3331 }
3332 
3333 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3334   switch (size_in_bytes) {
3335 #ifndef _LP64
3336   case  8:
3337     assert(src2 != noreg, "second source register required");
3338     movl(dst,                        src);
3339     movl(dst.plus_disp(BytesPerInt), src2);
3340     break;
3341 #else
3342   case  8:  movq(dst, src); break;
3343 #endif
3344   case  4:  movl(dst, src); break;
3345   case  2:  movw(dst, src); break;
3346   case  1:  movb(dst, src); break;
3347   default:  ShouldNotReachHere();
3348   }
3349 }
3350 
3351 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3352   if (reachable(dst)) {
3353     movl(as_Address(dst), src);
3354   } else {
3355     lea(rscratch1, dst);
3356     movl(Address(rscratch1, 0), src);
3357   }
3358 }
3359 
3360 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3361   if (reachable(src)) {
3362     movl(dst, as_Address(src));
3363   } else {
3364     lea(rscratch1, src);
3365     movl(dst, Address(rscratch1, 0));
3366   }
3367 }
3368 
3369 // C++ bool manipulation
3370 
3371 void MacroAssembler::movbool(Register dst, Address src) {
3372   if(sizeof(bool) == 1)
3373     movb(dst, src);
3374   else if(sizeof(bool) == 2)
3375     movw(dst, src);
3376   else if(sizeof(bool) == 4)
3377     movl(dst, src);
3378   else
3379     // unsupported
3380     ShouldNotReachHere();
3381 }
3382 
3383 void MacroAssembler::movbool(Address dst, bool boolconst) {
3384   if(sizeof(bool) == 1)
3385     movb(dst, (int) boolconst);
3386   else if(sizeof(bool) == 2)
3387     movw(dst, (int) boolconst);
3388   else if(sizeof(bool) == 4)
3389     movl(dst, (int) boolconst);
3390   else
3391     // unsupported
3392     ShouldNotReachHere();
3393 }
3394 
3395 void MacroAssembler::movbool(Address dst, Register src) {
3396   if(sizeof(bool) == 1)
3397     movb(dst, src);
3398   else if(sizeof(bool) == 2)
3399     movw(dst, src);
3400   else if(sizeof(bool) == 4)
3401     movl(dst, src);
3402   else
3403     // unsupported
3404     ShouldNotReachHere();
3405 }
3406 
3407 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3408   movb(as_Address(dst), src);
3409 }
3410 
3411 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3412   if (reachable(src)) {
3413     movdl(dst, as_Address(src));
3414   } else {
3415     lea(rscratch1, src);
3416     movdl(dst, Address(rscratch1, 0));
3417   }
3418 }
3419 
3420 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3421   if (reachable(src)) {
3422     movq(dst, as_Address(src));
3423   } else {
3424     lea(rscratch1, src);
3425     movq(dst, Address(rscratch1, 0));
3426   }
3427 }
3428 
3429 void MacroAssembler::setvectmask(Register dst, Register src) {
3430   Assembler::movl(dst, 1);
3431   Assembler::shlxl(dst, dst, src);
3432   Assembler::decl(dst);
3433   Assembler::kmovdl(k1, dst);
3434   Assembler::movl(dst, src);
3435 }
3436 
3437 void MacroAssembler::restorevectmask() {
3438   Assembler::knotwl(k1, k0);
3439 }
3440 
3441 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3442   if (reachable(src)) {
3443     if (UseXmmLoadAndClearUpper) {
3444       movsd (dst, as_Address(src));
3445     } else {
3446       movlpd(dst, as_Address(src));
3447     }
3448   } else {
3449     lea(rscratch1, src);
3450     if (UseXmmLoadAndClearUpper) {
3451       movsd (dst, Address(rscratch1, 0));
3452     } else {
3453       movlpd(dst, Address(rscratch1, 0));
3454     }
3455   }
3456 }
3457 
3458 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3459   if (reachable(src)) {
3460     movss(dst, as_Address(src));
3461   } else {
3462     lea(rscratch1, src);
3463     movss(dst, Address(rscratch1, 0));
3464   }
3465 }
3466 
3467 void MacroAssembler::movptr(Register dst, Register src) {
3468   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3469 }
3470 
3471 void MacroAssembler::movptr(Register dst, Address src) {
3472   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3473 }
3474 
3475 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3476 void MacroAssembler::movptr(Register dst, intptr_t src) {
3477   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3478 }
3479 
3480 void MacroAssembler::movptr(Address dst, Register src) {
3481   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3482 }
3483 
3484 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3485   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3486     Assembler::vextractf32x4(dst, src, 0);
3487   } else {
3488     Assembler::movdqu(dst, src);
3489   }
3490 }
3491 
3492 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3493   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3494     Assembler::vinsertf32x4(dst, dst, src, 0);
3495   } else {
3496     Assembler::movdqu(dst, src);
3497   }
3498 }
3499 
3500 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3501   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3502     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3503   } else {
3504     Assembler::movdqu(dst, src);
3505   }
3506 }
3507 
3508 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3509   if (reachable(src)) {
3510     movdqu(dst, as_Address(src));
3511   } else {
3512     lea(scratchReg, src);
3513     movdqu(dst, Address(scratchReg, 0));
3514   }
3515 }
3516 
3517 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3518   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3519     vextractf64x4_low(dst, src);
3520   } else {
3521     Assembler::vmovdqu(dst, src);
3522   }
3523 }
3524 
3525 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3526   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3527     vinsertf64x4_low(dst, src);
3528   } else {
3529     Assembler::vmovdqu(dst, src);
3530   }
3531 }
3532 
3533 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3534   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3535     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3536   }
3537   else {
3538     Assembler::vmovdqu(dst, src);
3539   }
3540 }
3541 
3542 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3543   if (reachable(src)) {
3544     vmovdqu(dst, as_Address(src));
3545   }
3546   else {
3547     lea(rscratch1, src);
3548     vmovdqu(dst, Address(rscratch1, 0));
3549   }
3550 }
3551 
3552 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3553   if (reachable(src)) {
3554     Assembler::movdqa(dst, as_Address(src));
3555   } else {
3556     lea(rscratch1, src);
3557     Assembler::movdqa(dst, Address(rscratch1, 0));
3558   }
3559 }
3560 
3561 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3562   if (reachable(src)) {
3563     Assembler::movsd(dst, as_Address(src));
3564   } else {
3565     lea(rscratch1, src);
3566     Assembler::movsd(dst, Address(rscratch1, 0));
3567   }
3568 }
3569 
3570 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3571   if (reachable(src)) {
3572     Assembler::movss(dst, as_Address(src));
3573   } else {
3574     lea(rscratch1, src);
3575     Assembler::movss(dst, Address(rscratch1, 0));
3576   }
3577 }
3578 
3579 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3580   if (reachable(src)) {
3581     Assembler::mulsd(dst, as_Address(src));
3582   } else {
3583     lea(rscratch1, src);
3584     Assembler::mulsd(dst, Address(rscratch1, 0));
3585   }
3586 }
3587 
3588 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3589   if (reachable(src)) {
3590     Assembler::mulss(dst, as_Address(src));
3591   } else {
3592     lea(rscratch1, src);
3593     Assembler::mulss(dst, Address(rscratch1, 0));
3594   }
3595 }
3596 
3597 void MacroAssembler::null_check(Register reg, int offset) {
3598   if (needs_explicit_null_check(offset)) {
3599     // provoke OS NULL exception if reg = NULL by
3600     // accessing M[reg] w/o changing any (non-CC) registers
3601     // NOTE: cmpl is plenty here to provoke a segv
3602     cmpptr(rax, Address(reg, 0));
3603     // Note: should probably use testl(rax, Address(reg, 0));
3604     //       may be shorter code (however, this version of
3605     //       testl needs to be implemented first)
3606   } else {
3607     // nothing to do, (later) access of M[reg + offset]
3608     // will provoke OS NULL exception if reg = NULL
3609   }
3610 }
3611 
3612 void MacroAssembler::os_breakpoint() {
3613   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3614   // (e.g., MSVC can't call ps() otherwise)
3615   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3616 }
3617 
3618 #ifdef _LP64
3619 #define XSTATE_BV 0x200
3620 #endif
3621 
3622 void MacroAssembler::pop_CPU_state() {
3623   pop_FPU_state();
3624   pop_IU_state();
3625 }
3626 
3627 void MacroAssembler::pop_FPU_state() {
3628 #ifndef _LP64
3629   frstor(Address(rsp, 0));
3630 #else
3631   fxrstor(Address(rsp, 0));
3632 #endif
3633   addptr(rsp, FPUStateSizeInWords * wordSize);
3634 }
3635 
3636 void MacroAssembler::pop_IU_state() {
3637   popa();
3638   LP64_ONLY(addq(rsp, 8));
3639   popf();
3640 }
3641 
3642 // Save Integer and Float state
3643 // Warning: Stack must be 16 byte aligned (64bit)
3644 void MacroAssembler::push_CPU_state() {
3645   push_IU_state();
3646   push_FPU_state();
3647 }
3648 
3649 void MacroAssembler::push_FPU_state() {
3650   subptr(rsp, FPUStateSizeInWords * wordSize);
3651 #ifndef _LP64
3652   fnsave(Address(rsp, 0));
3653   fwait();
3654 #else
3655   fxsave(Address(rsp, 0));
3656 #endif // LP64
3657 }
3658 
3659 void MacroAssembler::push_IU_state() {
3660   // Push flags first because pusha kills them
3661   pushf();
3662   // Make sure rsp stays 16-byte aligned
3663   LP64_ONLY(subq(rsp, 8));
3664   pusha();
3665 }
3666 
3667 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3668   if (!java_thread->is_valid()) {
3669     java_thread = rdi;
3670     get_thread(java_thread);
3671   }
3672   // we must set sp to zero to clear frame
3673   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3674   if (clear_fp) {
3675     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3676   }
3677 
3678   // Always clear the pc because it could have been set by make_walkable()
3679   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3680 
3681   vzeroupper();
3682 }
3683 
3684 void MacroAssembler::restore_rax(Register tmp) {
3685   if (tmp == noreg) pop(rax);
3686   else if (tmp != rax) mov(rax, tmp);
3687 }
3688 
3689 void MacroAssembler::round_to(Register reg, int modulus) {
3690   addptr(reg, modulus - 1);
3691   andptr(reg, -modulus);
3692 }
3693 
3694 void MacroAssembler::save_rax(Register tmp) {
3695   if (tmp == noreg) push(rax);
3696   else if (tmp != rax) mov(tmp, rax);
3697 }
3698 
3699 // Write serialization page so VM thread can do a pseudo remote membar.
3700 // We use the current thread pointer to calculate a thread specific
3701 // offset to write to within the page. This minimizes bus traffic
3702 // due to cache line collision.
3703 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3704   movl(tmp, thread);
3705   shrl(tmp, os::get_serialize_page_shift_count());
3706   andl(tmp, (os::vm_page_size() - sizeof(int)));
3707 
3708   Address index(noreg, tmp, Address::times_1);
3709   ExternalAddress page(os::get_memory_serialize_page());
3710 
3711   // Size of store must match masking code above
3712   movl(as_Address(ArrayAddress(page, index)), tmp);
3713 }
3714 
3715 // Calls to C land
3716 //
3717 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3718 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3719 // has to be reset to 0. This is required to allow proper stack traversal.
3720 void MacroAssembler::set_last_Java_frame(Register java_thread,
3721                                          Register last_java_sp,
3722                                          Register last_java_fp,
3723                                          address  last_java_pc) {
3724   vzeroupper();
3725   // determine java_thread register
3726   if (!java_thread->is_valid()) {
3727     java_thread = rdi;
3728     get_thread(java_thread);
3729   }
3730   // determine last_java_sp register
3731   if (!last_java_sp->is_valid()) {
3732     last_java_sp = rsp;
3733   }
3734 
3735   // last_java_fp is optional
3736 
3737   if (last_java_fp->is_valid()) {
3738     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3739   }
3740 
3741   // last_java_pc is optional
3742 
3743   if (last_java_pc != NULL) {
3744     lea(Address(java_thread,
3745                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3746         InternalAddress(last_java_pc));
3747 
3748   }
3749   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3750 }
3751 
3752 void MacroAssembler::shlptr(Register dst, int imm8) {
3753   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3754 }
3755 
3756 void MacroAssembler::shrptr(Register dst, int imm8) {
3757   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3758 }
3759 
3760 void MacroAssembler::sign_extend_byte(Register reg) {
3761   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3762     movsbl(reg, reg); // movsxb
3763   } else {
3764     shll(reg, 24);
3765     sarl(reg, 24);
3766   }
3767 }
3768 
3769 void MacroAssembler::sign_extend_short(Register reg) {
3770   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3771     movswl(reg, reg); // movsxw
3772   } else {
3773     shll(reg, 16);
3774     sarl(reg, 16);
3775   }
3776 }
3777 
3778 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3779   assert(reachable(src), "Address should be reachable");
3780   testl(dst, as_Address(src));
3781 }
3782 
3783 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3784   int dst_enc = dst->encoding();
3785   int src_enc = src->encoding();
3786   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3787     Assembler::pcmpeqb(dst, src);
3788   } else if ((dst_enc < 16) && (src_enc < 16)) {
3789     Assembler::pcmpeqb(dst, src);
3790   } else if (src_enc < 16) {
3791     subptr(rsp, 64);
3792     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3793     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3794     Assembler::pcmpeqb(xmm0, src);
3795     movdqu(dst, xmm0);
3796     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3797     addptr(rsp, 64);
3798   } else if (dst_enc < 16) {
3799     subptr(rsp, 64);
3800     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3801     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3802     Assembler::pcmpeqb(dst, xmm0);
3803     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3804     addptr(rsp, 64);
3805   } else {
3806     subptr(rsp, 64);
3807     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3808     subptr(rsp, 64);
3809     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3810     movdqu(xmm0, src);
3811     movdqu(xmm1, dst);
3812     Assembler::pcmpeqb(xmm1, xmm0);
3813     movdqu(dst, xmm1);
3814     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3815     addptr(rsp, 64);
3816     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3817     addptr(rsp, 64);
3818   }
3819 }
3820 
3821 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3822   int dst_enc = dst->encoding();
3823   int src_enc = src->encoding();
3824   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3825     Assembler::pcmpeqw(dst, src);
3826   } else if ((dst_enc < 16) && (src_enc < 16)) {
3827     Assembler::pcmpeqw(dst, src);
3828   } else if (src_enc < 16) {
3829     subptr(rsp, 64);
3830     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3831     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3832     Assembler::pcmpeqw(xmm0, src);
3833     movdqu(dst, xmm0);
3834     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3835     addptr(rsp, 64);
3836   } else if (dst_enc < 16) {
3837     subptr(rsp, 64);
3838     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3839     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3840     Assembler::pcmpeqw(dst, xmm0);
3841     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3842     addptr(rsp, 64);
3843   } else {
3844     subptr(rsp, 64);
3845     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3846     subptr(rsp, 64);
3847     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3848     movdqu(xmm0, src);
3849     movdqu(xmm1, dst);
3850     Assembler::pcmpeqw(xmm1, xmm0);
3851     movdqu(dst, xmm1);
3852     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3853     addptr(rsp, 64);
3854     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3855     addptr(rsp, 64);
3856   }
3857 }
3858 
3859 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3860   int dst_enc = dst->encoding();
3861   if (dst_enc < 16) {
3862     Assembler::pcmpestri(dst, src, imm8);
3863   } else {
3864     subptr(rsp, 64);
3865     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3866     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3867     Assembler::pcmpestri(xmm0, src, imm8);
3868     movdqu(dst, xmm0);
3869     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3870     addptr(rsp, 64);
3871   }
3872 }
3873 
3874 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3875   int dst_enc = dst->encoding();
3876   int src_enc = src->encoding();
3877   if ((dst_enc < 16) && (src_enc < 16)) {
3878     Assembler::pcmpestri(dst, src, imm8);
3879   } else if (src_enc < 16) {
3880     subptr(rsp, 64);
3881     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3882     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3883     Assembler::pcmpestri(xmm0, src, imm8);
3884     movdqu(dst, xmm0);
3885     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3886     addptr(rsp, 64);
3887   } else if (dst_enc < 16) {
3888     subptr(rsp, 64);
3889     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3890     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3891     Assembler::pcmpestri(dst, xmm0, imm8);
3892     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3893     addptr(rsp, 64);
3894   } else {
3895     subptr(rsp, 64);
3896     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3897     subptr(rsp, 64);
3898     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3899     movdqu(xmm0, src);
3900     movdqu(xmm1, dst);
3901     Assembler::pcmpestri(xmm1, xmm0, imm8);
3902     movdqu(dst, xmm1);
3903     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3904     addptr(rsp, 64);
3905     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3906     addptr(rsp, 64);
3907   }
3908 }
3909 
3910 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3911   int dst_enc = dst->encoding();
3912   int src_enc = src->encoding();
3913   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3914     Assembler::pmovzxbw(dst, src);
3915   } else if ((dst_enc < 16) && (src_enc < 16)) {
3916     Assembler::pmovzxbw(dst, src);
3917   } else if (src_enc < 16) {
3918     subptr(rsp, 64);
3919     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3920     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3921     Assembler::pmovzxbw(xmm0, src);
3922     movdqu(dst, xmm0);
3923     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3924     addptr(rsp, 64);
3925   } else if (dst_enc < 16) {
3926     subptr(rsp, 64);
3927     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3928     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3929     Assembler::pmovzxbw(dst, xmm0);
3930     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3931     addptr(rsp, 64);
3932   } else {
3933     subptr(rsp, 64);
3934     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3935     subptr(rsp, 64);
3936     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3937     movdqu(xmm0, src);
3938     movdqu(xmm1, dst);
3939     Assembler::pmovzxbw(xmm1, xmm0);
3940     movdqu(dst, xmm1);
3941     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3942     addptr(rsp, 64);
3943     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3944     addptr(rsp, 64);
3945   }
3946 }
3947 
3948 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
3949   int dst_enc = dst->encoding();
3950   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3951     Assembler::pmovzxbw(dst, src);
3952   } else if (dst_enc < 16) {
3953     Assembler::pmovzxbw(dst, src);
3954   } else {
3955     subptr(rsp, 64);
3956     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3957     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3958     Assembler::pmovzxbw(xmm0, src);
3959     movdqu(dst, xmm0);
3960     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3961     addptr(rsp, 64);
3962   }
3963 }
3964 
3965 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
3966   int src_enc = src->encoding();
3967   if (src_enc < 16) {
3968     Assembler::pmovmskb(dst, src);
3969   } else {
3970     subptr(rsp, 64);
3971     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3972     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3973     Assembler::pmovmskb(dst, xmm0);
3974     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3975     addptr(rsp, 64);
3976   }
3977 }
3978 
3979 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
3980   int dst_enc = dst->encoding();
3981   int src_enc = src->encoding();
3982   if ((dst_enc < 16) && (src_enc < 16)) {
3983     Assembler::ptest(dst, src);
3984   } else if (src_enc < 16) {
3985     subptr(rsp, 64);
3986     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3987     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3988     Assembler::ptest(xmm0, src);
3989     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3990     addptr(rsp, 64);
3991   } else if (dst_enc < 16) {
3992     subptr(rsp, 64);
3993     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3994     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3995     Assembler::ptest(dst, xmm0);
3996     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3997     addptr(rsp, 64);
3998   } else {
3999     subptr(rsp, 64);
4000     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4001     subptr(rsp, 64);
4002     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4003     movdqu(xmm0, src);
4004     movdqu(xmm1, dst);
4005     Assembler::ptest(xmm1, xmm0);
4006     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4007     addptr(rsp, 64);
4008     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4009     addptr(rsp, 64);
4010   }
4011 }
4012 
4013 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4014   if (reachable(src)) {
4015     Assembler::sqrtsd(dst, as_Address(src));
4016   } else {
4017     lea(rscratch1, src);
4018     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4019   }
4020 }
4021 
4022 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4023   if (reachable(src)) {
4024     Assembler::sqrtss(dst, as_Address(src));
4025   } else {
4026     lea(rscratch1, src);
4027     Assembler::sqrtss(dst, Address(rscratch1, 0));
4028   }
4029 }
4030 
4031 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4032   if (reachable(src)) {
4033     Assembler::subsd(dst, as_Address(src));
4034   } else {
4035     lea(rscratch1, src);
4036     Assembler::subsd(dst, Address(rscratch1, 0));
4037   }
4038 }
4039 
4040 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4041   if (reachable(src)) {
4042     Assembler::subss(dst, as_Address(src));
4043   } else {
4044     lea(rscratch1, src);
4045     Assembler::subss(dst, Address(rscratch1, 0));
4046   }
4047 }
4048 
4049 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4050   if (reachable(src)) {
4051     Assembler::ucomisd(dst, as_Address(src));
4052   } else {
4053     lea(rscratch1, src);
4054     Assembler::ucomisd(dst, Address(rscratch1, 0));
4055   }
4056 }
4057 
4058 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4059   if (reachable(src)) {
4060     Assembler::ucomiss(dst, as_Address(src));
4061   } else {
4062     lea(rscratch1, src);
4063     Assembler::ucomiss(dst, Address(rscratch1, 0));
4064   }
4065 }
4066 
4067 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4068   // Used in sign-bit flipping with aligned address.
4069   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4070   if (reachable(src)) {
4071     Assembler::xorpd(dst, as_Address(src));
4072   } else {
4073     lea(rscratch1, src);
4074     Assembler::xorpd(dst, Address(rscratch1, 0));
4075   }
4076 }
4077 
4078 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4079   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4080     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4081   }
4082   else {
4083     Assembler::xorpd(dst, src);
4084   }
4085 }
4086 
4087 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4088   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4089     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4090   } else {
4091     Assembler::xorps(dst, src);
4092   }
4093 }
4094 
4095 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4096   // Used in sign-bit flipping with aligned address.
4097   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4098   if (reachable(src)) {
4099     Assembler::xorps(dst, as_Address(src));
4100   } else {
4101     lea(rscratch1, src);
4102     Assembler::xorps(dst, Address(rscratch1, 0));
4103   }
4104 }
4105 
4106 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4107   // Used in sign-bit flipping with aligned address.
4108   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4109   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4110   if (reachable(src)) {
4111     Assembler::pshufb(dst, as_Address(src));
4112   } else {
4113     lea(rscratch1, src);
4114     Assembler::pshufb(dst, Address(rscratch1, 0));
4115   }
4116 }
4117 
4118 // AVX 3-operands instructions
4119 
4120 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4121   if (reachable(src)) {
4122     vaddsd(dst, nds, as_Address(src));
4123   } else {
4124     lea(rscratch1, src);
4125     vaddsd(dst, nds, Address(rscratch1, 0));
4126   }
4127 }
4128 
4129 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4130   if (reachable(src)) {
4131     vaddss(dst, nds, as_Address(src));
4132   } else {
4133     lea(rscratch1, src);
4134     vaddss(dst, nds, Address(rscratch1, 0));
4135   }
4136 }
4137 
4138 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4139   int dst_enc = dst->encoding();
4140   int nds_enc = nds->encoding();
4141   int src_enc = src->encoding();
4142   if ((dst_enc < 16) && (nds_enc < 16)) {
4143     vandps(dst, nds, negate_field, vector_len);
4144   } else if ((src_enc < 16) && (dst_enc < 16)) {
4145     movss(src, nds);
4146     vandps(dst, src, negate_field, vector_len);
4147   } else if (src_enc < 16) {
4148     movss(src, nds);
4149     vandps(src, src, negate_field, vector_len);
4150     movss(dst, src);
4151   } else if (dst_enc < 16) {
4152     movdqu(src, xmm0);
4153     movss(xmm0, nds);
4154     vandps(dst, xmm0, negate_field, vector_len);
4155     movdqu(xmm0, src);
4156   } else if (nds_enc < 16) {
4157     movdqu(src, xmm0);
4158     vandps(xmm0, nds, negate_field, vector_len);
4159     movss(dst, xmm0);
4160     movdqu(xmm0, src);
4161   } else {
4162     movdqu(src, xmm0);
4163     movss(xmm0, nds);
4164     vandps(xmm0, xmm0, negate_field, vector_len);
4165     movss(dst, xmm0);
4166     movdqu(xmm0, src);
4167   }
4168 }
4169 
4170 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4171   int dst_enc = dst->encoding();
4172   int nds_enc = nds->encoding();
4173   int src_enc = src->encoding();
4174   if ((dst_enc < 16) && (nds_enc < 16)) {
4175     vandpd(dst, nds, negate_field, vector_len);
4176   } else if ((src_enc < 16) && (dst_enc < 16)) {
4177     movsd(src, nds);
4178     vandpd(dst, src, negate_field, vector_len);
4179   } else if (src_enc < 16) {
4180     movsd(src, nds);
4181     vandpd(src, src, negate_field, vector_len);
4182     movsd(dst, src);
4183   } else if (dst_enc < 16) {
4184     movdqu(src, xmm0);
4185     movsd(xmm0, nds);
4186     vandpd(dst, xmm0, negate_field, vector_len);
4187     movdqu(xmm0, src);
4188   } else if (nds_enc < 16) {
4189     movdqu(src, xmm0);
4190     vandpd(xmm0, nds, negate_field, vector_len);
4191     movsd(dst, xmm0);
4192     movdqu(xmm0, src);
4193   } else {
4194     movdqu(src, xmm0);
4195     movsd(xmm0, nds);
4196     vandpd(xmm0, xmm0, negate_field, vector_len);
4197     movsd(dst, xmm0);
4198     movdqu(xmm0, src);
4199   }
4200 }
4201 
4202 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4203   int dst_enc = dst->encoding();
4204   int nds_enc = nds->encoding();
4205   int src_enc = src->encoding();
4206   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4207     Assembler::vpaddb(dst, nds, src, vector_len);
4208   } else if ((dst_enc < 16) && (src_enc < 16)) {
4209     Assembler::vpaddb(dst, dst, src, vector_len);
4210   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4211     // use nds as scratch for src
4212     evmovdqul(nds, src, Assembler::AVX_512bit);
4213     Assembler::vpaddb(dst, dst, nds, vector_len);
4214   } else if ((src_enc < 16) && (nds_enc < 16)) {
4215     // use nds as scratch for dst
4216     evmovdqul(nds, dst, Assembler::AVX_512bit);
4217     Assembler::vpaddb(nds, nds, src, vector_len);
4218     evmovdqul(dst, nds, Assembler::AVX_512bit);
4219   } else if (dst_enc < 16) {
4220     // use nds as scatch for xmm0 to hold src
4221     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4222     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4223     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4224     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4225   } else {
4226     // worse case scenario, all regs are in the upper bank
4227     subptr(rsp, 64);
4228     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4229     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4230     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4231     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4232     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4233     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4234     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4235     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4236     addptr(rsp, 64);
4237   }
4238 }
4239 
4240 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4241   int dst_enc = dst->encoding();
4242   int nds_enc = nds->encoding();
4243   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4244     Assembler::vpaddb(dst, nds, src, vector_len);
4245   } else if (dst_enc < 16) {
4246     Assembler::vpaddb(dst, dst, src, vector_len);
4247   } else if (nds_enc < 16) {
4248     // implies dst_enc in upper bank with src as scratch
4249     evmovdqul(nds, dst, Assembler::AVX_512bit);
4250     Assembler::vpaddb(nds, nds, src, vector_len);
4251     evmovdqul(dst, nds, Assembler::AVX_512bit);
4252   } else {
4253     // worse case scenario, all regs in upper bank
4254     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4255     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4256     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4257     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4258   }
4259 }
4260 
4261 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4262   int dst_enc = dst->encoding();
4263   int nds_enc = nds->encoding();
4264   int src_enc = src->encoding();
4265   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4266     Assembler::vpaddw(dst, nds, src, vector_len);
4267   } else if ((dst_enc < 16) && (src_enc < 16)) {
4268     Assembler::vpaddw(dst, dst, src, vector_len);
4269   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4270     // use nds as scratch for src
4271     evmovdqul(nds, src, Assembler::AVX_512bit);
4272     Assembler::vpaddw(dst, dst, nds, vector_len);
4273   } else if ((src_enc < 16) && (nds_enc < 16)) {
4274     // use nds as scratch for dst
4275     evmovdqul(nds, dst, Assembler::AVX_512bit);
4276     Assembler::vpaddw(nds, nds, src, vector_len);
4277     evmovdqul(dst, nds, Assembler::AVX_512bit);
4278   } else if (dst_enc < 16) {
4279     // use nds as scatch for xmm0 to hold src
4280     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4281     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4282     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4283     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4284   } else {
4285     // worse case scenario, all regs are in the upper bank
4286     subptr(rsp, 64);
4287     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4288     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4289     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4290     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4291     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4292     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4293     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4294     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4295     addptr(rsp, 64);
4296   }
4297 }
4298 
4299 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4300   int dst_enc = dst->encoding();
4301   int nds_enc = nds->encoding();
4302   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4303     Assembler::vpaddw(dst, nds, src, vector_len);
4304   } else if (dst_enc < 16) {
4305     Assembler::vpaddw(dst, dst, src, vector_len);
4306   } else if (nds_enc < 16) {
4307     // implies dst_enc in upper bank with src as scratch
4308     evmovdqul(nds, dst, Assembler::AVX_512bit);
4309     Assembler::vpaddw(nds, nds, src, vector_len);
4310     evmovdqul(dst, nds, Assembler::AVX_512bit);
4311   } else {
4312     // worse case scenario, all regs in upper bank
4313     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4314     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4315     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4316     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4317   }
4318 }
4319 
4320 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4321   if (reachable(src)) {
4322     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4323   } else {
4324     lea(rscratch1, src);
4325     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4326   }
4327 }
4328 
4329 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4330   int dst_enc = dst->encoding();
4331   int src_enc = src->encoding();
4332   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4333     Assembler::vpbroadcastw(dst, src);
4334   } else if ((dst_enc < 16) && (src_enc < 16)) {
4335     Assembler::vpbroadcastw(dst, src);
4336   } else if (src_enc < 16) {
4337     subptr(rsp, 64);
4338     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4339     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4340     Assembler::vpbroadcastw(xmm0, src);
4341     movdqu(dst, xmm0);
4342     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4343     addptr(rsp, 64);
4344   } else if (dst_enc < 16) {
4345     subptr(rsp, 64);
4346     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4347     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4348     Assembler::vpbroadcastw(dst, xmm0);
4349     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4350     addptr(rsp, 64);
4351   } else {
4352     subptr(rsp, 64);
4353     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4354     subptr(rsp, 64);
4355     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4356     movdqu(xmm0, src);
4357     movdqu(xmm1, dst);
4358     Assembler::vpbroadcastw(xmm1, xmm0);
4359     movdqu(dst, xmm1);
4360     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4361     addptr(rsp, 64);
4362     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4363     addptr(rsp, 64);
4364   }
4365 }
4366 
4367 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4368   int dst_enc = dst->encoding();
4369   int nds_enc = nds->encoding();
4370   int src_enc = src->encoding();
4371   assert(dst_enc == nds_enc, "");
4372   if ((dst_enc < 16) && (src_enc < 16)) {
4373     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4374   } else if (src_enc < 16) {
4375     subptr(rsp, 64);
4376     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4377     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4378     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4379     movdqu(dst, xmm0);
4380     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4381     addptr(rsp, 64);
4382   } else if (dst_enc < 16) {
4383     subptr(rsp, 64);
4384     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4385     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4386     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4387     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4388     addptr(rsp, 64);
4389   } else {
4390     subptr(rsp, 64);
4391     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4392     subptr(rsp, 64);
4393     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4394     movdqu(xmm0, src);
4395     movdqu(xmm1, dst);
4396     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4397     movdqu(dst, xmm1);
4398     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4399     addptr(rsp, 64);
4400     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4401     addptr(rsp, 64);
4402   }
4403 }
4404 
4405 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4406   int dst_enc = dst->encoding();
4407   int nds_enc = nds->encoding();
4408   int src_enc = src->encoding();
4409   assert(dst_enc == nds_enc, "");
4410   if ((dst_enc < 16) && (src_enc < 16)) {
4411     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4412   } else if (src_enc < 16) {
4413     subptr(rsp, 64);
4414     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4415     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4416     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4417     movdqu(dst, xmm0);
4418     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4419     addptr(rsp, 64);
4420   } else if (dst_enc < 16) {
4421     subptr(rsp, 64);
4422     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4423     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4424     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4425     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4426     addptr(rsp, 64);
4427   } else {
4428     subptr(rsp, 64);
4429     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4430     subptr(rsp, 64);
4431     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4432     movdqu(xmm0, src);
4433     movdqu(xmm1, dst);
4434     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4435     movdqu(dst, xmm1);
4436     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4437     addptr(rsp, 64);
4438     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4439     addptr(rsp, 64);
4440   }
4441 }
4442 
4443 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4444   int dst_enc = dst->encoding();
4445   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4446     Assembler::vpmovzxbw(dst, src, vector_len);
4447   } else if (dst_enc < 16) {
4448     Assembler::vpmovzxbw(dst, src, vector_len);
4449   } else {
4450     subptr(rsp, 64);
4451     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4452     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4453     Assembler::vpmovzxbw(xmm0, src, vector_len);
4454     movdqu(dst, xmm0);
4455     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4456     addptr(rsp, 64);
4457   }
4458 }
4459 
4460 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4461   int src_enc = src->encoding();
4462   if (src_enc < 16) {
4463     Assembler::vpmovmskb(dst, src);
4464   } else {
4465     subptr(rsp, 64);
4466     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4467     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4468     Assembler::vpmovmskb(dst, xmm0);
4469     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4470     addptr(rsp, 64);
4471   }
4472 }
4473 
4474 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4475   int dst_enc = dst->encoding();
4476   int nds_enc = nds->encoding();
4477   int src_enc = src->encoding();
4478   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4479     Assembler::vpmullw(dst, nds, src, vector_len);
4480   } else if ((dst_enc < 16) && (src_enc < 16)) {
4481     Assembler::vpmullw(dst, dst, src, vector_len);
4482   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4483     // use nds as scratch for src
4484     evmovdqul(nds, src, Assembler::AVX_512bit);
4485     Assembler::vpmullw(dst, dst, nds, vector_len);
4486   } else if ((src_enc < 16) && (nds_enc < 16)) {
4487     // use nds as scratch for dst
4488     evmovdqul(nds, dst, Assembler::AVX_512bit);
4489     Assembler::vpmullw(nds, nds, src, vector_len);
4490     evmovdqul(dst, nds, Assembler::AVX_512bit);
4491   } else if (dst_enc < 16) {
4492     // use nds as scatch for xmm0 to hold src
4493     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4494     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4495     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4496     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4497   } else {
4498     // worse case scenario, all regs are in the upper bank
4499     subptr(rsp, 64);
4500     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4501     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4502     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4503     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4504     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4505     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4506     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4507     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4508     addptr(rsp, 64);
4509   }
4510 }
4511 
4512 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4513   int dst_enc = dst->encoding();
4514   int nds_enc = nds->encoding();
4515   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4516     Assembler::vpmullw(dst, nds, src, vector_len);
4517   } else if (dst_enc < 16) {
4518     Assembler::vpmullw(dst, dst, src, vector_len);
4519   } else if (nds_enc < 16) {
4520     // implies dst_enc in upper bank with src as scratch
4521     evmovdqul(nds, dst, Assembler::AVX_512bit);
4522     Assembler::vpmullw(nds, nds, src, vector_len);
4523     evmovdqul(dst, nds, Assembler::AVX_512bit);
4524   } else {
4525     // worse case scenario, all regs in upper bank
4526     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4527     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4528     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4529     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4530   }
4531 }
4532 
4533 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4534   int dst_enc = dst->encoding();
4535   int nds_enc = nds->encoding();
4536   int src_enc = src->encoding();
4537   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4538     Assembler::vpsubb(dst, nds, src, vector_len);
4539   } else if ((dst_enc < 16) && (src_enc < 16)) {
4540     Assembler::vpsubb(dst, dst, src, vector_len);
4541   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4542     // use nds as scratch for src
4543     evmovdqul(nds, src, Assembler::AVX_512bit);
4544     Assembler::vpsubb(dst, dst, nds, vector_len);
4545   } else if ((src_enc < 16) && (nds_enc < 16)) {
4546     // use nds as scratch for dst
4547     evmovdqul(nds, dst, Assembler::AVX_512bit);
4548     Assembler::vpsubb(nds, nds, src, vector_len);
4549     evmovdqul(dst, nds, Assembler::AVX_512bit);
4550   } else if (dst_enc < 16) {
4551     // use nds as scatch for xmm0 to hold src
4552     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4553     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4554     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4555     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4556   } else {
4557     // worse case scenario, all regs are in the upper bank
4558     subptr(rsp, 64);
4559     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4560     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4561     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4562     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4563     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4564     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4565     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4566     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4567     addptr(rsp, 64);
4568   }
4569 }
4570 
4571 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4572   int dst_enc = dst->encoding();
4573   int nds_enc = nds->encoding();
4574   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4575     Assembler::vpsubb(dst, nds, src, vector_len);
4576   } else if (dst_enc < 16) {
4577     Assembler::vpsubb(dst, dst, src, vector_len);
4578   } else if (nds_enc < 16) {
4579     // implies dst_enc in upper bank with src as scratch
4580     evmovdqul(nds, dst, Assembler::AVX_512bit);
4581     Assembler::vpsubb(nds, nds, src, vector_len);
4582     evmovdqul(dst, nds, Assembler::AVX_512bit);
4583   } else {
4584     // worse case scenario, all regs in upper bank
4585     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4586     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4587     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4588     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4589   }
4590 }
4591 
4592 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4593   int dst_enc = dst->encoding();
4594   int nds_enc = nds->encoding();
4595   int src_enc = src->encoding();
4596   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4597     Assembler::vpsubw(dst, nds, src, vector_len);
4598   } else if ((dst_enc < 16) && (src_enc < 16)) {
4599     Assembler::vpsubw(dst, dst, src, vector_len);
4600   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4601     // use nds as scratch for src
4602     evmovdqul(nds, src, Assembler::AVX_512bit);
4603     Assembler::vpsubw(dst, dst, nds, vector_len);
4604   } else if ((src_enc < 16) && (nds_enc < 16)) {
4605     // use nds as scratch for dst
4606     evmovdqul(nds, dst, Assembler::AVX_512bit);
4607     Assembler::vpsubw(nds, nds, src, vector_len);
4608     evmovdqul(dst, nds, Assembler::AVX_512bit);
4609   } else if (dst_enc < 16) {
4610     // use nds as scatch for xmm0 to hold src
4611     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4612     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4613     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4614     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4615   } else {
4616     // worse case scenario, all regs are in the upper bank
4617     subptr(rsp, 64);
4618     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4619     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4620     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4621     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4622     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4623     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4624     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4625     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4626     addptr(rsp, 64);
4627   }
4628 }
4629 
4630 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4631   int dst_enc = dst->encoding();
4632   int nds_enc = nds->encoding();
4633   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4634     Assembler::vpsubw(dst, nds, src, vector_len);
4635   } else if (dst_enc < 16) {
4636     Assembler::vpsubw(dst, dst, src, vector_len);
4637   } else if (nds_enc < 16) {
4638     // implies dst_enc in upper bank with src as scratch
4639     evmovdqul(nds, dst, Assembler::AVX_512bit);
4640     Assembler::vpsubw(nds, nds, src, vector_len);
4641     evmovdqul(dst, nds, Assembler::AVX_512bit);
4642   } else {
4643     // worse case scenario, all regs in upper bank
4644     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4645     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4646     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4647     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4648   }
4649 }
4650 
4651 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4652   int dst_enc = dst->encoding();
4653   int nds_enc = nds->encoding();
4654   int shift_enc = shift->encoding();
4655   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4656     Assembler::vpsraw(dst, nds, shift, vector_len);
4657   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4658     Assembler::vpsraw(dst, dst, shift, vector_len);
4659   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4660     // use nds_enc as scratch with shift
4661     evmovdqul(nds, shift, Assembler::AVX_512bit);
4662     Assembler::vpsraw(dst, dst, nds, vector_len);
4663   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4664     // use nds as scratch with dst
4665     evmovdqul(nds, dst, Assembler::AVX_512bit);
4666     Assembler::vpsraw(nds, nds, shift, vector_len);
4667     evmovdqul(dst, nds, Assembler::AVX_512bit);
4668   } else if (dst_enc < 16) {
4669     // use nds to save a copy of xmm0 and hold shift
4670     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4671     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4672     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4673     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4674   } else if (nds_enc < 16) {
4675     // use nds as dest as temps
4676     evmovdqul(nds, dst, Assembler::AVX_512bit);
4677     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4678     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4679     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4680     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4681     evmovdqul(dst, nds, Assembler::AVX_512bit);
4682   } else {
4683     // worse case scenario, all regs are in the upper bank
4684     subptr(rsp, 64);
4685     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4686     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4687     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4688     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4689     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4690     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4691     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4692     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4693     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4694     addptr(rsp, 64);
4695   }
4696 }
4697 
4698 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4699   int dst_enc = dst->encoding();
4700   int nds_enc = nds->encoding();
4701   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4702     Assembler::vpsraw(dst, nds, shift, vector_len);
4703   } else if (dst_enc < 16) {
4704     Assembler::vpsraw(dst, dst, shift, vector_len);
4705   } else if (nds_enc < 16) {
4706     // use nds as scratch
4707     evmovdqul(nds, dst, Assembler::AVX_512bit);
4708     Assembler::vpsraw(nds, nds, shift, vector_len);
4709     evmovdqul(dst, nds, Assembler::AVX_512bit);
4710   } else {
4711     // use nds as scratch for xmm0
4712     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4713     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4714     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4715     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4716   }
4717 }
4718 
4719 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4720   int dst_enc = dst->encoding();
4721   int nds_enc = nds->encoding();
4722   int shift_enc = shift->encoding();
4723   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4724     Assembler::vpsrlw(dst, nds, shift, vector_len);
4725   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4726     Assembler::vpsrlw(dst, dst, shift, vector_len);
4727   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4728     // use nds_enc as scratch with shift
4729     evmovdqul(nds, shift, Assembler::AVX_512bit);
4730     Assembler::vpsrlw(dst, dst, nds, vector_len);
4731   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4732     // use nds as scratch with dst
4733     evmovdqul(nds, dst, Assembler::AVX_512bit);
4734     Assembler::vpsrlw(nds, nds, shift, vector_len);
4735     evmovdqul(dst, nds, Assembler::AVX_512bit);
4736   } else if (dst_enc < 16) {
4737     // use nds to save a copy of xmm0 and hold shift
4738     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4739     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4740     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4741     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4742   } else if (nds_enc < 16) {
4743     // use nds as dest as temps
4744     evmovdqul(nds, dst, Assembler::AVX_512bit);
4745     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4746     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4747     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4748     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4749     evmovdqul(dst, nds, Assembler::AVX_512bit);
4750   } else {
4751     // worse case scenario, all regs are in the upper bank
4752     subptr(rsp, 64);
4753     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4754     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4755     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4756     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4757     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4758     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4759     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4760     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4761     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4762     addptr(rsp, 64);
4763   }
4764 }
4765 
4766 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4767   int dst_enc = dst->encoding();
4768   int nds_enc = nds->encoding();
4769   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4770     Assembler::vpsrlw(dst, nds, shift, vector_len);
4771   } else if (dst_enc < 16) {
4772     Assembler::vpsrlw(dst, dst, shift, vector_len);
4773   } else if (nds_enc < 16) {
4774     // use nds as scratch
4775     evmovdqul(nds, dst, Assembler::AVX_512bit);
4776     Assembler::vpsrlw(nds, nds, shift, vector_len);
4777     evmovdqul(dst, nds, Assembler::AVX_512bit);
4778   } else {
4779     // use nds as scratch for xmm0
4780     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4781     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4782     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4783     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4784   }
4785 }
4786 
4787 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4788   int dst_enc = dst->encoding();
4789   int nds_enc = nds->encoding();
4790   int shift_enc = shift->encoding();
4791   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4792     Assembler::vpsllw(dst, nds, shift, vector_len);
4793   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4794     Assembler::vpsllw(dst, dst, shift, vector_len);
4795   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4796     // use nds_enc as scratch with shift
4797     evmovdqul(nds, shift, Assembler::AVX_512bit);
4798     Assembler::vpsllw(dst, dst, nds, vector_len);
4799   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4800     // use nds as scratch with dst
4801     evmovdqul(nds, dst, Assembler::AVX_512bit);
4802     Assembler::vpsllw(nds, nds, shift, vector_len);
4803     evmovdqul(dst, nds, Assembler::AVX_512bit);
4804   } else if (dst_enc < 16) {
4805     // use nds to save a copy of xmm0 and hold shift
4806     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4807     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4808     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4809     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4810   } else if (nds_enc < 16) {
4811     // use nds as dest as temps
4812     evmovdqul(nds, dst, Assembler::AVX_512bit);
4813     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4814     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4815     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4816     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4817     evmovdqul(dst, nds, Assembler::AVX_512bit);
4818   } else {
4819     // worse case scenario, all regs are in the upper bank
4820     subptr(rsp, 64);
4821     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4822     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4823     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4824     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4825     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4826     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4827     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4828     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4829     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4830     addptr(rsp, 64);
4831   }
4832 }
4833 
4834 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4835   int dst_enc = dst->encoding();
4836   int nds_enc = nds->encoding();
4837   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4838     Assembler::vpsllw(dst, nds, shift, vector_len);
4839   } else if (dst_enc < 16) {
4840     Assembler::vpsllw(dst, dst, shift, vector_len);
4841   } else if (nds_enc < 16) {
4842     // use nds as scratch
4843     evmovdqul(nds, dst, Assembler::AVX_512bit);
4844     Assembler::vpsllw(nds, nds, shift, vector_len);
4845     evmovdqul(dst, nds, Assembler::AVX_512bit);
4846   } else {
4847     // use nds as scratch for xmm0
4848     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4849     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4850     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4851     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4852   }
4853 }
4854 
4855 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4856   int dst_enc = dst->encoding();
4857   int src_enc = src->encoding();
4858   if ((dst_enc < 16) && (src_enc < 16)) {
4859     Assembler::vptest(dst, src);
4860   } else if (src_enc < 16) {
4861     subptr(rsp, 64);
4862     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4863     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4864     Assembler::vptest(xmm0, src);
4865     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4866     addptr(rsp, 64);
4867   } else if (dst_enc < 16) {
4868     subptr(rsp, 64);
4869     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4870     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4871     Assembler::vptest(dst, xmm0);
4872     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4873     addptr(rsp, 64);
4874   } else {
4875     subptr(rsp, 64);
4876     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4877     subptr(rsp, 64);
4878     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4879     movdqu(xmm0, src);
4880     movdqu(xmm1, dst);
4881     Assembler::vptest(xmm1, xmm0);
4882     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4883     addptr(rsp, 64);
4884     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4885     addptr(rsp, 64);
4886   }
4887 }
4888 
4889 // This instruction exists within macros, ergo we cannot control its input
4890 // when emitted through those patterns.
4891 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4892   if (VM_Version::supports_avx512nobw()) {
4893     int dst_enc = dst->encoding();
4894     int src_enc = src->encoding();
4895     if (dst_enc == src_enc) {
4896       if (dst_enc < 16) {
4897         Assembler::punpcklbw(dst, src);
4898       } else {
4899         subptr(rsp, 64);
4900         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4901         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4902         Assembler::punpcklbw(xmm0, xmm0);
4903         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4904         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4905         addptr(rsp, 64);
4906       }
4907     } else {
4908       if ((src_enc < 16) && (dst_enc < 16)) {
4909         Assembler::punpcklbw(dst, src);
4910       } else if (src_enc < 16) {
4911         subptr(rsp, 64);
4912         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4913         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4914         Assembler::punpcklbw(xmm0, src);
4915         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4916         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4917         addptr(rsp, 64);
4918       } else if (dst_enc < 16) {
4919         subptr(rsp, 64);
4920         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4921         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4922         Assembler::punpcklbw(dst, xmm0);
4923         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4924         addptr(rsp, 64);
4925       } else {
4926         subptr(rsp, 64);
4927         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4928         subptr(rsp, 64);
4929         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4930         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4931         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4932         Assembler::punpcklbw(xmm0, xmm1);
4933         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4934         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4935         addptr(rsp, 64);
4936         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4937         addptr(rsp, 64);
4938       }
4939     }
4940   } else {
4941     Assembler::punpcklbw(dst, src);
4942   }
4943 }
4944 
4945 // This instruction exists within macros, ergo we cannot control its input
4946 // when emitted through those patterns.
4947 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4948   if (VM_Version::supports_avx512nobw()) {
4949     int dst_enc = dst->encoding();
4950     int src_enc = src->encoding();
4951     if (dst_enc == src_enc) {
4952       if (dst_enc < 16) {
4953         Assembler::pshuflw(dst, src, mode);
4954       } else {
4955         subptr(rsp, 64);
4956         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4957         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4958         Assembler::pshuflw(xmm0, xmm0, mode);
4959         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4960         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4961         addptr(rsp, 64);
4962       }
4963     } else {
4964       if ((src_enc < 16) && (dst_enc < 16)) {
4965         Assembler::pshuflw(dst, src, mode);
4966       } else if (src_enc < 16) {
4967         subptr(rsp, 64);
4968         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4969         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4970         Assembler::pshuflw(xmm0, src, mode);
4971         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4972         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4973         addptr(rsp, 64);
4974       } else if (dst_enc < 16) {
4975         subptr(rsp, 64);
4976         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4977         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4978         Assembler::pshuflw(dst, xmm0, mode);
4979         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4980         addptr(rsp, 64);
4981       } else {
4982         subptr(rsp, 64);
4983         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4984         subptr(rsp, 64);
4985         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4986         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4987         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4988         Assembler::pshuflw(xmm0, xmm1, mode);
4989         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4990         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4991         addptr(rsp, 64);
4992         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4993         addptr(rsp, 64);
4994       }
4995     }
4996   } else {
4997     Assembler::pshuflw(dst, src, mode);
4998   }
4999 }
5000 
5001 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5002   if (reachable(src)) {
5003     vandpd(dst, nds, as_Address(src), vector_len);
5004   } else {
5005     lea(rscratch1, src);
5006     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5007   }
5008 }
5009 
5010 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5011   if (reachable(src)) {
5012     vandps(dst, nds, as_Address(src), vector_len);
5013   } else {
5014     lea(rscratch1, src);
5015     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5016   }
5017 }
5018 
5019 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5020   if (reachable(src)) {
5021     vdivsd(dst, nds, as_Address(src));
5022   } else {
5023     lea(rscratch1, src);
5024     vdivsd(dst, nds, Address(rscratch1, 0));
5025   }
5026 }
5027 
5028 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5029   if (reachable(src)) {
5030     vdivss(dst, nds, as_Address(src));
5031   } else {
5032     lea(rscratch1, src);
5033     vdivss(dst, nds, Address(rscratch1, 0));
5034   }
5035 }
5036 
5037 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5038   if (reachable(src)) {
5039     vmulsd(dst, nds, as_Address(src));
5040   } else {
5041     lea(rscratch1, src);
5042     vmulsd(dst, nds, Address(rscratch1, 0));
5043   }
5044 }
5045 
5046 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5047   if (reachable(src)) {
5048     vmulss(dst, nds, as_Address(src));
5049   } else {
5050     lea(rscratch1, src);
5051     vmulss(dst, nds, Address(rscratch1, 0));
5052   }
5053 }
5054 
5055 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5056   if (reachable(src)) {
5057     vsubsd(dst, nds, as_Address(src));
5058   } else {
5059     lea(rscratch1, src);
5060     vsubsd(dst, nds, Address(rscratch1, 0));
5061   }
5062 }
5063 
5064 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5065   if (reachable(src)) {
5066     vsubss(dst, nds, as_Address(src));
5067   } else {
5068     lea(rscratch1, src);
5069     vsubss(dst, nds, Address(rscratch1, 0));
5070   }
5071 }
5072 
5073 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5074   int nds_enc = nds->encoding();
5075   int dst_enc = dst->encoding();
5076   bool dst_upper_bank = (dst_enc > 15);
5077   bool nds_upper_bank = (nds_enc > 15);
5078   if (VM_Version::supports_avx512novl() &&
5079       (nds_upper_bank || dst_upper_bank)) {
5080     if (dst_upper_bank) {
5081       subptr(rsp, 64);
5082       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5083       movflt(xmm0, nds);
5084       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5085       movflt(dst, xmm0);
5086       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5087       addptr(rsp, 64);
5088     } else {
5089       movflt(dst, nds);
5090       vxorps(dst, dst, src, Assembler::AVX_128bit);
5091     }
5092   } else {
5093     vxorps(dst, nds, src, Assembler::AVX_128bit);
5094   }
5095 }
5096 
5097 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5098   int nds_enc = nds->encoding();
5099   int dst_enc = dst->encoding();
5100   bool dst_upper_bank = (dst_enc > 15);
5101   bool nds_upper_bank = (nds_enc > 15);
5102   if (VM_Version::supports_avx512novl() &&
5103       (nds_upper_bank || dst_upper_bank)) {
5104     if (dst_upper_bank) {
5105       subptr(rsp, 64);
5106       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5107       movdbl(xmm0, nds);
5108       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5109       movdbl(dst, xmm0);
5110       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5111       addptr(rsp, 64);
5112     } else {
5113       movdbl(dst, nds);
5114       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5115     }
5116   } else {
5117     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5118   }
5119 }
5120 
5121 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5122   if (reachable(src)) {
5123     vxorpd(dst, nds, as_Address(src), vector_len);
5124   } else {
5125     lea(rscratch1, src);
5126     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5127   }
5128 }
5129 
5130 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5131   if (reachable(src)) {
5132     vxorps(dst, nds, as_Address(src), vector_len);
5133   } else {
5134     lea(rscratch1, src);
5135     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5136   }
5137 }
5138 
5139 
5140 void MacroAssembler::resolve_jobject(Register value,
5141                                      Register thread,
5142                                      Register tmp) {
5143   assert_different_registers(value, thread, tmp);
5144   Label done, not_weak;
5145   testptr(value, value);
5146   jcc(Assembler::zero, done);                // Use NULL as-is.
5147   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5148   jcc(Assembler::zero, not_weak);
5149   // Resolve jweak.
5150   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5151   verify_oop(value);
5152 #if INCLUDE_ALL_GCS
5153   if (UseG1GC) {
5154     g1_write_barrier_pre(noreg /* obj */,
5155                          value /* pre_val */,
5156                          thread /* thread */,
5157                          tmp /* tmp */,
5158                          true /* tosca_live */,
5159                          true /* expand_call */);
5160   }
5161 #endif // INCLUDE_ALL_GCS
5162   jmp(done);
5163   bind(not_weak);
5164   // Resolve (untagged) jobject.
5165   movptr(value, Address(value, 0));
5166   verify_oop(value);
5167   bind(done);
5168 }
5169 
5170 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5171   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5172   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5173   // The inverted mask is sign-extended
5174   andptr(possibly_jweak, inverted_jweak_mask);
5175 }
5176 
5177 //////////////////////////////////////////////////////////////////////////////////
5178 #if INCLUDE_ALL_GCS
5179 
5180 void MacroAssembler::g1_write_barrier_pre(Register obj,
5181                                           Register pre_val,
5182                                           Register thread,
5183                                           Register tmp,
5184                                           bool tosca_live,
5185                                           bool expand_call) {
5186 
5187   // If expand_call is true then we expand the call_VM_leaf macro
5188   // directly to skip generating the check by
5189   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5190 
5191 #ifdef _LP64
5192   assert(thread == r15_thread, "must be");
5193 #endif // _LP64
5194 
5195   Label done;
5196   Label runtime;
5197 
5198   assert(pre_val != noreg, "check this code");
5199 
5200   if (obj != noreg) {
5201     assert_different_registers(obj, pre_val, tmp);
5202     assert(pre_val != rax, "check this code");
5203   }
5204 
5205   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5206                                        SATBMarkQueue::byte_offset_of_active()));
5207   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5208                                        SATBMarkQueue::byte_offset_of_index()));
5209   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5210                                        SATBMarkQueue::byte_offset_of_buf()));
5211 
5212 
5213   // Is marking active?
5214   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5215     cmpl(in_progress, 0);
5216   } else {
5217     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5218     cmpb(in_progress, 0);
5219   }
5220   jcc(Assembler::equal, done);
5221 
5222   // Do we need to load the previous value?
5223   if (obj != noreg) {
5224     load_heap_oop(pre_val, Address(obj, 0));
5225   }
5226 
5227   // Is the previous value null?
5228   cmpptr(pre_val, (int32_t) NULL_WORD);
5229   jcc(Assembler::equal, done);
5230 
5231   // Can we store original value in the thread's buffer?
5232   // Is index == 0?
5233   // (The index field is typed as size_t.)
5234 
5235   movptr(tmp, index);                   // tmp := *index_adr
5236   cmpptr(tmp, 0);                       // tmp == 0?
5237   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5238 
5239   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5240   movptr(index, tmp);                   // *index_adr := tmp
5241   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5242 
5243   // Record the previous value
5244   movptr(Address(tmp, 0), pre_val);
5245   jmp(done);
5246 
5247   bind(runtime);
5248   // save the live input values
5249   if(tosca_live) push(rax);
5250 
5251   if (obj != noreg && obj != rax)
5252     push(obj);
5253 
5254   if (pre_val != rax)
5255     push(pre_val);
5256 
5257   // Calling the runtime using the regular call_VM_leaf mechanism generates
5258   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5259   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5260   //
5261   // If we care generating the pre-barrier without a frame (e.g. in the
5262   // intrinsified Reference.get() routine) then ebp might be pointing to
5263   // the caller frame and so this check will most likely fail at runtime.
5264   //
5265   // Expanding the call directly bypasses the generation of the check.
5266   // So when we do not have have a full interpreter frame on the stack
5267   // expand_call should be passed true.
5268 
5269   NOT_LP64( push(thread); )
5270 
5271   if (expand_call) {
5272     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5273     pass_arg1(this, thread);
5274     pass_arg0(this, pre_val);
5275     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5276   } else {
5277     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5278   }
5279 
5280   NOT_LP64( pop(thread); )
5281 
5282   // save the live input values
5283   if (pre_val != rax)
5284     pop(pre_val);
5285 
5286   if (obj != noreg && obj != rax)
5287     pop(obj);
5288 
5289   if(tosca_live) pop(rax);
5290 
5291   bind(done);
5292 }
5293 
5294 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5295                                            Register new_val,
5296                                            Register thread,
5297                                            Register tmp,
5298                                            Register tmp2) {
5299 #ifdef _LP64
5300   assert(thread == r15_thread, "must be");
5301 #endif // _LP64
5302 
5303   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5304                                        DirtyCardQueue::byte_offset_of_index()));
5305   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5306                                        DirtyCardQueue::byte_offset_of_buf()));
5307 
5308   CardTableModRefBS* ct =
5309     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5310   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5311 
5312   Label done;
5313   Label runtime;
5314 
5315   // Does store cross heap regions?
5316 
5317   movptr(tmp, store_addr);
5318   xorptr(tmp, new_val);
5319   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5320   jcc(Assembler::equal, done);
5321 
5322   // crosses regions, storing NULL?
5323 
5324   cmpptr(new_val, (int32_t) NULL_WORD);
5325   jcc(Assembler::equal, done);
5326 
5327   // storing region crossing non-NULL, is card already dirty?
5328 
5329   const Register card_addr = tmp;
5330   const Register cardtable = tmp2;
5331 
5332   movptr(card_addr, store_addr);
5333   shrptr(card_addr, CardTableModRefBS::card_shift);
5334   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5335   // a valid address and therefore is not properly handled by the relocation code.
5336   movptr(cardtable, (intptr_t)ct->byte_map_base);
5337   addptr(card_addr, cardtable);
5338 
5339   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5340   jcc(Assembler::equal, done);
5341 
5342   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5343   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5344   jcc(Assembler::equal, done);
5345 
5346 
5347   // storing a region crossing, non-NULL oop, card is clean.
5348   // dirty card and log.
5349 
5350   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5351 
5352   cmpl(queue_index, 0);
5353   jcc(Assembler::equal, runtime);
5354   subl(queue_index, wordSize);
5355   movptr(tmp2, buffer);
5356 #ifdef _LP64
5357   movslq(rscratch1, queue_index);
5358   addq(tmp2, rscratch1);
5359   movq(Address(tmp2, 0), card_addr);
5360 #else
5361   addl(tmp2, queue_index);
5362   movl(Address(tmp2, 0), card_addr);
5363 #endif
5364   jmp(done);
5365 
5366   bind(runtime);
5367   // save the live input values
5368   push(store_addr);
5369   push(new_val);
5370 #ifdef _LP64
5371   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5372 #else
5373   push(thread);
5374   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5375   pop(thread);
5376 #endif
5377   pop(new_val);
5378   pop(store_addr);
5379 
5380   bind(done);
5381 }
5382 
5383 #endif // INCLUDE_ALL_GCS
5384 //////////////////////////////////////////////////////////////////////////////////
5385 
5386 
5387 void MacroAssembler::store_check(Register obj, Address dst) {
5388   store_check(obj);
5389 }
5390 
5391 void MacroAssembler::store_check(Register obj) {
5392   // Does a store check for the oop in register obj. The content of
5393   // register obj is destroyed afterwards.
5394   BarrierSet* bs = Universe::heap()->barrier_set();
5395   assert(bs->kind() == BarrierSet::CardTableForRS ||
5396          bs->kind() == BarrierSet::CardTableExtension,
5397          "Wrong barrier set kind");
5398 
5399   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5400   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5401 
5402   shrptr(obj, CardTableModRefBS::card_shift);
5403 
5404   Address card_addr;
5405 
5406   // The calculation for byte_map_base is as follows:
5407   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5408   // So this essentially converts an address to a displacement and it will
5409   // never need to be relocated. On 64bit however the value may be too
5410   // large for a 32bit displacement.
5411   intptr_t disp = (intptr_t) ct->byte_map_base;
5412   if (is_simm32(disp)) {
5413     card_addr = Address(noreg, obj, Address::times_1, disp);
5414   } else {
5415     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5416     // displacement and done in a single instruction given favorable mapping and a
5417     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5418     // entry and that entry is not properly handled by the relocation code.
5419     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5420     Address index(noreg, obj, Address::times_1);
5421     card_addr = as_Address(ArrayAddress(cardtable, index));
5422   }
5423 
5424   int dirty = CardTableModRefBS::dirty_card_val();
5425   if (UseCondCardMark) {
5426     Label L_already_dirty;
5427     if (UseConcMarkSweepGC) {
5428       membar(Assembler::StoreLoad);
5429     }
5430     cmpb(card_addr, dirty);
5431     jcc(Assembler::equal, L_already_dirty);
5432     movb(card_addr, dirty);
5433     bind(L_already_dirty);
5434   } else {
5435     movb(card_addr, dirty);
5436   }
5437 }
5438 
5439 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5440   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5441 }
5442 
5443 // Force generation of a 4 byte immediate value even if it fits into 8bit
5444 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5445   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5446 }
5447 
5448 void MacroAssembler::subptr(Register dst, Register src) {
5449   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5450 }
5451 
5452 // C++ bool manipulation
5453 void MacroAssembler::testbool(Register dst) {
5454   if(sizeof(bool) == 1)
5455     testb(dst, 0xff);
5456   else if(sizeof(bool) == 2) {
5457     // testw implementation needed for two byte bools
5458     ShouldNotReachHere();
5459   } else if(sizeof(bool) == 4)
5460     testl(dst, dst);
5461   else
5462     // unsupported
5463     ShouldNotReachHere();
5464 }
5465 
5466 void MacroAssembler::testptr(Register dst, Register src) {
5467   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5468 }
5469 
5470 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5471 void MacroAssembler::tlab_allocate(Register obj,
5472                                    Register var_size_in_bytes,
5473                                    int con_size_in_bytes,
5474                                    Register t1,
5475                                    Register t2,
5476                                    Label& slow_case) {
5477   assert_different_registers(obj, t1, t2);
5478   assert_different_registers(obj, var_size_in_bytes, t1);
5479   Register end = t2;
5480   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5481 
5482   verify_tlab();
5483 
5484   NOT_LP64(get_thread(thread));
5485 
5486   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5487   if (var_size_in_bytes == noreg) {
5488     lea(end, Address(obj, con_size_in_bytes));
5489   } else {
5490     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5491   }
5492   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5493   jcc(Assembler::above, slow_case);
5494 
5495   // update the tlab top pointer
5496   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5497 
5498   // recover var_size_in_bytes if necessary
5499   if (var_size_in_bytes == end) {
5500     subptr(var_size_in_bytes, obj);
5501   }
5502   verify_tlab();
5503 }
5504 
5505 // Preserves rbx, and rdx.
5506 Register MacroAssembler::tlab_refill(Label& retry,
5507                                      Label& try_eden,
5508                                      Label& slow_case) {
5509   Register top = rax;
5510   Register t1  = rcx; // object size
5511   Register t2  = rsi;
5512   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5513   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5514   Label do_refill, discard_tlab;
5515 
5516   if (!Universe::heap()->supports_inline_contig_alloc()) {
5517     // No allocation in the shared eden.
5518     jmp(slow_case);
5519   }
5520 
5521   NOT_LP64(get_thread(thread_reg));
5522 
5523   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5524   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5525 
5526   // calculate amount of free space
5527   subptr(t1, top);
5528   shrptr(t1, LogHeapWordSize);
5529 
5530   // Retain tlab and allocate object in shared space if
5531   // the amount free in the tlab is too large to discard.
5532   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5533   jcc(Assembler::lessEqual, discard_tlab);
5534 
5535   // Retain
5536   // %%% yuck as movptr...
5537   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5538   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5539   if (TLABStats) {
5540     // increment number of slow_allocations
5541     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5542   }
5543   jmp(try_eden);
5544 
5545   bind(discard_tlab);
5546   if (TLABStats) {
5547     // increment number of refills
5548     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5549     // accumulate wastage -- t1 is amount free in tlab
5550     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5551   }
5552 
5553   // if tlab is currently allocated (top or end != null) then
5554   // fill [top, end + alignment_reserve) with array object
5555   testptr(top, top);
5556   jcc(Assembler::zero, do_refill);
5557 
5558   // set up the mark word
5559   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5560   // set the length to the remaining space
5561   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5562   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5563   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5564   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5565   // set klass to intArrayKlass
5566   // dubious reloc why not an oop reloc?
5567   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5568   // store klass last.  concurrent gcs assumes klass length is valid if
5569   // klass field is not null.
5570   store_klass(top, t1);
5571 
5572   movptr(t1, top);
5573   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5574   incr_allocated_bytes(thread_reg, t1, 0);
5575 
5576   // refill the tlab with an eden allocation
5577   bind(do_refill);
5578   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5579   shlptr(t1, LogHeapWordSize);
5580   // allocate new tlab, address returned in top
5581   eden_allocate(top, t1, 0, t2, slow_case);
5582 
5583   // Check that t1 was preserved in eden_allocate.
5584 #ifdef ASSERT
5585   if (UseTLAB) {
5586     Label ok;
5587     Register tsize = rsi;
5588     assert_different_registers(tsize, thread_reg, t1);
5589     push(tsize);
5590     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5591     shlptr(tsize, LogHeapWordSize);
5592     cmpptr(t1, tsize);
5593     jcc(Assembler::equal, ok);
5594     STOP("assert(t1 != tlab size)");
5595     should_not_reach_here();
5596 
5597     bind(ok);
5598     pop(tsize);
5599   }
5600 #endif
5601   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5602   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5603   addptr(top, t1);
5604   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5605   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5606 
5607   if (ZeroTLAB) {
5608     // This is a fast TLAB refill, therefore the GC is not notified of it.
5609     // So compiled code must fill the new TLAB with zeroes.
5610     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5611     zero_memory(top, t1, 0, t2);
5612   }
5613 
5614   verify_tlab();
5615   jmp(retry);
5616 
5617   return thread_reg; // for use by caller
5618 }
5619 
5620 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5621 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5622   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5623   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5624   Label done;
5625 
5626   testptr(length_in_bytes, length_in_bytes);
5627   jcc(Assembler::zero, done);
5628 
5629   // initialize topmost word, divide index by 2, check if odd and test if zero
5630   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5631 #ifdef ASSERT
5632   {
5633     Label L;
5634     testptr(length_in_bytes, BytesPerWord - 1);
5635     jcc(Assembler::zero, L);
5636     stop("length must be a multiple of BytesPerWord");
5637     bind(L);
5638   }
5639 #endif
5640   Register index = length_in_bytes;
5641   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5642   if (UseIncDec) {
5643     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5644   } else {
5645     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5646     shrptr(index, 1);
5647   }
5648 #ifndef _LP64
5649   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5650   {
5651     Label even;
5652     // note: if index was a multiple of 8, then it cannot
5653     //       be 0 now otherwise it must have been 0 before
5654     //       => if it is even, we don't need to check for 0 again
5655     jcc(Assembler::carryClear, even);
5656     // clear topmost word (no jump would be needed if conditional assignment worked here)
5657     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5658     // index could be 0 now, must check again
5659     jcc(Assembler::zero, done);
5660     bind(even);
5661   }
5662 #endif // !_LP64
5663   // initialize remaining object fields: index is a multiple of 2 now
5664   {
5665     Label loop;
5666     bind(loop);
5667     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5668     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5669     decrement(index);
5670     jcc(Assembler::notZero, loop);
5671   }
5672 
5673   bind(done);
5674 }
5675 
5676 void MacroAssembler::incr_allocated_bytes(Register thread,
5677                                           Register var_size_in_bytes,
5678                                           int con_size_in_bytes,
5679                                           Register t1) {
5680   if (!thread->is_valid()) {
5681 #ifdef _LP64
5682     thread = r15_thread;
5683 #else
5684     assert(t1->is_valid(), "need temp reg");
5685     thread = t1;
5686     get_thread(thread);
5687 #endif
5688   }
5689 
5690 #ifdef _LP64
5691   if (var_size_in_bytes->is_valid()) {
5692     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5693   } else {
5694     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5695   }
5696 #else
5697   if (var_size_in_bytes->is_valid()) {
5698     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5699   } else {
5700     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5701   }
5702   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5703 #endif
5704 }
5705 
5706 // Look up the method for a megamorphic invokeinterface call.
5707 // The target method is determined by <intf_klass, itable_index>.
5708 // The receiver klass is in recv_klass.
5709 // On success, the result will be in method_result, and execution falls through.
5710 // On failure, execution transfers to the given label.
5711 void MacroAssembler::lookup_interface_method(Register recv_klass,
5712                                              Register intf_klass,
5713                                              RegisterOrConstant itable_index,
5714                                              Register method_result,
5715                                              Register scan_temp,
5716                                              Label& L_no_such_interface) {
5717   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5718   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5719          "caller must use same register for non-constant itable index as for method");
5720 
5721   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5722   int vtable_base = in_bytes(Klass::vtable_start_offset());
5723   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5724   int scan_step   = itableOffsetEntry::size() * wordSize;
5725   int vte_size    = vtableEntry::size_in_bytes();
5726   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5727   assert(vte_size == wordSize, "else adjust times_vte_scale");
5728 
5729   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5730 
5731   // %%% Could store the aligned, prescaled offset in the klassoop.
5732   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5733 
5734   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5735   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5736   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5737 
5738   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5739   //   if (scan->interface() == intf) {
5740   //     result = (klass + scan->offset() + itable_index);
5741   //   }
5742   // }
5743   Label search, found_method;
5744 
5745   for (int peel = 1; peel >= 0; peel--) {
5746     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5747     cmpptr(intf_klass, method_result);
5748 
5749     if (peel) {
5750       jccb(Assembler::equal, found_method);
5751     } else {
5752       jccb(Assembler::notEqual, search);
5753       // (invert the test to fall through to found_method...)
5754     }
5755 
5756     if (!peel)  break;
5757 
5758     bind(search);
5759 
5760     // Check that the previous entry is non-null.  A null entry means that
5761     // the receiver class doesn't implement the interface, and wasn't the
5762     // same as when the caller was compiled.
5763     testptr(method_result, method_result);
5764     jcc(Assembler::zero, L_no_such_interface);
5765     addptr(scan_temp, scan_step);
5766   }
5767 
5768   bind(found_method);
5769 
5770   // Got a hit.
5771   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5772   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5773 }
5774 
5775 
5776 // virtual method calling
5777 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5778                                            RegisterOrConstant vtable_index,
5779                                            Register method_result) {
5780   const int base = in_bytes(Klass::vtable_start_offset());
5781   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5782   Address vtable_entry_addr(recv_klass,
5783                             vtable_index, Address::times_ptr,
5784                             base + vtableEntry::method_offset_in_bytes());
5785   movptr(method_result, vtable_entry_addr);
5786 }
5787 
5788 
5789 void MacroAssembler::check_klass_subtype(Register sub_klass,
5790                            Register super_klass,
5791                            Register temp_reg,
5792                            Label& L_success) {
5793   Label L_failure;
5794   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5795   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5796   bind(L_failure);
5797 }
5798 
5799 
5800 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5801                                                    Register super_klass,
5802                                                    Register temp_reg,
5803                                                    Label* L_success,
5804                                                    Label* L_failure,
5805                                                    Label* L_slow_path,
5806                                         RegisterOrConstant super_check_offset) {
5807   assert_different_registers(sub_klass, super_klass, temp_reg);
5808   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5809   if (super_check_offset.is_register()) {
5810     assert_different_registers(sub_klass, super_klass,
5811                                super_check_offset.as_register());
5812   } else if (must_load_sco) {
5813     assert(temp_reg != noreg, "supply either a temp or a register offset");
5814   }
5815 
5816   Label L_fallthrough;
5817   int label_nulls = 0;
5818   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5819   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5820   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5821   assert(label_nulls <= 1, "at most one NULL in the batch");
5822 
5823   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5824   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5825   Address super_check_offset_addr(super_klass, sco_offset);
5826 
5827   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5828   // range of a jccb.  If this routine grows larger, reconsider at
5829   // least some of these.
5830 #define local_jcc(assembler_cond, label)                                \
5831   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5832   else                             jcc( assembler_cond, label) /*omit semi*/
5833 
5834   // Hacked jmp, which may only be used just before L_fallthrough.
5835 #define final_jmp(label)                                                \
5836   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5837   else                            jmp(label)                /*omit semi*/
5838 
5839   // If the pointers are equal, we are done (e.g., String[] elements).
5840   // This self-check enables sharing of secondary supertype arrays among
5841   // non-primary types such as array-of-interface.  Otherwise, each such
5842   // type would need its own customized SSA.
5843   // We move this check to the front of the fast path because many
5844   // type checks are in fact trivially successful in this manner,
5845   // so we get a nicely predicted branch right at the start of the check.
5846   cmpptr(sub_klass, super_klass);
5847   local_jcc(Assembler::equal, *L_success);
5848 
5849   // Check the supertype display:
5850   if (must_load_sco) {
5851     // Positive movl does right thing on LP64.
5852     movl(temp_reg, super_check_offset_addr);
5853     super_check_offset = RegisterOrConstant(temp_reg);
5854   }
5855   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5856   cmpptr(super_klass, super_check_addr); // load displayed supertype
5857 
5858   // This check has worked decisively for primary supers.
5859   // Secondary supers are sought in the super_cache ('super_cache_addr').
5860   // (Secondary supers are interfaces and very deeply nested subtypes.)
5861   // This works in the same check above because of a tricky aliasing
5862   // between the super_cache and the primary super display elements.
5863   // (The 'super_check_addr' can address either, as the case requires.)
5864   // Note that the cache is updated below if it does not help us find
5865   // what we need immediately.
5866   // So if it was a primary super, we can just fail immediately.
5867   // Otherwise, it's the slow path for us (no success at this point).
5868 
5869   if (super_check_offset.is_register()) {
5870     local_jcc(Assembler::equal, *L_success);
5871     cmpl(super_check_offset.as_register(), sc_offset);
5872     if (L_failure == &L_fallthrough) {
5873       local_jcc(Assembler::equal, *L_slow_path);
5874     } else {
5875       local_jcc(Assembler::notEqual, *L_failure);
5876       final_jmp(*L_slow_path);
5877     }
5878   } else if (super_check_offset.as_constant() == sc_offset) {
5879     // Need a slow path; fast failure is impossible.
5880     if (L_slow_path == &L_fallthrough) {
5881       local_jcc(Assembler::equal, *L_success);
5882     } else {
5883       local_jcc(Assembler::notEqual, *L_slow_path);
5884       final_jmp(*L_success);
5885     }
5886   } else {
5887     // No slow path; it's a fast decision.
5888     if (L_failure == &L_fallthrough) {
5889       local_jcc(Assembler::equal, *L_success);
5890     } else {
5891       local_jcc(Assembler::notEqual, *L_failure);
5892       final_jmp(*L_success);
5893     }
5894   }
5895 
5896   bind(L_fallthrough);
5897 
5898 #undef local_jcc
5899 #undef final_jmp
5900 }
5901 
5902 
5903 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5904                                                    Register super_klass,
5905                                                    Register temp_reg,
5906                                                    Register temp2_reg,
5907                                                    Label* L_success,
5908                                                    Label* L_failure,
5909                                                    bool set_cond_codes) {
5910   assert_different_registers(sub_klass, super_klass, temp_reg);
5911   if (temp2_reg != noreg)
5912     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5913 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5914 
5915   Label L_fallthrough;
5916   int label_nulls = 0;
5917   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5918   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5919   assert(label_nulls <= 1, "at most one NULL in the batch");
5920 
5921   // a couple of useful fields in sub_klass:
5922   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5923   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5924   Address secondary_supers_addr(sub_klass, ss_offset);
5925   Address super_cache_addr(     sub_klass, sc_offset);
5926 
5927   // Do a linear scan of the secondary super-klass chain.
5928   // This code is rarely used, so simplicity is a virtue here.
5929   // The repne_scan instruction uses fixed registers, which we must spill.
5930   // Don't worry too much about pre-existing connections with the input regs.
5931 
5932   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5933   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5934 
5935   // Get super_klass value into rax (even if it was in rdi or rcx).
5936   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5937   if (super_klass != rax || UseCompressedOops) {
5938     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5939     mov(rax, super_klass);
5940   }
5941   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5942   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5943 
5944 #ifndef PRODUCT
5945   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5946   ExternalAddress pst_counter_addr((address) pst_counter);
5947   NOT_LP64(  incrementl(pst_counter_addr) );
5948   LP64_ONLY( lea(rcx, pst_counter_addr) );
5949   LP64_ONLY( incrementl(Address(rcx, 0)) );
5950 #endif //PRODUCT
5951 
5952   // We will consult the secondary-super array.
5953   movptr(rdi, secondary_supers_addr);
5954   // Load the array length.  (Positive movl does right thing on LP64.)
5955   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5956   // Skip to start of data.
5957   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5958 
5959   // Scan RCX words at [RDI] for an occurrence of RAX.
5960   // Set NZ/Z based on last compare.
5961   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5962   // not change flags (only scas instruction which is repeated sets flags).
5963   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5964 
5965     testptr(rax,rax); // Set Z = 0
5966     repne_scan();
5967 
5968   // Unspill the temp. registers:
5969   if (pushed_rdi)  pop(rdi);
5970   if (pushed_rcx)  pop(rcx);
5971   if (pushed_rax)  pop(rax);
5972 
5973   if (set_cond_codes) {
5974     // Special hack for the AD files:  rdi is guaranteed non-zero.
5975     assert(!pushed_rdi, "rdi must be left non-NULL");
5976     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5977   }
5978 
5979   if (L_failure == &L_fallthrough)
5980         jccb(Assembler::notEqual, *L_failure);
5981   else  jcc(Assembler::notEqual, *L_failure);
5982 
5983   // Success.  Cache the super we found and proceed in triumph.
5984   movptr(super_cache_addr, super_klass);
5985 
5986   if (L_success != &L_fallthrough) {
5987     jmp(*L_success);
5988   }
5989 
5990 #undef IS_A_TEMP
5991 
5992   bind(L_fallthrough);
5993 }
5994 
5995 
5996 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5997   if (VM_Version::supports_cmov()) {
5998     cmovl(cc, dst, src);
5999   } else {
6000     Label L;
6001     jccb(negate_condition(cc), L);
6002     movl(dst, src);
6003     bind(L);
6004   }
6005 }
6006 
6007 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6008   if (VM_Version::supports_cmov()) {
6009     cmovl(cc, dst, src);
6010   } else {
6011     Label L;
6012     jccb(negate_condition(cc), L);
6013     movl(dst, src);
6014     bind(L);
6015   }
6016 }
6017 
6018 void MacroAssembler::verify_oop(Register reg, const char* s) {
6019   if (!VerifyOops) return;
6020 
6021   // Pass register number to verify_oop_subroutine
6022   const char* b = NULL;
6023   {
6024     ResourceMark rm;
6025     stringStream ss;
6026     ss.print("verify_oop: %s: %s", reg->name(), s);
6027     b = code_string(ss.as_string());
6028   }
6029   BLOCK_COMMENT("verify_oop {");
6030 #ifdef _LP64
6031   push(rscratch1);                    // save r10, trashed by movptr()
6032 #endif
6033   push(rax);                          // save rax,
6034   push(reg);                          // pass register argument
6035   ExternalAddress buffer((address) b);
6036   // avoid using pushptr, as it modifies scratch registers
6037   // and our contract is not to modify anything
6038   movptr(rax, buffer.addr());
6039   push(rax);
6040   // call indirectly to solve generation ordering problem
6041   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6042   call(rax);
6043   // Caller pops the arguments (oop, message) and restores rax, r10
6044   BLOCK_COMMENT("} verify_oop");
6045 }
6046 
6047 
6048 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6049                                                       Register tmp,
6050                                                       int offset) {
6051   intptr_t value = *delayed_value_addr;
6052   if (value != 0)
6053     return RegisterOrConstant(value + offset);
6054 
6055   // load indirectly to solve generation ordering problem
6056   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6057 
6058 #ifdef ASSERT
6059   { Label L;
6060     testptr(tmp, tmp);
6061     if (WizardMode) {
6062       const char* buf = NULL;
6063       {
6064         ResourceMark rm;
6065         stringStream ss;
6066         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6067         buf = code_string(ss.as_string());
6068       }
6069       jcc(Assembler::notZero, L);
6070       STOP(buf);
6071     } else {
6072       jccb(Assembler::notZero, L);
6073       hlt();
6074     }
6075     bind(L);
6076   }
6077 #endif
6078 
6079   if (offset != 0)
6080     addptr(tmp, offset);
6081 
6082   return RegisterOrConstant(tmp);
6083 }
6084 
6085 
6086 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6087                                          int extra_slot_offset) {
6088   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6089   int stackElementSize = Interpreter::stackElementSize;
6090   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6091 #ifdef ASSERT
6092   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6093   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6094 #endif
6095   Register             scale_reg    = noreg;
6096   Address::ScaleFactor scale_factor = Address::no_scale;
6097   if (arg_slot.is_constant()) {
6098     offset += arg_slot.as_constant() * stackElementSize;
6099   } else {
6100     scale_reg    = arg_slot.as_register();
6101     scale_factor = Address::times(stackElementSize);
6102   }
6103   offset += wordSize;           // return PC is on stack
6104   return Address(rsp, scale_reg, scale_factor, offset);
6105 }
6106 
6107 
6108 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6109   if (!VerifyOops) return;
6110 
6111   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6112   // Pass register number to verify_oop_subroutine
6113   const char* b = NULL;
6114   {
6115     ResourceMark rm;
6116     stringStream ss;
6117     ss.print("verify_oop_addr: %s", s);
6118     b = code_string(ss.as_string());
6119   }
6120 #ifdef _LP64
6121   push(rscratch1);                    // save r10, trashed by movptr()
6122 #endif
6123   push(rax);                          // save rax,
6124   // addr may contain rsp so we will have to adjust it based on the push
6125   // we just did (and on 64 bit we do two pushes)
6126   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6127   // stores rax into addr which is backwards of what was intended.
6128   if (addr.uses(rsp)) {
6129     lea(rax, addr);
6130     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6131   } else {
6132     pushptr(addr);
6133   }
6134 
6135   ExternalAddress buffer((address) b);
6136   // pass msg argument
6137   // avoid using pushptr, as it modifies scratch registers
6138   // and our contract is not to modify anything
6139   movptr(rax, buffer.addr());
6140   push(rax);
6141 
6142   // call indirectly to solve generation ordering problem
6143   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6144   call(rax);
6145   // Caller pops the arguments (addr, message) and restores rax, r10.
6146 }
6147 
6148 void MacroAssembler::verify_tlab() {
6149 #ifdef ASSERT
6150   if (UseTLAB && VerifyOops) {
6151     Label next, ok;
6152     Register t1 = rsi;
6153     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6154 
6155     push(t1);
6156     NOT_LP64(push(thread_reg));
6157     NOT_LP64(get_thread(thread_reg));
6158 
6159     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6160     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6161     jcc(Assembler::aboveEqual, next);
6162     STOP("assert(top >= start)");
6163     should_not_reach_here();
6164 
6165     bind(next);
6166     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6167     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6168     jcc(Assembler::aboveEqual, ok);
6169     STOP("assert(top <= end)");
6170     should_not_reach_here();
6171 
6172     bind(ok);
6173     NOT_LP64(pop(thread_reg));
6174     pop(t1);
6175   }
6176 #endif
6177 }
6178 
6179 class ControlWord {
6180  public:
6181   int32_t _value;
6182 
6183   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6184   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6185   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6186   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6187   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6188   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6189   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6190   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6191 
6192   void print() const {
6193     // rounding control
6194     const char* rc;
6195     switch (rounding_control()) {
6196       case 0: rc = "round near"; break;
6197       case 1: rc = "round down"; break;
6198       case 2: rc = "round up  "; break;
6199       case 3: rc = "chop      "; break;
6200     };
6201     // precision control
6202     const char* pc;
6203     switch (precision_control()) {
6204       case 0: pc = "24 bits "; break;
6205       case 1: pc = "reserved"; break;
6206       case 2: pc = "53 bits "; break;
6207       case 3: pc = "64 bits "; break;
6208     };
6209     // flags
6210     char f[9];
6211     f[0] = ' ';
6212     f[1] = ' ';
6213     f[2] = (precision   ()) ? 'P' : 'p';
6214     f[3] = (underflow   ()) ? 'U' : 'u';
6215     f[4] = (overflow    ()) ? 'O' : 'o';
6216     f[5] = (zero_divide ()) ? 'Z' : 'z';
6217     f[6] = (denormalized()) ? 'D' : 'd';
6218     f[7] = (invalid     ()) ? 'I' : 'i';
6219     f[8] = '\x0';
6220     // output
6221     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6222   }
6223 
6224 };
6225 
6226 class StatusWord {
6227  public:
6228   int32_t _value;
6229 
6230   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6231   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6232   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6233   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6234   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6235   int  top() const                     { return  (_value >> 11) & 7      ; }
6236   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6237   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6238   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6239   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6240   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6241   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6242   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6243   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6244 
6245   void print() const {
6246     // condition codes
6247     char c[5];
6248     c[0] = (C3()) ? '3' : '-';
6249     c[1] = (C2()) ? '2' : '-';
6250     c[2] = (C1()) ? '1' : '-';
6251     c[3] = (C0()) ? '0' : '-';
6252     c[4] = '\x0';
6253     // flags
6254     char f[9];
6255     f[0] = (error_status()) ? 'E' : '-';
6256     f[1] = (stack_fault ()) ? 'S' : '-';
6257     f[2] = (precision   ()) ? 'P' : '-';
6258     f[3] = (underflow   ()) ? 'U' : '-';
6259     f[4] = (overflow    ()) ? 'O' : '-';
6260     f[5] = (zero_divide ()) ? 'Z' : '-';
6261     f[6] = (denormalized()) ? 'D' : '-';
6262     f[7] = (invalid     ()) ? 'I' : '-';
6263     f[8] = '\x0';
6264     // output
6265     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6266   }
6267 
6268 };
6269 
6270 class TagWord {
6271  public:
6272   int32_t _value;
6273 
6274   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6275 
6276   void print() const {
6277     printf("%04x", _value & 0xFFFF);
6278   }
6279 
6280 };
6281 
6282 class FPU_Register {
6283  public:
6284   int32_t _m0;
6285   int32_t _m1;
6286   int16_t _ex;
6287 
6288   bool is_indefinite() const           {
6289     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6290   }
6291 
6292   void print() const {
6293     char  sign = (_ex < 0) ? '-' : '+';
6294     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6295     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6296   };
6297 
6298 };
6299 
6300 class FPU_State {
6301  public:
6302   enum {
6303     register_size       = 10,
6304     number_of_registers =  8,
6305     register_mask       =  7
6306   };
6307 
6308   ControlWord  _control_word;
6309   StatusWord   _status_word;
6310   TagWord      _tag_word;
6311   int32_t      _error_offset;
6312   int32_t      _error_selector;
6313   int32_t      _data_offset;
6314   int32_t      _data_selector;
6315   int8_t       _register[register_size * number_of_registers];
6316 
6317   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6318   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6319 
6320   const char* tag_as_string(int tag) const {
6321     switch (tag) {
6322       case 0: return "valid";
6323       case 1: return "zero";
6324       case 2: return "special";
6325       case 3: return "empty";
6326     }
6327     ShouldNotReachHere();
6328     return NULL;
6329   }
6330 
6331   void print() const {
6332     // print computation registers
6333     { int t = _status_word.top();
6334       for (int i = 0; i < number_of_registers; i++) {
6335         int j = (i - t) & register_mask;
6336         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6337         st(j)->print();
6338         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6339       }
6340     }
6341     printf("\n");
6342     // print control registers
6343     printf("ctrl = "); _control_word.print(); printf("\n");
6344     printf("stat = "); _status_word .print(); printf("\n");
6345     printf("tags = "); _tag_word    .print(); printf("\n");
6346   }
6347 
6348 };
6349 
6350 class Flag_Register {
6351  public:
6352   int32_t _value;
6353 
6354   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6355   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6356   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6357   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6358   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6359   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6360   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6361 
6362   void print() const {
6363     // flags
6364     char f[8];
6365     f[0] = (overflow       ()) ? 'O' : '-';
6366     f[1] = (direction      ()) ? 'D' : '-';
6367     f[2] = (sign           ()) ? 'S' : '-';
6368     f[3] = (zero           ()) ? 'Z' : '-';
6369     f[4] = (auxiliary_carry()) ? 'A' : '-';
6370     f[5] = (parity         ()) ? 'P' : '-';
6371     f[6] = (carry          ()) ? 'C' : '-';
6372     f[7] = '\x0';
6373     // output
6374     printf("%08x  flags = %s", _value, f);
6375   }
6376 
6377 };
6378 
6379 class IU_Register {
6380  public:
6381   int32_t _value;
6382 
6383   void print() const {
6384     printf("%08x  %11d", _value, _value);
6385   }
6386 
6387 };
6388 
6389 class IU_State {
6390  public:
6391   Flag_Register _eflags;
6392   IU_Register   _rdi;
6393   IU_Register   _rsi;
6394   IU_Register   _rbp;
6395   IU_Register   _rsp;
6396   IU_Register   _rbx;
6397   IU_Register   _rdx;
6398   IU_Register   _rcx;
6399   IU_Register   _rax;
6400 
6401   void print() const {
6402     // computation registers
6403     printf("rax,  = "); _rax.print(); printf("\n");
6404     printf("rbx,  = "); _rbx.print(); printf("\n");
6405     printf("rcx  = "); _rcx.print(); printf("\n");
6406     printf("rdx  = "); _rdx.print(); printf("\n");
6407     printf("rdi  = "); _rdi.print(); printf("\n");
6408     printf("rsi  = "); _rsi.print(); printf("\n");
6409     printf("rbp,  = "); _rbp.print(); printf("\n");
6410     printf("rsp  = "); _rsp.print(); printf("\n");
6411     printf("\n");
6412     // control registers
6413     printf("flgs = "); _eflags.print(); printf("\n");
6414   }
6415 };
6416 
6417 
6418 class CPU_State {
6419  public:
6420   FPU_State _fpu_state;
6421   IU_State  _iu_state;
6422 
6423   void print() const {
6424     printf("--------------------------------------------------\n");
6425     _iu_state .print();
6426     printf("\n");
6427     _fpu_state.print();
6428     printf("--------------------------------------------------\n");
6429   }
6430 
6431 };
6432 
6433 
6434 static void _print_CPU_state(CPU_State* state) {
6435   state->print();
6436 };
6437 
6438 
6439 void MacroAssembler::print_CPU_state() {
6440   push_CPU_state();
6441   push(rsp);                // pass CPU state
6442   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6443   addptr(rsp, wordSize);       // discard argument
6444   pop_CPU_state();
6445 }
6446 
6447 
6448 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6449   static int counter = 0;
6450   FPU_State* fs = &state->_fpu_state;
6451   counter++;
6452   // For leaf calls, only verify that the top few elements remain empty.
6453   // We only need 1 empty at the top for C2 code.
6454   if( stack_depth < 0 ) {
6455     if( fs->tag_for_st(7) != 3 ) {
6456       printf("FPR7 not empty\n");
6457       state->print();
6458       assert(false, "error");
6459       return false;
6460     }
6461     return true;                // All other stack states do not matter
6462   }
6463 
6464   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6465          "bad FPU control word");
6466 
6467   // compute stack depth
6468   int i = 0;
6469   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6470   int d = i;
6471   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6472   // verify findings
6473   if (i != FPU_State::number_of_registers) {
6474     // stack not contiguous
6475     printf("%s: stack not contiguous at ST%d\n", s, i);
6476     state->print();
6477     assert(false, "error");
6478     return false;
6479   }
6480   // check if computed stack depth corresponds to expected stack depth
6481   if (stack_depth < 0) {
6482     // expected stack depth is -stack_depth or less
6483     if (d > -stack_depth) {
6484       // too many elements on the stack
6485       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6486       state->print();
6487       assert(false, "error");
6488       return false;
6489     }
6490   } else {
6491     // expected stack depth is stack_depth
6492     if (d != stack_depth) {
6493       // wrong stack depth
6494       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6495       state->print();
6496       assert(false, "error");
6497       return false;
6498     }
6499   }
6500   // everything is cool
6501   return true;
6502 }
6503 
6504 
6505 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6506   if (!VerifyFPU) return;
6507   push_CPU_state();
6508   push(rsp);                // pass CPU state
6509   ExternalAddress msg((address) s);
6510   // pass message string s
6511   pushptr(msg.addr());
6512   push(stack_depth);        // pass stack depth
6513   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6514   addptr(rsp, 3 * wordSize);   // discard arguments
6515   // check for error
6516   { Label L;
6517     testl(rax, rax);
6518     jcc(Assembler::notZero, L);
6519     int3();                  // break if error condition
6520     bind(L);
6521   }
6522   pop_CPU_state();
6523 }
6524 
6525 void MacroAssembler::restore_cpu_control_state_after_jni() {
6526   // Either restore the MXCSR register after returning from the JNI Call
6527   // or verify that it wasn't changed (with -Xcheck:jni flag).
6528   if (VM_Version::supports_sse()) {
6529     if (RestoreMXCSROnJNICalls) {
6530       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6531     } else if (CheckJNICalls) {
6532       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6533     }
6534   }
6535   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6536   vzeroupper();
6537 
6538 #ifndef _LP64
6539   // Either restore the x87 floating pointer control word after returning
6540   // from the JNI call or verify that it wasn't changed.
6541   if (CheckJNICalls) {
6542     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6543   }
6544 #endif // _LP64
6545 }
6546 
6547 void MacroAssembler::load_mirror(Register mirror, Register method) {
6548   // get mirror
6549   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6550   movptr(mirror, Address(method, Method::const_offset()));
6551   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6552   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6553   movptr(mirror, Address(mirror, mirror_offset));
6554 }
6555 
6556 void MacroAssembler::load_klass(Register dst, Register src) {
6557 #ifdef _LP64
6558   if (UseCompressedClassPointers) {
6559     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6560     decode_klass_not_null(dst);
6561   } else
6562 #endif
6563     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6564 }
6565 
6566 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6567   load_klass(dst, src);
6568   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6569 }
6570 
6571 void MacroAssembler::store_klass(Register dst, Register src) {
6572 #ifdef _LP64
6573   if (UseCompressedClassPointers) {
6574     encode_klass_not_null(src);
6575     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6576   } else
6577 #endif
6578     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6579 }
6580 
6581 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6582 #ifdef _LP64
6583   // FIXME: Must change all places where we try to load the klass.
6584   if (UseCompressedOops) {
6585     movl(dst, src);
6586     decode_heap_oop(dst);
6587   } else
6588 #endif
6589     movptr(dst, src);
6590 }
6591 
6592 // Doesn't do verfication, generates fixed size code
6593 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6594 #ifdef _LP64
6595   if (UseCompressedOops) {
6596     movl(dst, src);
6597     decode_heap_oop_not_null(dst);
6598   } else
6599 #endif
6600     movptr(dst, src);
6601 }
6602 
6603 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6604 #ifdef _LP64
6605   if (UseCompressedOops) {
6606     assert(!dst.uses(src), "not enough registers");
6607     encode_heap_oop(src);
6608     movl(dst, src);
6609   } else
6610 #endif
6611     movptr(dst, src);
6612 }
6613 
6614 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6615   assert_different_registers(src1, tmp);
6616 #ifdef _LP64
6617   if (UseCompressedOops) {
6618     bool did_push = false;
6619     if (tmp == noreg) {
6620       tmp = rax;
6621       push(tmp);
6622       did_push = true;
6623       assert(!src2.uses(rsp), "can't push");
6624     }
6625     load_heap_oop(tmp, src2);
6626     cmpptr(src1, tmp);
6627     if (did_push)  pop(tmp);
6628   } else
6629 #endif
6630     cmpptr(src1, src2);
6631 }
6632 
6633 // Used for storing NULLs.
6634 void MacroAssembler::store_heap_oop_null(Address dst) {
6635 #ifdef _LP64
6636   if (UseCompressedOops) {
6637     movl(dst, (int32_t)NULL_WORD);
6638   } else {
6639     movslq(dst, (int32_t)NULL_WORD);
6640   }
6641 #else
6642   movl(dst, (int32_t)NULL_WORD);
6643 #endif
6644 }
6645 
6646 #ifdef _LP64
6647 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6648   if (UseCompressedClassPointers) {
6649     // Store to klass gap in destination
6650     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6651   }
6652 }
6653 
6654 #ifdef ASSERT
6655 void MacroAssembler::verify_heapbase(const char* msg) {
6656   assert (UseCompressedOops, "should be compressed");
6657   assert (Universe::heap() != NULL, "java heap should be initialized");
6658   if (CheckCompressedOops) {
6659     Label ok;
6660     push(rscratch1); // cmpptr trashes rscratch1
6661     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6662     jcc(Assembler::equal, ok);
6663     STOP(msg);
6664     bind(ok);
6665     pop(rscratch1);
6666   }
6667 }
6668 #endif
6669 
6670 // Algorithm must match oop.inline.hpp encode_heap_oop.
6671 void MacroAssembler::encode_heap_oop(Register r) {
6672 #ifdef ASSERT
6673   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6674 #endif
6675   verify_oop(r, "broken oop in encode_heap_oop");
6676   if (Universe::narrow_oop_base() == NULL) {
6677     if (Universe::narrow_oop_shift() != 0) {
6678       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6679       shrq(r, LogMinObjAlignmentInBytes);
6680     }
6681     return;
6682   }
6683   testq(r, r);
6684   cmovq(Assembler::equal, r, r12_heapbase);
6685   subq(r, r12_heapbase);
6686   shrq(r, LogMinObjAlignmentInBytes);
6687 }
6688 
6689 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6690 #ifdef ASSERT
6691   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6692   if (CheckCompressedOops) {
6693     Label ok;
6694     testq(r, r);
6695     jcc(Assembler::notEqual, ok);
6696     STOP("null oop passed to encode_heap_oop_not_null");
6697     bind(ok);
6698   }
6699 #endif
6700   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6701   if (Universe::narrow_oop_base() != NULL) {
6702     subq(r, r12_heapbase);
6703   }
6704   if (Universe::narrow_oop_shift() != 0) {
6705     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6706     shrq(r, LogMinObjAlignmentInBytes);
6707   }
6708 }
6709 
6710 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6711 #ifdef ASSERT
6712   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6713   if (CheckCompressedOops) {
6714     Label ok;
6715     testq(src, src);
6716     jcc(Assembler::notEqual, ok);
6717     STOP("null oop passed to encode_heap_oop_not_null2");
6718     bind(ok);
6719   }
6720 #endif
6721   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6722   if (dst != src) {
6723     movq(dst, src);
6724   }
6725   if (Universe::narrow_oop_base() != NULL) {
6726     subq(dst, r12_heapbase);
6727   }
6728   if (Universe::narrow_oop_shift() != 0) {
6729     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6730     shrq(dst, LogMinObjAlignmentInBytes);
6731   }
6732 }
6733 
6734 void  MacroAssembler::decode_heap_oop(Register r) {
6735 #ifdef ASSERT
6736   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6737 #endif
6738   if (Universe::narrow_oop_base() == NULL) {
6739     if (Universe::narrow_oop_shift() != 0) {
6740       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6741       shlq(r, LogMinObjAlignmentInBytes);
6742     }
6743   } else {
6744     Label done;
6745     shlq(r, LogMinObjAlignmentInBytes);
6746     jccb(Assembler::equal, done);
6747     addq(r, r12_heapbase);
6748     bind(done);
6749   }
6750   verify_oop(r, "broken oop in decode_heap_oop");
6751 }
6752 
6753 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6754   // Note: it will change flags
6755   assert (UseCompressedOops, "should only be used for compressed headers");
6756   assert (Universe::heap() != NULL, "java heap should be initialized");
6757   // Cannot assert, unverified entry point counts instructions (see .ad file)
6758   // vtableStubs also counts instructions in pd_code_size_limit.
6759   // Also do not verify_oop as this is called by verify_oop.
6760   if (Universe::narrow_oop_shift() != 0) {
6761     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6762     shlq(r, LogMinObjAlignmentInBytes);
6763     if (Universe::narrow_oop_base() != NULL) {
6764       addq(r, r12_heapbase);
6765     }
6766   } else {
6767     assert (Universe::narrow_oop_base() == NULL, "sanity");
6768   }
6769 }
6770 
6771 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6772   // Note: it will change flags
6773   assert (UseCompressedOops, "should only be used for compressed headers");
6774   assert (Universe::heap() != NULL, "java heap should be initialized");
6775   // Cannot assert, unverified entry point counts instructions (see .ad file)
6776   // vtableStubs also counts instructions in pd_code_size_limit.
6777   // Also do not verify_oop as this is called by verify_oop.
6778   if (Universe::narrow_oop_shift() != 0) {
6779     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6780     if (LogMinObjAlignmentInBytes == Address::times_8) {
6781       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6782     } else {
6783       if (dst != src) {
6784         movq(dst, src);
6785       }
6786       shlq(dst, LogMinObjAlignmentInBytes);
6787       if (Universe::narrow_oop_base() != NULL) {
6788         addq(dst, r12_heapbase);
6789       }
6790     }
6791   } else {
6792     assert (Universe::narrow_oop_base() == NULL, "sanity");
6793     if (dst != src) {
6794       movq(dst, src);
6795     }
6796   }
6797 }
6798 
6799 void MacroAssembler::encode_klass_not_null(Register r) {
6800   if (Universe::narrow_klass_base() != NULL) {
6801     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6802     assert(r != r12_heapbase, "Encoding a klass in r12");
6803     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6804     subq(r, r12_heapbase);
6805   }
6806   if (Universe::narrow_klass_shift() != 0) {
6807     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6808     shrq(r, LogKlassAlignmentInBytes);
6809   }
6810   if (Universe::narrow_klass_base() != NULL) {
6811     reinit_heapbase();
6812   }
6813 }
6814 
6815 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6816   if (dst == src) {
6817     encode_klass_not_null(src);
6818   } else {
6819     if (Universe::narrow_klass_base() != NULL) {
6820       mov64(dst, (int64_t)Universe::narrow_klass_base());
6821       negq(dst);
6822       addq(dst, src);
6823     } else {
6824       movptr(dst, src);
6825     }
6826     if (Universe::narrow_klass_shift() != 0) {
6827       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6828       shrq(dst, LogKlassAlignmentInBytes);
6829     }
6830   }
6831 }
6832 
6833 // Function instr_size_for_decode_klass_not_null() counts the instructions
6834 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6835 // when (Universe::heap() != NULL).  Hence, if the instructions they
6836 // generate change, then this method needs to be updated.
6837 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6838   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6839   if (Universe::narrow_klass_base() != NULL) {
6840     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6841     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6842   } else {
6843     // longest load decode klass function, mov64, leaq
6844     return 16;
6845   }
6846 }
6847 
6848 // !!! If the instructions that get generated here change then function
6849 // instr_size_for_decode_klass_not_null() needs to get updated.
6850 void  MacroAssembler::decode_klass_not_null(Register r) {
6851   // Note: it will change flags
6852   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6853   assert(r != r12_heapbase, "Decoding a klass in r12");
6854   // Cannot assert, unverified entry point counts instructions (see .ad file)
6855   // vtableStubs also counts instructions in pd_code_size_limit.
6856   // Also do not verify_oop as this is called by verify_oop.
6857   if (Universe::narrow_klass_shift() != 0) {
6858     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6859     shlq(r, LogKlassAlignmentInBytes);
6860   }
6861   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6862   if (Universe::narrow_klass_base() != NULL) {
6863     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6864     addq(r, r12_heapbase);
6865     reinit_heapbase();
6866   }
6867 }
6868 
6869 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6870   // Note: it will change flags
6871   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6872   if (dst == src) {
6873     decode_klass_not_null(dst);
6874   } else {
6875     // Cannot assert, unverified entry point counts instructions (see .ad file)
6876     // vtableStubs also counts instructions in pd_code_size_limit.
6877     // Also do not verify_oop as this is called by verify_oop.
6878     mov64(dst, (int64_t)Universe::narrow_klass_base());
6879     if (Universe::narrow_klass_shift() != 0) {
6880       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6881       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6882       leaq(dst, Address(dst, src, Address::times_8, 0));
6883     } else {
6884       addq(dst, src);
6885     }
6886   }
6887 }
6888 
6889 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6890   assert (UseCompressedOops, "should only be used for compressed headers");
6891   assert (Universe::heap() != NULL, "java heap should be initialized");
6892   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6893   int oop_index = oop_recorder()->find_index(obj);
6894   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6895   mov_narrow_oop(dst, oop_index, rspec);
6896 }
6897 
6898 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6899   assert (UseCompressedOops, "should only be used for compressed headers");
6900   assert (Universe::heap() != NULL, "java heap should be initialized");
6901   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6902   int oop_index = oop_recorder()->find_index(obj);
6903   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6904   mov_narrow_oop(dst, oop_index, rspec);
6905 }
6906 
6907 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6908   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6909   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6910   int klass_index = oop_recorder()->find_index(k);
6911   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6912   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6913 }
6914 
6915 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6916   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6917   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6918   int klass_index = oop_recorder()->find_index(k);
6919   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6920   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6921 }
6922 
6923 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6924   assert (UseCompressedOops, "should only be used for compressed headers");
6925   assert (Universe::heap() != NULL, "java heap should be initialized");
6926   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6927   int oop_index = oop_recorder()->find_index(obj);
6928   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6929   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6930 }
6931 
6932 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6933   assert (UseCompressedOops, "should only be used for compressed headers");
6934   assert (Universe::heap() != NULL, "java heap should be initialized");
6935   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6936   int oop_index = oop_recorder()->find_index(obj);
6937   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6938   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6939 }
6940 
6941 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6942   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6943   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6944   int klass_index = oop_recorder()->find_index(k);
6945   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6946   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6947 }
6948 
6949 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6950   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6951   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6952   int klass_index = oop_recorder()->find_index(k);
6953   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6954   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6955 }
6956 
6957 void MacroAssembler::reinit_heapbase() {
6958   if (UseCompressedOops || UseCompressedClassPointers) {
6959     if (Universe::heap() != NULL) {
6960       if (Universe::narrow_oop_base() == NULL) {
6961         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6962       } else {
6963         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6964       }
6965     } else {
6966       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6967     }
6968   }
6969 }
6970 
6971 #endif // _LP64
6972 
6973 
6974 // C2 compiled method's prolog code.
6975 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6976 
6977   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6978   // NativeJump::patch_verified_entry will be able to patch out the entry
6979   // code safely. The push to verify stack depth is ok at 5 bytes,
6980   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6981   // stack bang then we must use the 6 byte frame allocation even if
6982   // we have no frame. :-(
6983   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6984 
6985   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6986   // Remove word for return addr
6987   framesize -= wordSize;
6988   stack_bang_size -= wordSize;
6989 
6990   // Calls to C2R adapters often do not accept exceptional returns.
6991   // We require that their callers must bang for them.  But be careful, because
6992   // some VM calls (such as call site linkage) can use several kilobytes of
6993   // stack.  But the stack safety zone should account for that.
6994   // See bugs 4446381, 4468289, 4497237.
6995   if (stack_bang_size > 0) {
6996     generate_stack_overflow_check(stack_bang_size);
6997 
6998     // We always push rbp, so that on return to interpreter rbp, will be
6999     // restored correctly and we can correct the stack.
7000     push(rbp);
7001     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7002     if (PreserveFramePointer) {
7003       mov(rbp, rsp);
7004     }
7005     // Remove word for ebp
7006     framesize -= wordSize;
7007 
7008     // Create frame
7009     if (framesize) {
7010       subptr(rsp, framesize);
7011     }
7012   } else {
7013     // Create frame (force generation of a 4 byte immediate value)
7014     subptr_imm32(rsp, framesize);
7015 
7016     // Save RBP register now.
7017     framesize -= wordSize;
7018     movptr(Address(rsp, framesize), rbp);
7019     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7020     if (PreserveFramePointer) {
7021       movptr(rbp, rsp);
7022       if (framesize > 0) {
7023         addptr(rbp, framesize);
7024       }
7025     }
7026   }
7027 
7028   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7029     framesize -= wordSize;
7030     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7031   }
7032 
7033 #ifndef _LP64
7034   // If method sets FPU control word do it now
7035   if (fp_mode_24b) {
7036     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7037   }
7038   if (UseSSE >= 2 && VerifyFPU) {
7039     verify_FPU(0, "FPU stack must be clean on entry");
7040   }
7041 #endif
7042 
7043 #ifdef ASSERT
7044   if (VerifyStackAtCalls) {
7045     Label L;
7046     push(rax);
7047     mov(rax, rsp);
7048     andptr(rax, StackAlignmentInBytes-1);
7049     cmpptr(rax, StackAlignmentInBytes-wordSize);
7050     pop(rax);
7051     jcc(Assembler::equal, L);
7052     STOP("Stack is not properly aligned!");
7053     bind(L);
7054   }
7055 #endif
7056 
7057 }
7058 
7059 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7060   // cnt - number of qwords (8-byte words).
7061   // base - start address, qword aligned.
7062   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7063   assert(base==rdi, "base register must be edi for rep stos");
7064   assert(tmp==rax,   "tmp register must be eax for rep stos");
7065   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7066   assert(InitArrayShortSize % BytesPerLong == 0,
7067     "InitArrayShortSize should be the multiple of BytesPerLong");
7068 
7069   Label DONE;
7070 
7071   xorptr(tmp, tmp);
7072 
7073   if (!is_large) {
7074     Label LOOP, LONG;
7075     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7076     jccb(Assembler::greater, LONG);
7077 
7078     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7079 
7080     decrement(cnt);
7081     jccb(Assembler::negative, DONE); // Zero length
7082 
7083     // Use individual pointer-sized stores for small counts:
7084     BIND(LOOP);
7085     movptr(Address(base, cnt, Address::times_ptr), tmp);
7086     decrement(cnt);
7087     jccb(Assembler::greaterEqual, LOOP);
7088     jmpb(DONE);
7089 
7090     BIND(LONG);
7091   }
7092 
7093   // Use longer rep-prefixed ops for non-small counts:
7094   if (UseFastStosb) {
7095     shlptr(cnt, 3); // convert to number of bytes
7096     rep_stosb();
7097   } else {
7098     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7099     rep_stos();
7100   }
7101 
7102   BIND(DONE);
7103 }
7104 
7105 #ifdef COMPILER2
7106 
7107 // IndexOf for constant substrings with size >= 8 chars
7108 // which don't need to be loaded through stack.
7109 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7110                                       Register cnt1, Register cnt2,
7111                                       int int_cnt2,  Register result,
7112                                       XMMRegister vec, Register tmp,
7113                                       int ae) {
7114   ShortBranchVerifier sbv(this);
7115   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7116   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7117 
7118   // This method uses the pcmpestri instruction with bound registers
7119   //   inputs:
7120   //     xmm - substring
7121   //     rax - substring length (elements count)
7122   //     mem - scanned string
7123   //     rdx - string length (elements count)
7124   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7125   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7126   //   outputs:
7127   //     rcx - matched index in string
7128   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7129   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7130   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7131   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7132   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7133 
7134   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7135         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7136         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7137 
7138   // Note, inline_string_indexOf() generates checks:
7139   // if (substr.count > string.count) return -1;
7140   // if (substr.count == 0) return 0;
7141   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7142 
7143   // Load substring.
7144   if (ae == StrIntrinsicNode::UL) {
7145     pmovzxbw(vec, Address(str2, 0));
7146   } else {
7147     movdqu(vec, Address(str2, 0));
7148   }
7149   movl(cnt2, int_cnt2);
7150   movptr(result, str1); // string addr
7151 
7152   if (int_cnt2 > stride) {
7153     jmpb(SCAN_TO_SUBSTR);
7154 
7155     // Reload substr for rescan, this code
7156     // is executed only for large substrings (> 8 chars)
7157     bind(RELOAD_SUBSTR);
7158     if (ae == StrIntrinsicNode::UL) {
7159       pmovzxbw(vec, Address(str2, 0));
7160     } else {
7161       movdqu(vec, Address(str2, 0));
7162     }
7163     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7164 
7165     bind(RELOAD_STR);
7166     // We came here after the beginning of the substring was
7167     // matched but the rest of it was not so we need to search
7168     // again. Start from the next element after the previous match.
7169 
7170     // cnt2 is number of substring reminding elements and
7171     // cnt1 is number of string reminding elements when cmp failed.
7172     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7173     subl(cnt1, cnt2);
7174     addl(cnt1, int_cnt2);
7175     movl(cnt2, int_cnt2); // Now restore cnt2
7176 
7177     decrementl(cnt1);     // Shift to next element
7178     cmpl(cnt1, cnt2);
7179     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7180 
7181     addptr(result, (1<<scale1));
7182 
7183   } // (int_cnt2 > 8)
7184 
7185   // Scan string for start of substr in 16-byte vectors
7186   bind(SCAN_TO_SUBSTR);
7187   pcmpestri(vec, Address(result, 0), mode);
7188   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7189   subl(cnt1, stride);
7190   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7191   cmpl(cnt1, cnt2);
7192   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7193   addptr(result, 16);
7194   jmpb(SCAN_TO_SUBSTR);
7195 
7196   // Found a potential substr
7197   bind(FOUND_CANDIDATE);
7198   // Matched whole vector if first element matched (tmp(rcx) == 0).
7199   if (int_cnt2 == stride) {
7200     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7201   } else { // int_cnt2 > 8
7202     jccb(Assembler::overflow, FOUND_SUBSTR);
7203   }
7204   // After pcmpestri tmp(rcx) contains matched element index
7205   // Compute start addr of substr
7206   lea(result, Address(result, tmp, scale1));
7207 
7208   // Make sure string is still long enough
7209   subl(cnt1, tmp);
7210   cmpl(cnt1, cnt2);
7211   if (int_cnt2 == stride) {
7212     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7213   } else { // int_cnt2 > 8
7214     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7215   }
7216   // Left less then substring.
7217 
7218   bind(RET_NOT_FOUND);
7219   movl(result, -1);
7220   jmp(EXIT);
7221 
7222   if (int_cnt2 > stride) {
7223     // This code is optimized for the case when whole substring
7224     // is matched if its head is matched.
7225     bind(MATCH_SUBSTR_HEAD);
7226     pcmpestri(vec, Address(result, 0), mode);
7227     // Reload only string if does not match
7228     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7229 
7230     Label CONT_SCAN_SUBSTR;
7231     // Compare the rest of substring (> 8 chars).
7232     bind(FOUND_SUBSTR);
7233     // First 8 chars are already matched.
7234     negptr(cnt2);
7235     addptr(cnt2, stride);
7236 
7237     bind(SCAN_SUBSTR);
7238     subl(cnt1, stride);
7239     cmpl(cnt2, -stride); // Do not read beyond substring
7240     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7241     // Back-up strings to avoid reading beyond substring:
7242     // cnt1 = cnt1 - cnt2 + 8
7243     addl(cnt1, cnt2); // cnt2 is negative
7244     addl(cnt1, stride);
7245     movl(cnt2, stride); negptr(cnt2);
7246     bind(CONT_SCAN_SUBSTR);
7247     if (int_cnt2 < (int)G) {
7248       int tail_off1 = int_cnt2<<scale1;
7249       int tail_off2 = int_cnt2<<scale2;
7250       if (ae == StrIntrinsicNode::UL) {
7251         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7252       } else {
7253         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7254       }
7255       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7256     } else {
7257       // calculate index in register to avoid integer overflow (int_cnt2*2)
7258       movl(tmp, int_cnt2);
7259       addptr(tmp, cnt2);
7260       if (ae == StrIntrinsicNode::UL) {
7261         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7262       } else {
7263         movdqu(vec, Address(str2, tmp, scale2, 0));
7264       }
7265       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7266     }
7267     // Need to reload strings pointers if not matched whole vector
7268     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7269     addptr(cnt2, stride);
7270     jcc(Assembler::negative, SCAN_SUBSTR);
7271     // Fall through if found full substring
7272 
7273   } // (int_cnt2 > 8)
7274 
7275   bind(RET_FOUND);
7276   // Found result if we matched full small substring.
7277   // Compute substr offset
7278   subptr(result, str1);
7279   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7280     shrl(result, 1); // index
7281   }
7282   bind(EXIT);
7283 
7284 } // string_indexofC8
7285 
7286 // Small strings are loaded through stack if they cross page boundary.
7287 void MacroAssembler::string_indexof(Register str1, Register str2,
7288                                     Register cnt1, Register cnt2,
7289                                     int int_cnt2,  Register result,
7290                                     XMMRegister vec, Register tmp,
7291                                     int ae) {
7292   ShortBranchVerifier sbv(this);
7293   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7294   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7295 
7296   //
7297   // int_cnt2 is length of small (< 8 chars) constant substring
7298   // or (-1) for non constant substring in which case its length
7299   // is in cnt2 register.
7300   //
7301   // Note, inline_string_indexOf() generates checks:
7302   // if (substr.count > string.count) return -1;
7303   // if (substr.count == 0) return 0;
7304   //
7305   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7306   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7307   // This method uses the pcmpestri instruction with bound registers
7308   //   inputs:
7309   //     xmm - substring
7310   //     rax - substring length (elements count)
7311   //     mem - scanned string
7312   //     rdx - string length (elements count)
7313   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7314   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7315   //   outputs:
7316   //     rcx - matched index in string
7317   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7318   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7319   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7320   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7321 
7322   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7323         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7324         FOUND_CANDIDATE;
7325 
7326   { //========================================================
7327     // We don't know where these strings are located
7328     // and we can't read beyond them. Load them through stack.
7329     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7330 
7331     movptr(tmp, rsp); // save old SP
7332 
7333     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7334       if (int_cnt2 == (1>>scale2)) { // One byte
7335         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7336         load_unsigned_byte(result, Address(str2, 0));
7337         movdl(vec, result); // move 32 bits
7338       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7339         // Not enough header space in 32-bit VM: 12+3 = 15.
7340         movl(result, Address(str2, -1));
7341         shrl(result, 8);
7342         movdl(vec, result); // move 32 bits
7343       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7344         load_unsigned_short(result, Address(str2, 0));
7345         movdl(vec, result); // move 32 bits
7346       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7347         movdl(vec, Address(str2, 0)); // move 32 bits
7348       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7349         movq(vec, Address(str2, 0));  // move 64 bits
7350       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7351         // Array header size is 12 bytes in 32-bit VM
7352         // + 6 bytes for 3 chars == 18 bytes,
7353         // enough space to load vec and shift.
7354         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7355         if (ae == StrIntrinsicNode::UL) {
7356           int tail_off = int_cnt2-8;
7357           pmovzxbw(vec, Address(str2, tail_off));
7358           psrldq(vec, -2*tail_off);
7359         }
7360         else {
7361           int tail_off = int_cnt2*(1<<scale2);
7362           movdqu(vec, Address(str2, tail_off-16));
7363           psrldq(vec, 16-tail_off);
7364         }
7365       }
7366     } else { // not constant substring
7367       cmpl(cnt2, stride);
7368       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7369 
7370       // We can read beyond string if srt+16 does not cross page boundary
7371       // since heaps are aligned and mapped by pages.
7372       assert(os::vm_page_size() < (int)G, "default page should be small");
7373       movl(result, str2); // We need only low 32 bits
7374       andl(result, (os::vm_page_size()-1));
7375       cmpl(result, (os::vm_page_size()-16));
7376       jccb(Assembler::belowEqual, CHECK_STR);
7377 
7378       // Move small strings to stack to allow load 16 bytes into vec.
7379       subptr(rsp, 16);
7380       int stk_offset = wordSize-(1<<scale2);
7381       push(cnt2);
7382 
7383       bind(COPY_SUBSTR);
7384       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7385         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7386         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7387       } else if (ae == StrIntrinsicNode::UU) {
7388         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7389         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7390       }
7391       decrement(cnt2);
7392       jccb(Assembler::notZero, COPY_SUBSTR);
7393 
7394       pop(cnt2);
7395       movptr(str2, rsp);  // New substring address
7396     } // non constant
7397 
7398     bind(CHECK_STR);
7399     cmpl(cnt1, stride);
7400     jccb(Assembler::aboveEqual, BIG_STRINGS);
7401 
7402     // Check cross page boundary.
7403     movl(result, str1); // We need only low 32 bits
7404     andl(result, (os::vm_page_size()-1));
7405     cmpl(result, (os::vm_page_size()-16));
7406     jccb(Assembler::belowEqual, BIG_STRINGS);
7407 
7408     subptr(rsp, 16);
7409     int stk_offset = -(1<<scale1);
7410     if (int_cnt2 < 0) { // not constant
7411       push(cnt2);
7412       stk_offset += wordSize;
7413     }
7414     movl(cnt2, cnt1);
7415 
7416     bind(COPY_STR);
7417     if (ae == StrIntrinsicNode::LL) {
7418       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7419       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7420     } else {
7421       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7422       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7423     }
7424     decrement(cnt2);
7425     jccb(Assembler::notZero, COPY_STR);
7426 
7427     if (int_cnt2 < 0) { // not constant
7428       pop(cnt2);
7429     }
7430     movptr(str1, rsp);  // New string address
7431 
7432     bind(BIG_STRINGS);
7433     // Load substring.
7434     if (int_cnt2 < 0) { // -1
7435       if (ae == StrIntrinsicNode::UL) {
7436         pmovzxbw(vec, Address(str2, 0));
7437       } else {
7438         movdqu(vec, Address(str2, 0));
7439       }
7440       push(cnt2);       // substr count
7441       push(str2);       // substr addr
7442       push(str1);       // string addr
7443     } else {
7444       // Small (< 8 chars) constant substrings are loaded already.
7445       movl(cnt2, int_cnt2);
7446     }
7447     push(tmp);  // original SP
7448 
7449   } // Finished loading
7450 
7451   //========================================================
7452   // Start search
7453   //
7454 
7455   movptr(result, str1); // string addr
7456 
7457   if (int_cnt2  < 0) {  // Only for non constant substring
7458     jmpb(SCAN_TO_SUBSTR);
7459 
7460     // SP saved at sp+0
7461     // String saved at sp+1*wordSize
7462     // Substr saved at sp+2*wordSize
7463     // Substr count saved at sp+3*wordSize
7464 
7465     // Reload substr for rescan, this code
7466     // is executed only for large substrings (> 8 chars)
7467     bind(RELOAD_SUBSTR);
7468     movptr(str2, Address(rsp, 2*wordSize));
7469     movl(cnt2, Address(rsp, 3*wordSize));
7470     if (ae == StrIntrinsicNode::UL) {
7471       pmovzxbw(vec, Address(str2, 0));
7472     } else {
7473       movdqu(vec, Address(str2, 0));
7474     }
7475     // We came here after the beginning of the substring was
7476     // matched but the rest of it was not so we need to search
7477     // again. Start from the next element after the previous match.
7478     subptr(str1, result); // Restore counter
7479     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7480       shrl(str1, 1);
7481     }
7482     addl(cnt1, str1);
7483     decrementl(cnt1);   // Shift to next element
7484     cmpl(cnt1, cnt2);
7485     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7486 
7487     addptr(result, (1<<scale1));
7488   } // non constant
7489 
7490   // Scan string for start of substr in 16-byte vectors
7491   bind(SCAN_TO_SUBSTR);
7492   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7493   pcmpestri(vec, Address(result, 0), mode);
7494   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7495   subl(cnt1, stride);
7496   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7497   cmpl(cnt1, cnt2);
7498   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7499   addptr(result, 16);
7500 
7501   bind(ADJUST_STR);
7502   cmpl(cnt1, stride); // Do not read beyond string
7503   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7504   // Back-up string to avoid reading beyond string.
7505   lea(result, Address(result, cnt1, scale1, -16));
7506   movl(cnt1, stride);
7507   jmpb(SCAN_TO_SUBSTR);
7508 
7509   // Found a potential substr
7510   bind(FOUND_CANDIDATE);
7511   // After pcmpestri tmp(rcx) contains matched element index
7512 
7513   // Make sure string is still long enough
7514   subl(cnt1, tmp);
7515   cmpl(cnt1, cnt2);
7516   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7517   // Left less then substring.
7518 
7519   bind(RET_NOT_FOUND);
7520   movl(result, -1);
7521   jmpb(CLEANUP);
7522 
7523   bind(FOUND_SUBSTR);
7524   // Compute start addr of substr
7525   lea(result, Address(result, tmp, scale1));
7526   if (int_cnt2 > 0) { // Constant substring
7527     // Repeat search for small substring (< 8 chars)
7528     // from new point without reloading substring.
7529     // Have to check that we don't read beyond string.
7530     cmpl(tmp, stride-int_cnt2);
7531     jccb(Assembler::greater, ADJUST_STR);
7532     // Fall through if matched whole substring.
7533   } else { // non constant
7534     assert(int_cnt2 == -1, "should be != 0");
7535 
7536     addl(tmp, cnt2);
7537     // Found result if we matched whole substring.
7538     cmpl(tmp, stride);
7539     jccb(Assembler::lessEqual, RET_FOUND);
7540 
7541     // Repeat search for small substring (<= 8 chars)
7542     // from new point 'str1' without reloading substring.
7543     cmpl(cnt2, stride);
7544     // Have to check that we don't read beyond string.
7545     jccb(Assembler::lessEqual, ADJUST_STR);
7546 
7547     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7548     // Compare the rest of substring (> 8 chars).
7549     movptr(str1, result);
7550 
7551     cmpl(tmp, cnt2);
7552     // First 8 chars are already matched.
7553     jccb(Assembler::equal, CHECK_NEXT);
7554 
7555     bind(SCAN_SUBSTR);
7556     pcmpestri(vec, Address(str1, 0), mode);
7557     // Need to reload strings pointers if not matched whole vector
7558     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7559 
7560     bind(CHECK_NEXT);
7561     subl(cnt2, stride);
7562     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7563     addptr(str1, 16);
7564     if (ae == StrIntrinsicNode::UL) {
7565       addptr(str2, 8);
7566     } else {
7567       addptr(str2, 16);
7568     }
7569     subl(cnt1, stride);
7570     cmpl(cnt2, stride); // Do not read beyond substring
7571     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7572     // Back-up strings to avoid reading beyond substring.
7573 
7574     if (ae == StrIntrinsicNode::UL) {
7575       lea(str2, Address(str2, cnt2, scale2, -8));
7576       lea(str1, Address(str1, cnt2, scale1, -16));
7577     } else {
7578       lea(str2, Address(str2, cnt2, scale2, -16));
7579       lea(str1, Address(str1, cnt2, scale1, -16));
7580     }
7581     subl(cnt1, cnt2);
7582     movl(cnt2, stride);
7583     addl(cnt1, stride);
7584     bind(CONT_SCAN_SUBSTR);
7585     if (ae == StrIntrinsicNode::UL) {
7586       pmovzxbw(vec, Address(str2, 0));
7587     } else {
7588       movdqu(vec, Address(str2, 0));
7589     }
7590     jmp(SCAN_SUBSTR);
7591 
7592     bind(RET_FOUND_LONG);
7593     movptr(str1, Address(rsp, wordSize));
7594   } // non constant
7595 
7596   bind(RET_FOUND);
7597   // Compute substr offset
7598   subptr(result, str1);
7599   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7600     shrl(result, 1); // index
7601   }
7602   bind(CLEANUP);
7603   pop(rsp); // restore SP
7604 
7605 } // string_indexof
7606 
7607 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7608                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7609   ShortBranchVerifier sbv(this);
7610   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7611 
7612   int stride = 8;
7613 
7614   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7615         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7616         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7617         FOUND_SEQ_CHAR, DONE_LABEL;
7618 
7619   movptr(result, str1);
7620   if (UseAVX >= 2) {
7621     cmpl(cnt1, stride);
7622     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7623     cmpl(cnt1, 2*stride);
7624     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7625     movdl(vec1, ch);
7626     vpbroadcastw(vec1, vec1);
7627     vpxor(vec2, vec2);
7628     movl(tmp, cnt1);
7629     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7630     andl(cnt1,0x0000000F);  //tail count (in chars)
7631 
7632     bind(SCAN_TO_16_CHAR_LOOP);
7633     vmovdqu(vec3, Address(result, 0));
7634     vpcmpeqw(vec3, vec3, vec1, 1);
7635     vptest(vec2, vec3);
7636     jcc(Assembler::carryClear, FOUND_CHAR);
7637     addptr(result, 32);
7638     subl(tmp, 2*stride);
7639     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7640     jmp(SCAN_TO_8_CHAR);
7641     bind(SCAN_TO_8_CHAR_INIT);
7642     movdl(vec1, ch);
7643     pshuflw(vec1, vec1, 0x00);
7644     pshufd(vec1, vec1, 0);
7645     pxor(vec2, vec2);
7646   }
7647   bind(SCAN_TO_8_CHAR);
7648   cmpl(cnt1, stride);
7649   if (UseAVX >= 2) {
7650     jcc(Assembler::less, SCAN_TO_CHAR);
7651   } else {
7652     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7653     movdl(vec1, ch);
7654     pshuflw(vec1, vec1, 0x00);
7655     pshufd(vec1, vec1, 0);
7656     pxor(vec2, vec2);
7657   }
7658   movl(tmp, cnt1);
7659   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7660   andl(cnt1,0x00000007);  //tail count (in chars)
7661 
7662   bind(SCAN_TO_8_CHAR_LOOP);
7663   movdqu(vec3, Address(result, 0));
7664   pcmpeqw(vec3, vec1);
7665   ptest(vec2, vec3);
7666   jcc(Assembler::carryClear, FOUND_CHAR);
7667   addptr(result, 16);
7668   subl(tmp, stride);
7669   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7670   bind(SCAN_TO_CHAR);
7671   testl(cnt1, cnt1);
7672   jcc(Assembler::zero, RET_NOT_FOUND);
7673   bind(SCAN_TO_CHAR_LOOP);
7674   load_unsigned_short(tmp, Address(result, 0));
7675   cmpl(ch, tmp);
7676   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7677   addptr(result, 2);
7678   subl(cnt1, 1);
7679   jccb(Assembler::zero, RET_NOT_FOUND);
7680   jmp(SCAN_TO_CHAR_LOOP);
7681 
7682   bind(RET_NOT_FOUND);
7683   movl(result, -1);
7684   jmpb(DONE_LABEL);
7685 
7686   bind(FOUND_CHAR);
7687   if (UseAVX >= 2) {
7688     vpmovmskb(tmp, vec3);
7689   } else {
7690     pmovmskb(tmp, vec3);
7691   }
7692   bsfl(ch, tmp);
7693   addl(result, ch);
7694 
7695   bind(FOUND_SEQ_CHAR);
7696   subptr(result, str1);
7697   shrl(result, 1);
7698 
7699   bind(DONE_LABEL);
7700 } // string_indexof_char
7701 
7702 // helper function for string_compare
7703 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7704                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7705                                         Address::ScaleFactor scale2, Register index, int ae) {
7706   if (ae == StrIntrinsicNode::LL) {
7707     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7708     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7709   } else if (ae == StrIntrinsicNode::UU) {
7710     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7711     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7712   } else {
7713     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7714     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7715   }
7716 }
7717 
7718 // Compare strings, used for char[] and byte[].
7719 void MacroAssembler::string_compare(Register str1, Register str2,
7720                                     Register cnt1, Register cnt2, Register result,
7721                                     XMMRegister vec1, int ae) {
7722   ShortBranchVerifier sbv(this);
7723   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7724   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7725   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7726   int stride2x2 = 0x40;
7727   Address::ScaleFactor scale = Address::no_scale;
7728   Address::ScaleFactor scale1 = Address::no_scale;
7729   Address::ScaleFactor scale2 = Address::no_scale;
7730 
7731   if (ae != StrIntrinsicNode::LL) {
7732     stride2x2 = 0x20;
7733   }
7734 
7735   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7736     shrl(cnt2, 1);
7737   }
7738   // Compute the minimum of the string lengths and the
7739   // difference of the string lengths (stack).
7740   // Do the conditional move stuff
7741   movl(result, cnt1);
7742   subl(cnt1, cnt2);
7743   push(cnt1);
7744   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7745 
7746   // Is the minimum length zero?
7747   testl(cnt2, cnt2);
7748   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7749   if (ae == StrIntrinsicNode::LL) {
7750     // Load first bytes
7751     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7752     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7753   } else if (ae == StrIntrinsicNode::UU) {
7754     // Load first characters
7755     load_unsigned_short(result, Address(str1, 0));
7756     load_unsigned_short(cnt1, Address(str2, 0));
7757   } else {
7758     load_unsigned_byte(result, Address(str1, 0));
7759     load_unsigned_short(cnt1, Address(str2, 0));
7760   }
7761   subl(result, cnt1);
7762   jcc(Assembler::notZero,  POP_LABEL);
7763 
7764   if (ae == StrIntrinsicNode::UU) {
7765     // Divide length by 2 to get number of chars
7766     shrl(cnt2, 1);
7767   }
7768   cmpl(cnt2, 1);
7769   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7770 
7771   // Check if the strings start at the same location and setup scale and stride
7772   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7773     cmpptr(str1, str2);
7774     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7775     if (ae == StrIntrinsicNode::LL) {
7776       scale = Address::times_1;
7777       stride = 16;
7778     } else {
7779       scale = Address::times_2;
7780       stride = 8;
7781     }
7782   } else {
7783     scale1 = Address::times_1;
7784     scale2 = Address::times_2;
7785     // scale not used
7786     stride = 8;
7787   }
7788 
7789   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7790     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7791     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7792     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7793     Label COMPARE_TAIL_LONG;
7794     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7795 
7796     int pcmpmask = 0x19;
7797     if (ae == StrIntrinsicNode::LL) {
7798       pcmpmask &= ~0x01;
7799     }
7800 
7801     // Setup to compare 16-chars (32-bytes) vectors,
7802     // start from first character again because it has aligned address.
7803     if (ae == StrIntrinsicNode::LL) {
7804       stride2 = 32;
7805     } else {
7806       stride2 = 16;
7807     }
7808     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7809       adr_stride = stride << scale;
7810     } else {
7811       adr_stride1 = 8;  //stride << scale1;
7812       adr_stride2 = 16; //stride << scale2;
7813     }
7814 
7815     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7816     // rax and rdx are used by pcmpestri as elements counters
7817     movl(result, cnt2);
7818     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7819     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7820 
7821     // fast path : compare first 2 8-char vectors.
7822     bind(COMPARE_16_CHARS);
7823     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7824       movdqu(vec1, Address(str1, 0));
7825     } else {
7826       pmovzxbw(vec1, Address(str1, 0));
7827     }
7828     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7829     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7830 
7831     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7832       movdqu(vec1, Address(str1, adr_stride));
7833       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7834     } else {
7835       pmovzxbw(vec1, Address(str1, adr_stride1));
7836       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7837     }
7838     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7839     addl(cnt1, stride);
7840 
7841     // Compare the characters at index in cnt1
7842     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7843     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7844     subl(result, cnt2);
7845     jmp(POP_LABEL);
7846 
7847     // Setup the registers to start vector comparison loop
7848     bind(COMPARE_WIDE_VECTORS);
7849     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7850       lea(str1, Address(str1, result, scale));
7851       lea(str2, Address(str2, result, scale));
7852     } else {
7853       lea(str1, Address(str1, result, scale1));
7854       lea(str2, Address(str2, result, scale2));
7855     }
7856     subl(result, stride2);
7857     subl(cnt2, stride2);
7858     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7859     negptr(result);
7860 
7861     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7862     bind(COMPARE_WIDE_VECTORS_LOOP);
7863 
7864 #ifdef _LP64
7865     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7866       cmpl(cnt2, stride2x2);
7867       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7868       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7869       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7870 
7871       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7872       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7873         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7874         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7875       } else {
7876         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7877         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7878       }
7879       kortestql(k7, k7);
7880       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7881       addptr(result, stride2x2);  // update since we already compared at this addr
7882       subl(cnt2, stride2x2);      // and sub the size too
7883       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7884 
7885       vpxor(vec1, vec1);
7886       jmpb(COMPARE_WIDE_TAIL);
7887     }//if (VM_Version::supports_avx512vlbw())
7888 #endif // _LP64
7889 
7890 
7891     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7892     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7893       vmovdqu(vec1, Address(str1, result, scale));
7894       vpxor(vec1, Address(str2, result, scale));
7895     } else {
7896       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7897       vpxor(vec1, Address(str2, result, scale2));
7898     }
7899     vptest(vec1, vec1);
7900     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7901     addptr(result, stride2);
7902     subl(cnt2, stride2);
7903     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7904     // clean upper bits of YMM registers
7905     vpxor(vec1, vec1);
7906 
7907     // compare wide vectors tail
7908     bind(COMPARE_WIDE_TAIL);
7909     testptr(result, result);
7910     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7911 
7912     movl(result, stride2);
7913     movl(cnt2, result);
7914     negptr(result);
7915     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7916 
7917     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7918     bind(VECTOR_NOT_EQUAL);
7919     // clean upper bits of YMM registers
7920     vpxor(vec1, vec1);
7921     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7922       lea(str1, Address(str1, result, scale));
7923       lea(str2, Address(str2, result, scale));
7924     } else {
7925       lea(str1, Address(str1, result, scale1));
7926       lea(str2, Address(str2, result, scale2));
7927     }
7928     jmp(COMPARE_16_CHARS);
7929 
7930     // Compare tail chars, length between 1 to 15 chars
7931     bind(COMPARE_TAIL_LONG);
7932     movl(cnt2, result);
7933     cmpl(cnt2, stride);
7934     jcc(Assembler::less, COMPARE_SMALL_STR);
7935 
7936     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7937       movdqu(vec1, Address(str1, 0));
7938     } else {
7939       pmovzxbw(vec1, Address(str1, 0));
7940     }
7941     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7942     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7943     subptr(cnt2, stride);
7944     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7945     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7946       lea(str1, Address(str1, result, scale));
7947       lea(str2, Address(str2, result, scale));
7948     } else {
7949       lea(str1, Address(str1, result, scale1));
7950       lea(str2, Address(str2, result, scale2));
7951     }
7952     negptr(cnt2);
7953     jmpb(WHILE_HEAD_LABEL);
7954 
7955     bind(COMPARE_SMALL_STR);
7956   } else if (UseSSE42Intrinsics) {
7957     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7958     int pcmpmask = 0x19;
7959     // Setup to compare 8-char (16-byte) vectors,
7960     // start from first character again because it has aligned address.
7961     movl(result, cnt2);
7962     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7963     if (ae == StrIntrinsicNode::LL) {
7964       pcmpmask &= ~0x01;
7965     }
7966     jcc(Assembler::zero, COMPARE_TAIL);
7967     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7968       lea(str1, Address(str1, result, scale));
7969       lea(str2, Address(str2, result, scale));
7970     } else {
7971       lea(str1, Address(str1, result, scale1));
7972       lea(str2, Address(str2, result, scale2));
7973     }
7974     negptr(result);
7975 
7976     // pcmpestri
7977     //   inputs:
7978     //     vec1- substring
7979     //     rax - negative string length (elements count)
7980     //     mem - scanned string
7981     //     rdx - string length (elements count)
7982     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7983     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7984     //   outputs:
7985     //     rcx - first mismatched element index
7986     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7987 
7988     bind(COMPARE_WIDE_VECTORS);
7989     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7990       movdqu(vec1, Address(str1, result, scale));
7991       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7992     } else {
7993       pmovzxbw(vec1, Address(str1, result, scale1));
7994       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7995     }
7996     // After pcmpestri cnt1(rcx) contains mismatched element index
7997 
7998     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7999     addptr(result, stride);
8000     subptr(cnt2, stride);
8001     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8002 
8003     // compare wide vectors tail
8004     testptr(result, result);
8005     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8006 
8007     movl(cnt2, stride);
8008     movl(result, stride);
8009     negptr(result);
8010     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8011       movdqu(vec1, Address(str1, result, scale));
8012       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8013     } else {
8014       pmovzxbw(vec1, Address(str1, result, scale1));
8015       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8016     }
8017     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8018 
8019     // Mismatched characters in the vectors
8020     bind(VECTOR_NOT_EQUAL);
8021     addptr(cnt1, result);
8022     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8023     subl(result, cnt2);
8024     jmpb(POP_LABEL);
8025 
8026     bind(COMPARE_TAIL); // limit is zero
8027     movl(cnt2, result);
8028     // Fallthru to tail compare
8029   }
8030   // Shift str2 and str1 to the end of the arrays, negate min
8031   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8032     lea(str1, Address(str1, cnt2, scale));
8033     lea(str2, Address(str2, cnt2, scale));
8034   } else {
8035     lea(str1, Address(str1, cnt2, scale1));
8036     lea(str2, Address(str2, cnt2, scale2));
8037   }
8038   decrementl(cnt2);  // first character was compared already
8039   negptr(cnt2);
8040 
8041   // Compare the rest of the elements
8042   bind(WHILE_HEAD_LABEL);
8043   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8044   subl(result, cnt1);
8045   jccb(Assembler::notZero, POP_LABEL);
8046   increment(cnt2);
8047   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8048 
8049   // Strings are equal up to min length.  Return the length difference.
8050   bind(LENGTH_DIFF_LABEL);
8051   pop(result);
8052   if (ae == StrIntrinsicNode::UU) {
8053     // Divide diff by 2 to get number of chars
8054     sarl(result, 1);
8055   }
8056   jmpb(DONE_LABEL);
8057 
8058 #ifdef _LP64
8059   if (VM_Version::supports_avx512vlbw()) {
8060 
8061     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8062 
8063     kmovql(cnt1, k7);
8064     notq(cnt1);
8065     bsfq(cnt2, cnt1);
8066     if (ae != StrIntrinsicNode::LL) {
8067       // Divide diff by 2 to get number of chars
8068       sarl(cnt2, 1);
8069     }
8070     addq(result, cnt2);
8071     if (ae == StrIntrinsicNode::LL) {
8072       load_unsigned_byte(cnt1, Address(str2, result));
8073       load_unsigned_byte(result, Address(str1, result));
8074     } else if (ae == StrIntrinsicNode::UU) {
8075       load_unsigned_short(cnt1, Address(str2, result, scale));
8076       load_unsigned_short(result, Address(str1, result, scale));
8077     } else {
8078       load_unsigned_short(cnt1, Address(str2, result, scale2));
8079       load_unsigned_byte(result, Address(str1, result, scale1));
8080     }
8081     subl(result, cnt1);
8082     jmpb(POP_LABEL);
8083   }//if (VM_Version::supports_avx512vlbw())
8084 #endif // _LP64
8085 
8086   // Discard the stored length difference
8087   bind(POP_LABEL);
8088   pop(cnt1);
8089 
8090   // That's it
8091   bind(DONE_LABEL);
8092   if(ae == StrIntrinsicNode::UL) {
8093     negl(result);
8094   }
8095 
8096 }
8097 
8098 // Search for Non-ASCII character (Negative byte value) in a byte array,
8099 // return true if it has any and false otherwise.
8100 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8101 //   @HotSpotIntrinsicCandidate
8102 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8103 //     for (int i = off; i < off + len; i++) {
8104 //       if (ba[i] < 0) {
8105 //         return true;
8106 //       }
8107 //     }
8108 //     return false;
8109 //   }
8110 void MacroAssembler::has_negatives(Register ary1, Register len,
8111   Register result, Register tmp1,
8112   XMMRegister vec1, XMMRegister vec2) {
8113   // rsi: byte array
8114   // rcx: len
8115   // rax: result
8116   ShortBranchVerifier sbv(this);
8117   assert_different_registers(ary1, len, result, tmp1);
8118   assert_different_registers(vec1, vec2);
8119   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8120 
8121   // len == 0
8122   testl(len, len);
8123   jcc(Assembler::zero, FALSE_LABEL);
8124 
8125   if ((UseAVX > 2) && // AVX512
8126     VM_Version::supports_avx512vlbw() &&
8127     VM_Version::supports_bmi2()) {
8128 
8129     set_vector_masking();  // opening of the stub context for programming mask registers
8130 
8131     Label test_64_loop, test_tail;
8132     Register tmp3_aliased = len;
8133 
8134     movl(tmp1, len);
8135     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8136 
8137     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8138     andl(len, ~(64 - 1));    // vector count (in chars)
8139     jccb(Assembler::zero, test_tail);
8140 
8141     lea(ary1, Address(ary1, len, Address::times_1));
8142     negptr(len);
8143 
8144     bind(test_64_loop);
8145     // Check whether our 64 elements of size byte contain negatives
8146     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8147     kortestql(k2, k2);
8148     jcc(Assembler::notZero, TRUE_LABEL);
8149 
8150     addptr(len, 64);
8151     jccb(Assembler::notZero, test_64_loop);
8152 
8153 
8154     bind(test_tail);
8155     // bail out when there is nothing to be done
8156     testl(tmp1, -1);
8157     jcc(Assembler::zero, FALSE_LABEL);
8158 
8159     // Save k1
8160     kmovql(k3, k1);
8161 
8162     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8163 #ifdef _LP64
8164     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8165     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8166     notq(tmp3_aliased);
8167     kmovql(k1, tmp3_aliased);
8168 #else
8169     Label k_init;
8170     jmp(k_init);
8171 
8172     // We could not read 64-bits from a general purpose register thus we move
8173     // data required to compose 64 1's to the instruction stream
8174     // We emit 64 byte wide series of elements from 0..63 which later on would
8175     // be used as a compare targets with tail count contained in tmp1 register.
8176     // Result would be a k1 register having tmp1 consecutive number or 1
8177     // counting from least significant bit.
8178     address tmp = pc();
8179     emit_int64(0x0706050403020100);
8180     emit_int64(0x0F0E0D0C0B0A0908);
8181     emit_int64(0x1716151413121110);
8182     emit_int64(0x1F1E1D1C1B1A1918);
8183     emit_int64(0x2726252423222120);
8184     emit_int64(0x2F2E2D2C2B2A2928);
8185     emit_int64(0x3736353433323130);
8186     emit_int64(0x3F3E3D3C3B3A3938);
8187 
8188     bind(k_init);
8189     lea(len, InternalAddress(tmp));
8190     // create mask to test for negative byte inside a vector
8191     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8192     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8193 
8194 #endif
8195     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8196     ktestq(k2, k1);
8197     // Restore k1
8198     kmovql(k1, k3);
8199     jcc(Assembler::notZero, TRUE_LABEL);
8200 
8201     jmp(FALSE_LABEL);
8202 
8203     clear_vector_masking();   // closing of the stub context for programming mask registers
8204   } else {
8205     movl(result, len); // copy
8206 
8207     if (UseAVX == 2 && UseSSE >= 2) {
8208       // With AVX2, use 32-byte vector compare
8209       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8210 
8211       // Compare 32-byte vectors
8212       andl(result, 0x0000001f);  //   tail count (in bytes)
8213       andl(len, 0xffffffe0);   // vector count (in bytes)
8214       jccb(Assembler::zero, COMPARE_TAIL);
8215 
8216       lea(ary1, Address(ary1, len, Address::times_1));
8217       negptr(len);
8218 
8219       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8220       movdl(vec2, tmp1);
8221       vpbroadcastd(vec2, vec2);
8222 
8223       bind(COMPARE_WIDE_VECTORS);
8224       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8225       vptest(vec1, vec2);
8226       jccb(Assembler::notZero, TRUE_LABEL);
8227       addptr(len, 32);
8228       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8229 
8230       testl(result, result);
8231       jccb(Assembler::zero, FALSE_LABEL);
8232 
8233       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8234       vptest(vec1, vec2);
8235       jccb(Assembler::notZero, TRUE_LABEL);
8236       jmpb(FALSE_LABEL);
8237 
8238       bind(COMPARE_TAIL); // len is zero
8239       movl(len, result);
8240       // Fallthru to tail compare
8241     } else if (UseSSE42Intrinsics) {
8242       // With SSE4.2, use double quad vector compare
8243       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8244 
8245       // Compare 16-byte vectors
8246       andl(result, 0x0000000f);  //   tail count (in bytes)
8247       andl(len, 0xfffffff0);   // vector count (in bytes)
8248       jccb(Assembler::zero, COMPARE_TAIL);
8249 
8250       lea(ary1, Address(ary1, len, Address::times_1));
8251       negptr(len);
8252 
8253       movl(tmp1, 0x80808080);
8254       movdl(vec2, tmp1);
8255       pshufd(vec2, vec2, 0);
8256 
8257       bind(COMPARE_WIDE_VECTORS);
8258       movdqu(vec1, Address(ary1, len, Address::times_1));
8259       ptest(vec1, vec2);
8260       jccb(Assembler::notZero, TRUE_LABEL);
8261       addptr(len, 16);
8262       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8263 
8264       testl(result, result);
8265       jccb(Assembler::zero, FALSE_LABEL);
8266 
8267       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8268       ptest(vec1, vec2);
8269       jccb(Assembler::notZero, TRUE_LABEL);
8270       jmpb(FALSE_LABEL);
8271 
8272       bind(COMPARE_TAIL); // len is zero
8273       movl(len, result);
8274       // Fallthru to tail compare
8275     }
8276   }
8277   // Compare 4-byte vectors
8278   andl(len, 0xfffffffc); // vector count (in bytes)
8279   jccb(Assembler::zero, COMPARE_CHAR);
8280 
8281   lea(ary1, Address(ary1, len, Address::times_1));
8282   negptr(len);
8283 
8284   bind(COMPARE_VECTORS);
8285   movl(tmp1, Address(ary1, len, Address::times_1));
8286   andl(tmp1, 0x80808080);
8287   jccb(Assembler::notZero, TRUE_LABEL);
8288   addptr(len, 4);
8289   jcc(Assembler::notZero, COMPARE_VECTORS);
8290 
8291   // Compare trailing char (final 2 bytes), if any
8292   bind(COMPARE_CHAR);
8293   testl(result, 0x2);   // tail  char
8294   jccb(Assembler::zero, COMPARE_BYTE);
8295   load_unsigned_short(tmp1, Address(ary1, 0));
8296   andl(tmp1, 0x00008080);
8297   jccb(Assembler::notZero, TRUE_LABEL);
8298   subptr(result, 2);
8299   lea(ary1, Address(ary1, 2));
8300 
8301   bind(COMPARE_BYTE);
8302   testl(result, 0x1);   // tail  byte
8303   jccb(Assembler::zero, FALSE_LABEL);
8304   load_unsigned_byte(tmp1, Address(ary1, 0));
8305   andl(tmp1, 0x00000080);
8306   jccb(Assembler::notEqual, TRUE_LABEL);
8307   jmpb(FALSE_LABEL);
8308 
8309   bind(TRUE_LABEL);
8310   movl(result, 1);   // return true
8311   jmpb(DONE);
8312 
8313   bind(FALSE_LABEL);
8314   xorl(result, result); // return false
8315 
8316   // That's it
8317   bind(DONE);
8318   if (UseAVX >= 2 && UseSSE >= 2) {
8319     // clean upper bits of YMM registers
8320     vpxor(vec1, vec1);
8321     vpxor(vec2, vec2);
8322   }
8323 }
8324 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8325 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8326                                    Register limit, Register result, Register chr,
8327                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8328   ShortBranchVerifier sbv(this);
8329   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8330 
8331   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8332   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8333 
8334   if (is_array_equ) {
8335     // Check the input args
8336     cmpptr(ary1, ary2);
8337     jcc(Assembler::equal, TRUE_LABEL);
8338 
8339     // Need additional checks for arrays_equals.
8340     testptr(ary1, ary1);
8341     jcc(Assembler::zero, FALSE_LABEL);
8342     testptr(ary2, ary2);
8343     jcc(Assembler::zero, FALSE_LABEL);
8344 
8345     // Check the lengths
8346     movl(limit, Address(ary1, length_offset));
8347     cmpl(limit, Address(ary2, length_offset));
8348     jcc(Assembler::notEqual, FALSE_LABEL);
8349   }
8350 
8351   // count == 0
8352   testl(limit, limit);
8353   jcc(Assembler::zero, TRUE_LABEL);
8354 
8355   if (is_array_equ) {
8356     // Load array address
8357     lea(ary1, Address(ary1, base_offset));
8358     lea(ary2, Address(ary2, base_offset));
8359   }
8360 
8361   if (is_array_equ && is_char) {
8362     // arrays_equals when used for char[].
8363     shll(limit, 1);      // byte count != 0
8364   }
8365   movl(result, limit); // copy
8366 
8367   if (UseAVX >= 2) {
8368     // With AVX2, use 32-byte vector compare
8369     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8370 
8371     // Compare 32-byte vectors
8372     andl(result, 0x0000001f);  //   tail count (in bytes)
8373     andl(limit, 0xffffffe0);   // vector count (in bytes)
8374     jcc(Assembler::zero, COMPARE_TAIL);
8375 
8376     lea(ary1, Address(ary1, limit, Address::times_1));
8377     lea(ary2, Address(ary2, limit, Address::times_1));
8378     negptr(limit);
8379 
8380     bind(COMPARE_WIDE_VECTORS);
8381 
8382 #ifdef _LP64
8383     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8384       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8385 
8386       cmpl(limit, -64);
8387       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8388 
8389       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8390 
8391       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8392       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8393       kortestql(k7, k7);
8394       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8395       addptr(limit, 64);  // update since we already compared at this addr
8396       cmpl(limit, -64);
8397       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8398 
8399       // At this point we may still need to compare -limit+result bytes.
8400       // We could execute the next two instruction and just continue via non-wide path:
8401       //  cmpl(limit, 0);
8402       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8403       // But since we stopped at the points ary{1,2}+limit which are
8404       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8405       // (|limit| <= 32 and result < 32),
8406       // we may just compare the last 64 bytes.
8407       //
8408       addptr(result, -64);   // it is safe, bc we just came from this area
8409       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8410       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8411       kortestql(k7, k7);
8412       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8413 
8414       jmp(TRUE_LABEL);
8415 
8416       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8417 
8418     }//if (VM_Version::supports_avx512vlbw())
8419 #endif //_LP64
8420 
8421     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8422     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8423     vpxor(vec1, vec2);
8424 
8425     vptest(vec1, vec1);
8426     jcc(Assembler::notZero, FALSE_LABEL);
8427     addptr(limit, 32);
8428     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8429 
8430     testl(result, result);
8431     jcc(Assembler::zero, TRUE_LABEL);
8432 
8433     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8434     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8435     vpxor(vec1, vec2);
8436 
8437     vptest(vec1, vec1);
8438     jccb(Assembler::notZero, FALSE_LABEL);
8439     jmpb(TRUE_LABEL);
8440 
8441     bind(COMPARE_TAIL); // limit is zero
8442     movl(limit, result);
8443     // Fallthru to tail compare
8444   } else if (UseSSE42Intrinsics) {
8445     // With SSE4.2, use double quad vector compare
8446     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8447 
8448     // Compare 16-byte vectors
8449     andl(result, 0x0000000f);  //   tail count (in bytes)
8450     andl(limit, 0xfffffff0);   // vector count (in bytes)
8451     jcc(Assembler::zero, COMPARE_TAIL);
8452 
8453     lea(ary1, Address(ary1, limit, Address::times_1));
8454     lea(ary2, Address(ary2, limit, Address::times_1));
8455     negptr(limit);
8456 
8457     bind(COMPARE_WIDE_VECTORS);
8458     movdqu(vec1, Address(ary1, limit, Address::times_1));
8459     movdqu(vec2, Address(ary2, limit, Address::times_1));
8460     pxor(vec1, vec2);
8461 
8462     ptest(vec1, vec1);
8463     jcc(Assembler::notZero, FALSE_LABEL);
8464     addptr(limit, 16);
8465     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8466 
8467     testl(result, result);
8468     jcc(Assembler::zero, TRUE_LABEL);
8469 
8470     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8471     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8472     pxor(vec1, vec2);
8473 
8474     ptest(vec1, vec1);
8475     jccb(Assembler::notZero, FALSE_LABEL);
8476     jmpb(TRUE_LABEL);
8477 
8478     bind(COMPARE_TAIL); // limit is zero
8479     movl(limit, result);
8480     // Fallthru to tail compare
8481   }
8482 
8483   // Compare 4-byte vectors
8484   andl(limit, 0xfffffffc); // vector count (in bytes)
8485   jccb(Assembler::zero, COMPARE_CHAR);
8486 
8487   lea(ary1, Address(ary1, limit, Address::times_1));
8488   lea(ary2, Address(ary2, limit, Address::times_1));
8489   negptr(limit);
8490 
8491   bind(COMPARE_VECTORS);
8492   movl(chr, Address(ary1, limit, Address::times_1));
8493   cmpl(chr, Address(ary2, limit, Address::times_1));
8494   jccb(Assembler::notEqual, FALSE_LABEL);
8495   addptr(limit, 4);
8496   jcc(Assembler::notZero, COMPARE_VECTORS);
8497 
8498   // Compare trailing char (final 2 bytes), if any
8499   bind(COMPARE_CHAR);
8500   testl(result, 0x2);   // tail  char
8501   jccb(Assembler::zero, COMPARE_BYTE);
8502   load_unsigned_short(chr, Address(ary1, 0));
8503   load_unsigned_short(limit, Address(ary2, 0));
8504   cmpl(chr, limit);
8505   jccb(Assembler::notEqual, FALSE_LABEL);
8506 
8507   if (is_array_equ && is_char) {
8508     bind(COMPARE_BYTE);
8509   } else {
8510     lea(ary1, Address(ary1, 2));
8511     lea(ary2, Address(ary2, 2));
8512 
8513     bind(COMPARE_BYTE);
8514     testl(result, 0x1);   // tail  byte
8515     jccb(Assembler::zero, TRUE_LABEL);
8516     load_unsigned_byte(chr, Address(ary1, 0));
8517     load_unsigned_byte(limit, Address(ary2, 0));
8518     cmpl(chr, limit);
8519     jccb(Assembler::notEqual, FALSE_LABEL);
8520   }
8521   bind(TRUE_LABEL);
8522   movl(result, 1);   // return true
8523   jmpb(DONE);
8524 
8525   bind(FALSE_LABEL);
8526   xorl(result, result); // return false
8527 
8528   // That's it
8529   bind(DONE);
8530   if (UseAVX >= 2) {
8531     // clean upper bits of YMM registers
8532     vpxor(vec1, vec1);
8533     vpxor(vec2, vec2);
8534   }
8535 }
8536 
8537 #endif
8538 
8539 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8540                                    Register to, Register value, Register count,
8541                                    Register rtmp, XMMRegister xtmp) {
8542   ShortBranchVerifier sbv(this);
8543   assert_different_registers(to, value, count, rtmp);
8544   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8545   Label L_fill_2_bytes, L_fill_4_bytes;
8546 
8547   int shift = -1;
8548   switch (t) {
8549     case T_BYTE:
8550       shift = 2;
8551       break;
8552     case T_SHORT:
8553       shift = 1;
8554       break;
8555     case T_INT:
8556       shift = 0;
8557       break;
8558     default: ShouldNotReachHere();
8559   }
8560 
8561   if (t == T_BYTE) {
8562     andl(value, 0xff);
8563     movl(rtmp, value);
8564     shll(rtmp, 8);
8565     orl(value, rtmp);
8566   }
8567   if (t == T_SHORT) {
8568     andl(value, 0xffff);
8569   }
8570   if (t == T_BYTE || t == T_SHORT) {
8571     movl(rtmp, value);
8572     shll(rtmp, 16);
8573     orl(value, rtmp);
8574   }
8575 
8576   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8577   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8578   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8579     // align source address at 4 bytes address boundary
8580     if (t == T_BYTE) {
8581       // One byte misalignment happens only for byte arrays
8582       testptr(to, 1);
8583       jccb(Assembler::zero, L_skip_align1);
8584       movb(Address(to, 0), value);
8585       increment(to);
8586       decrement(count);
8587       BIND(L_skip_align1);
8588     }
8589     // Two bytes misalignment happens only for byte and short (char) arrays
8590     testptr(to, 2);
8591     jccb(Assembler::zero, L_skip_align2);
8592     movw(Address(to, 0), value);
8593     addptr(to, 2);
8594     subl(count, 1<<(shift-1));
8595     BIND(L_skip_align2);
8596   }
8597   if (UseSSE < 2) {
8598     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8599     // Fill 32-byte chunks
8600     subl(count, 8 << shift);
8601     jcc(Assembler::less, L_check_fill_8_bytes);
8602     align(16);
8603 
8604     BIND(L_fill_32_bytes_loop);
8605 
8606     for (int i = 0; i < 32; i += 4) {
8607       movl(Address(to, i), value);
8608     }
8609 
8610     addptr(to, 32);
8611     subl(count, 8 << shift);
8612     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8613     BIND(L_check_fill_8_bytes);
8614     addl(count, 8 << shift);
8615     jccb(Assembler::zero, L_exit);
8616     jmpb(L_fill_8_bytes);
8617 
8618     //
8619     // length is too short, just fill qwords
8620     //
8621     BIND(L_fill_8_bytes_loop);
8622     movl(Address(to, 0), value);
8623     movl(Address(to, 4), value);
8624     addptr(to, 8);
8625     BIND(L_fill_8_bytes);
8626     subl(count, 1 << (shift + 1));
8627     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8628     // fall through to fill 4 bytes
8629   } else {
8630     Label L_fill_32_bytes;
8631     if (!UseUnalignedLoadStores) {
8632       // align to 8 bytes, we know we are 4 byte aligned to start
8633       testptr(to, 4);
8634       jccb(Assembler::zero, L_fill_32_bytes);
8635       movl(Address(to, 0), value);
8636       addptr(to, 4);
8637       subl(count, 1<<shift);
8638     }
8639     BIND(L_fill_32_bytes);
8640     {
8641       assert( UseSSE >= 2, "supported cpu only" );
8642       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8643       if (UseAVX > 2) {
8644         movl(rtmp, 0xffff);
8645         kmovwl(k1, rtmp);
8646       }
8647       movdl(xtmp, value);
8648       if (UseAVX > 2 && UseUnalignedLoadStores) {
8649         // Fill 64-byte chunks
8650         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8651         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8652 
8653         subl(count, 16 << shift);
8654         jcc(Assembler::less, L_check_fill_32_bytes);
8655         align(16);
8656 
8657         BIND(L_fill_64_bytes_loop);
8658         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8659         addptr(to, 64);
8660         subl(count, 16 << shift);
8661         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8662 
8663         BIND(L_check_fill_32_bytes);
8664         addl(count, 8 << shift);
8665         jccb(Assembler::less, L_check_fill_8_bytes);
8666         vmovdqu(Address(to, 0), xtmp);
8667         addptr(to, 32);
8668         subl(count, 8 << shift);
8669 
8670         BIND(L_check_fill_8_bytes);
8671       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8672         // Fill 64-byte chunks
8673         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8674         vpbroadcastd(xtmp, xtmp);
8675 
8676         subl(count, 16 << shift);
8677         jcc(Assembler::less, L_check_fill_32_bytes);
8678         align(16);
8679 
8680         BIND(L_fill_64_bytes_loop);
8681         vmovdqu(Address(to, 0), xtmp);
8682         vmovdqu(Address(to, 32), xtmp);
8683         addptr(to, 64);
8684         subl(count, 16 << shift);
8685         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8686 
8687         BIND(L_check_fill_32_bytes);
8688         addl(count, 8 << shift);
8689         jccb(Assembler::less, L_check_fill_8_bytes);
8690         vmovdqu(Address(to, 0), xtmp);
8691         addptr(to, 32);
8692         subl(count, 8 << shift);
8693 
8694         BIND(L_check_fill_8_bytes);
8695         // clean upper bits of YMM registers
8696         movdl(xtmp, value);
8697         pshufd(xtmp, xtmp, 0);
8698       } else {
8699         // Fill 32-byte chunks
8700         pshufd(xtmp, xtmp, 0);
8701 
8702         subl(count, 8 << shift);
8703         jcc(Assembler::less, L_check_fill_8_bytes);
8704         align(16);
8705 
8706         BIND(L_fill_32_bytes_loop);
8707 
8708         if (UseUnalignedLoadStores) {
8709           movdqu(Address(to, 0), xtmp);
8710           movdqu(Address(to, 16), xtmp);
8711         } else {
8712           movq(Address(to, 0), xtmp);
8713           movq(Address(to, 8), xtmp);
8714           movq(Address(to, 16), xtmp);
8715           movq(Address(to, 24), xtmp);
8716         }
8717 
8718         addptr(to, 32);
8719         subl(count, 8 << shift);
8720         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8721 
8722         BIND(L_check_fill_8_bytes);
8723       }
8724       addl(count, 8 << shift);
8725       jccb(Assembler::zero, L_exit);
8726       jmpb(L_fill_8_bytes);
8727 
8728       //
8729       // length is too short, just fill qwords
8730       //
8731       BIND(L_fill_8_bytes_loop);
8732       movq(Address(to, 0), xtmp);
8733       addptr(to, 8);
8734       BIND(L_fill_8_bytes);
8735       subl(count, 1 << (shift + 1));
8736       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8737     }
8738   }
8739   // fill trailing 4 bytes
8740   BIND(L_fill_4_bytes);
8741   testl(count, 1<<shift);
8742   jccb(Assembler::zero, L_fill_2_bytes);
8743   movl(Address(to, 0), value);
8744   if (t == T_BYTE || t == T_SHORT) {
8745     addptr(to, 4);
8746     BIND(L_fill_2_bytes);
8747     // fill trailing 2 bytes
8748     testl(count, 1<<(shift-1));
8749     jccb(Assembler::zero, L_fill_byte);
8750     movw(Address(to, 0), value);
8751     if (t == T_BYTE) {
8752       addptr(to, 2);
8753       BIND(L_fill_byte);
8754       // fill trailing byte
8755       testl(count, 1);
8756       jccb(Assembler::zero, L_exit);
8757       movb(Address(to, 0), value);
8758     } else {
8759       BIND(L_fill_byte);
8760     }
8761   } else {
8762     BIND(L_fill_2_bytes);
8763   }
8764   BIND(L_exit);
8765 }
8766 
8767 // encode char[] to byte[] in ISO_8859_1
8768    //@HotSpotIntrinsicCandidate
8769    //private static int implEncodeISOArray(byte[] sa, int sp,
8770    //byte[] da, int dp, int len) {
8771    //  int i = 0;
8772    //  for (; i < len; i++) {
8773    //    char c = StringUTF16.getChar(sa, sp++);
8774    //    if (c > '\u00FF')
8775    //      break;
8776    //    da[dp++] = (byte)c;
8777    //  }
8778    //  return i;
8779    //}
8780 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8781   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8782   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8783   Register tmp5, Register result) {
8784 
8785   // rsi: src
8786   // rdi: dst
8787   // rdx: len
8788   // rcx: tmp5
8789   // rax: result
8790   ShortBranchVerifier sbv(this);
8791   assert_different_registers(src, dst, len, tmp5, result);
8792   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8793 
8794   // set result
8795   xorl(result, result);
8796   // check for zero length
8797   testl(len, len);
8798   jcc(Assembler::zero, L_done);
8799 
8800   movl(result, len);
8801 
8802   // Setup pointers
8803   lea(src, Address(src, len, Address::times_2)); // char[]
8804   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8805   negptr(len);
8806 
8807   if (UseSSE42Intrinsics || UseAVX >= 2) {
8808     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8809     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8810 
8811     if (UseAVX >= 2) {
8812       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8813       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8814       movdl(tmp1Reg, tmp5);
8815       vpbroadcastd(tmp1Reg, tmp1Reg);
8816       jmp(L_chars_32_check);
8817 
8818       bind(L_copy_32_chars);
8819       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8820       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8821       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8822       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8823       jccb(Assembler::notZero, L_copy_32_chars_exit);
8824       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8825       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8826       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8827 
8828       bind(L_chars_32_check);
8829       addptr(len, 32);
8830       jcc(Assembler::lessEqual, L_copy_32_chars);
8831 
8832       bind(L_copy_32_chars_exit);
8833       subptr(len, 16);
8834       jccb(Assembler::greater, L_copy_16_chars_exit);
8835 
8836     } else if (UseSSE42Intrinsics) {
8837       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8838       movdl(tmp1Reg, tmp5);
8839       pshufd(tmp1Reg, tmp1Reg, 0);
8840       jmpb(L_chars_16_check);
8841     }
8842 
8843     bind(L_copy_16_chars);
8844     if (UseAVX >= 2) {
8845       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8846       vptest(tmp2Reg, tmp1Reg);
8847       jcc(Assembler::notZero, L_copy_16_chars_exit);
8848       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8849       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8850     } else {
8851       if (UseAVX > 0) {
8852         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8853         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8854         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8855       } else {
8856         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8857         por(tmp2Reg, tmp3Reg);
8858         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8859         por(tmp2Reg, tmp4Reg);
8860       }
8861       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8862       jccb(Assembler::notZero, L_copy_16_chars_exit);
8863       packuswb(tmp3Reg, tmp4Reg);
8864     }
8865     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8866 
8867     bind(L_chars_16_check);
8868     addptr(len, 16);
8869     jcc(Assembler::lessEqual, L_copy_16_chars);
8870 
8871     bind(L_copy_16_chars_exit);
8872     if (UseAVX >= 2) {
8873       // clean upper bits of YMM registers
8874       vpxor(tmp2Reg, tmp2Reg);
8875       vpxor(tmp3Reg, tmp3Reg);
8876       vpxor(tmp4Reg, tmp4Reg);
8877       movdl(tmp1Reg, tmp5);
8878       pshufd(tmp1Reg, tmp1Reg, 0);
8879     }
8880     subptr(len, 8);
8881     jccb(Assembler::greater, L_copy_8_chars_exit);
8882 
8883     bind(L_copy_8_chars);
8884     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8885     ptest(tmp3Reg, tmp1Reg);
8886     jccb(Assembler::notZero, L_copy_8_chars_exit);
8887     packuswb(tmp3Reg, tmp1Reg);
8888     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8889     addptr(len, 8);
8890     jccb(Assembler::lessEqual, L_copy_8_chars);
8891 
8892     bind(L_copy_8_chars_exit);
8893     subptr(len, 8);
8894     jccb(Assembler::zero, L_done);
8895   }
8896 
8897   bind(L_copy_1_char);
8898   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8899   testl(tmp5, 0xff00);      // check if Unicode char
8900   jccb(Assembler::notZero, L_copy_1_char_exit);
8901   movb(Address(dst, len, Address::times_1, 0), tmp5);
8902   addptr(len, 1);
8903   jccb(Assembler::less, L_copy_1_char);
8904 
8905   bind(L_copy_1_char_exit);
8906   addptr(result, len); // len is negative count of not processed elements
8907 
8908   bind(L_done);
8909 }
8910 
8911 #ifdef _LP64
8912 /**
8913  * Helper for multiply_to_len().
8914  */
8915 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8916   addq(dest_lo, src1);
8917   adcq(dest_hi, 0);
8918   addq(dest_lo, src2);
8919   adcq(dest_hi, 0);
8920 }
8921 
8922 /**
8923  * Multiply 64 bit by 64 bit first loop.
8924  */
8925 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8926                                            Register y, Register y_idx, Register z,
8927                                            Register carry, Register product,
8928                                            Register idx, Register kdx) {
8929   //
8930   //  jlong carry, x[], y[], z[];
8931   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8932   //    huge_128 product = y[idx] * x[xstart] + carry;
8933   //    z[kdx] = (jlong)product;
8934   //    carry  = (jlong)(product >>> 64);
8935   //  }
8936   //  z[xstart] = carry;
8937   //
8938 
8939   Label L_first_loop, L_first_loop_exit;
8940   Label L_one_x, L_one_y, L_multiply;
8941 
8942   decrementl(xstart);
8943   jcc(Assembler::negative, L_one_x);
8944 
8945   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8946   rorq(x_xstart, 32); // convert big-endian to little-endian
8947 
8948   bind(L_first_loop);
8949   decrementl(idx);
8950   jcc(Assembler::negative, L_first_loop_exit);
8951   decrementl(idx);
8952   jcc(Assembler::negative, L_one_y);
8953   movq(y_idx, Address(y, idx, Address::times_4,  0));
8954   rorq(y_idx, 32); // convert big-endian to little-endian
8955   bind(L_multiply);
8956   movq(product, x_xstart);
8957   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8958   addq(product, carry);
8959   adcq(rdx, 0);
8960   subl(kdx, 2);
8961   movl(Address(z, kdx, Address::times_4,  4), product);
8962   shrq(product, 32);
8963   movl(Address(z, kdx, Address::times_4,  0), product);
8964   movq(carry, rdx);
8965   jmp(L_first_loop);
8966 
8967   bind(L_one_y);
8968   movl(y_idx, Address(y,  0));
8969   jmp(L_multiply);
8970 
8971   bind(L_one_x);
8972   movl(x_xstart, Address(x,  0));
8973   jmp(L_first_loop);
8974 
8975   bind(L_first_loop_exit);
8976 }
8977 
8978 /**
8979  * Multiply 64 bit by 64 bit and add 128 bit.
8980  */
8981 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8982                                             Register yz_idx, Register idx,
8983                                             Register carry, Register product, int offset) {
8984   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8985   //     z[kdx] = (jlong)product;
8986 
8987   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8988   rorq(yz_idx, 32); // convert big-endian to little-endian
8989   movq(product, x_xstart);
8990   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8991   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8992   rorq(yz_idx, 32); // convert big-endian to little-endian
8993 
8994   add2_with_carry(rdx, product, carry, yz_idx);
8995 
8996   movl(Address(z, idx, Address::times_4,  offset+4), product);
8997   shrq(product, 32);
8998   movl(Address(z, idx, Address::times_4,  offset), product);
8999 
9000 }
9001 
9002 /**
9003  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9004  */
9005 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9006                                              Register yz_idx, Register idx, Register jdx,
9007                                              Register carry, Register product,
9008                                              Register carry2) {
9009   //   jlong carry, x[], y[], z[];
9010   //   int kdx = ystart+1;
9011   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9012   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9013   //     z[kdx+idx+1] = (jlong)product;
9014   //     jlong carry2  = (jlong)(product >>> 64);
9015   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9016   //     z[kdx+idx] = (jlong)product;
9017   //     carry  = (jlong)(product >>> 64);
9018   //   }
9019   //   idx += 2;
9020   //   if (idx > 0) {
9021   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9022   //     z[kdx+idx] = (jlong)product;
9023   //     carry  = (jlong)(product >>> 64);
9024   //   }
9025   //
9026 
9027   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9028 
9029   movl(jdx, idx);
9030   andl(jdx, 0xFFFFFFFC);
9031   shrl(jdx, 2);
9032 
9033   bind(L_third_loop);
9034   subl(jdx, 1);
9035   jcc(Assembler::negative, L_third_loop_exit);
9036   subl(idx, 4);
9037 
9038   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9039   movq(carry2, rdx);
9040 
9041   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9042   movq(carry, rdx);
9043   jmp(L_third_loop);
9044 
9045   bind (L_third_loop_exit);
9046 
9047   andl (idx, 0x3);
9048   jcc(Assembler::zero, L_post_third_loop_done);
9049 
9050   Label L_check_1;
9051   subl(idx, 2);
9052   jcc(Assembler::negative, L_check_1);
9053 
9054   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9055   movq(carry, rdx);
9056 
9057   bind (L_check_1);
9058   addl (idx, 0x2);
9059   andl (idx, 0x1);
9060   subl(idx, 1);
9061   jcc(Assembler::negative, L_post_third_loop_done);
9062 
9063   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9064   movq(product, x_xstart);
9065   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9066   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9067 
9068   add2_with_carry(rdx, product, yz_idx, carry);
9069 
9070   movl(Address(z, idx, Address::times_4,  0), product);
9071   shrq(product, 32);
9072 
9073   shlq(rdx, 32);
9074   orq(product, rdx);
9075   movq(carry, product);
9076 
9077   bind(L_post_third_loop_done);
9078 }
9079 
9080 /**
9081  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9082  *
9083  */
9084 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9085                                                   Register carry, Register carry2,
9086                                                   Register idx, Register jdx,
9087                                                   Register yz_idx1, Register yz_idx2,
9088                                                   Register tmp, Register tmp3, Register tmp4) {
9089   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9090 
9091   //   jlong carry, x[], y[], z[];
9092   //   int kdx = ystart+1;
9093   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9094   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9095   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9096   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9097   //     carry  = (jlong)(tmp4 >>> 64);
9098   //     z[kdx+idx+1] = (jlong)tmp3;
9099   //     z[kdx+idx] = (jlong)tmp4;
9100   //   }
9101   //   idx += 2;
9102   //   if (idx > 0) {
9103   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9104   //     z[kdx+idx] = (jlong)yz_idx1;
9105   //     carry  = (jlong)(yz_idx1 >>> 64);
9106   //   }
9107   //
9108 
9109   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9110 
9111   movl(jdx, idx);
9112   andl(jdx, 0xFFFFFFFC);
9113   shrl(jdx, 2);
9114 
9115   bind(L_third_loop);
9116   subl(jdx, 1);
9117   jcc(Assembler::negative, L_third_loop_exit);
9118   subl(idx, 4);
9119 
9120   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9121   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9122   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9123   rorxq(yz_idx2, yz_idx2, 32);
9124 
9125   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9126   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9127 
9128   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9129   rorxq(yz_idx1, yz_idx1, 32);
9130   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9131   rorxq(yz_idx2, yz_idx2, 32);
9132 
9133   if (VM_Version::supports_adx()) {
9134     adcxq(tmp3, carry);
9135     adoxq(tmp3, yz_idx1);
9136 
9137     adcxq(tmp4, tmp);
9138     adoxq(tmp4, yz_idx2);
9139 
9140     movl(carry, 0); // does not affect flags
9141     adcxq(carry2, carry);
9142     adoxq(carry2, carry);
9143   } else {
9144     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9145     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9146   }
9147   movq(carry, carry2);
9148 
9149   movl(Address(z, idx, Address::times_4, 12), tmp3);
9150   shrq(tmp3, 32);
9151   movl(Address(z, idx, Address::times_4,  8), tmp3);
9152 
9153   movl(Address(z, idx, Address::times_4,  4), tmp4);
9154   shrq(tmp4, 32);
9155   movl(Address(z, idx, Address::times_4,  0), tmp4);
9156 
9157   jmp(L_third_loop);
9158 
9159   bind (L_third_loop_exit);
9160 
9161   andl (idx, 0x3);
9162   jcc(Assembler::zero, L_post_third_loop_done);
9163 
9164   Label L_check_1;
9165   subl(idx, 2);
9166   jcc(Assembler::negative, L_check_1);
9167 
9168   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9169   rorxq(yz_idx1, yz_idx1, 32);
9170   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9171   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9172   rorxq(yz_idx2, yz_idx2, 32);
9173 
9174   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9175 
9176   movl(Address(z, idx, Address::times_4,  4), tmp3);
9177   shrq(tmp3, 32);
9178   movl(Address(z, idx, Address::times_4,  0), tmp3);
9179   movq(carry, tmp4);
9180 
9181   bind (L_check_1);
9182   addl (idx, 0x2);
9183   andl (idx, 0x1);
9184   subl(idx, 1);
9185   jcc(Assembler::negative, L_post_third_loop_done);
9186   movl(tmp4, Address(y, idx, Address::times_4,  0));
9187   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9188   movl(tmp4, Address(z, idx, Address::times_4,  0));
9189 
9190   add2_with_carry(carry2, tmp3, tmp4, carry);
9191 
9192   movl(Address(z, idx, Address::times_4,  0), tmp3);
9193   shrq(tmp3, 32);
9194 
9195   shlq(carry2, 32);
9196   orq(tmp3, carry2);
9197   movq(carry, tmp3);
9198 
9199   bind(L_post_third_loop_done);
9200 }
9201 
9202 /**
9203  * Code for BigInteger::multiplyToLen() instrinsic.
9204  *
9205  * rdi: x
9206  * rax: xlen
9207  * rsi: y
9208  * rcx: ylen
9209  * r8:  z
9210  * r11: zlen
9211  * r12: tmp1
9212  * r13: tmp2
9213  * r14: tmp3
9214  * r15: tmp4
9215  * rbx: tmp5
9216  *
9217  */
9218 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9219                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9220   ShortBranchVerifier sbv(this);
9221   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9222 
9223   push(tmp1);
9224   push(tmp2);
9225   push(tmp3);
9226   push(tmp4);
9227   push(tmp5);
9228 
9229   push(xlen);
9230   push(zlen);
9231 
9232   const Register idx = tmp1;
9233   const Register kdx = tmp2;
9234   const Register xstart = tmp3;
9235 
9236   const Register y_idx = tmp4;
9237   const Register carry = tmp5;
9238   const Register product  = xlen;
9239   const Register x_xstart = zlen;  // reuse register
9240 
9241   // First Loop.
9242   //
9243   //  final static long LONG_MASK = 0xffffffffL;
9244   //  int xstart = xlen - 1;
9245   //  int ystart = ylen - 1;
9246   //  long carry = 0;
9247   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9248   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9249   //    z[kdx] = (int)product;
9250   //    carry = product >>> 32;
9251   //  }
9252   //  z[xstart] = (int)carry;
9253   //
9254 
9255   movl(idx, ylen);      // idx = ylen;
9256   movl(kdx, zlen);      // kdx = xlen+ylen;
9257   xorq(carry, carry);   // carry = 0;
9258 
9259   Label L_done;
9260 
9261   movl(xstart, xlen);
9262   decrementl(xstart);
9263   jcc(Assembler::negative, L_done);
9264 
9265   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9266 
9267   Label L_second_loop;
9268   testl(kdx, kdx);
9269   jcc(Assembler::zero, L_second_loop);
9270 
9271   Label L_carry;
9272   subl(kdx, 1);
9273   jcc(Assembler::zero, L_carry);
9274 
9275   movl(Address(z, kdx, Address::times_4,  0), carry);
9276   shrq(carry, 32);
9277   subl(kdx, 1);
9278 
9279   bind(L_carry);
9280   movl(Address(z, kdx, Address::times_4,  0), carry);
9281 
9282   // Second and third (nested) loops.
9283   //
9284   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9285   //   carry = 0;
9286   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9287   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9288   //                    (z[k] & LONG_MASK) + carry;
9289   //     z[k] = (int)product;
9290   //     carry = product >>> 32;
9291   //   }
9292   //   z[i] = (int)carry;
9293   // }
9294   //
9295   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9296 
9297   const Register jdx = tmp1;
9298 
9299   bind(L_second_loop);
9300   xorl(carry, carry);    // carry = 0;
9301   movl(jdx, ylen);       // j = ystart+1
9302 
9303   subl(xstart, 1);       // i = xstart-1;
9304   jcc(Assembler::negative, L_done);
9305 
9306   push (z);
9307 
9308   Label L_last_x;
9309   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9310   subl(xstart, 1);       // i = xstart-1;
9311   jcc(Assembler::negative, L_last_x);
9312 
9313   if (UseBMI2Instructions) {
9314     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9315     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9316   } else {
9317     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9318     rorq(x_xstart, 32);  // convert big-endian to little-endian
9319   }
9320 
9321   Label L_third_loop_prologue;
9322   bind(L_third_loop_prologue);
9323 
9324   push (x);
9325   push (xstart);
9326   push (ylen);
9327 
9328 
9329   if (UseBMI2Instructions) {
9330     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9331   } else { // !UseBMI2Instructions
9332     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9333   }
9334 
9335   pop(ylen);
9336   pop(xlen);
9337   pop(x);
9338   pop(z);
9339 
9340   movl(tmp3, xlen);
9341   addl(tmp3, 1);
9342   movl(Address(z, tmp3, Address::times_4,  0), carry);
9343   subl(tmp3, 1);
9344   jccb(Assembler::negative, L_done);
9345 
9346   shrq(carry, 32);
9347   movl(Address(z, tmp3, Address::times_4,  0), carry);
9348   jmp(L_second_loop);
9349 
9350   // Next infrequent code is moved outside loops.
9351   bind(L_last_x);
9352   if (UseBMI2Instructions) {
9353     movl(rdx, Address(x,  0));
9354   } else {
9355     movl(x_xstart, Address(x,  0));
9356   }
9357   jmp(L_third_loop_prologue);
9358 
9359   bind(L_done);
9360 
9361   pop(zlen);
9362   pop(xlen);
9363 
9364   pop(tmp5);
9365   pop(tmp4);
9366   pop(tmp3);
9367   pop(tmp2);
9368   pop(tmp1);
9369 }
9370 
9371 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9372   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9373   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9374   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9375   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9376   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9377   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9378   Label SAME_TILL_END, DONE;
9379   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9380 
9381   //scale is in rcx in both Win64 and Unix
9382   ShortBranchVerifier sbv(this);
9383 
9384   shlq(length);
9385   xorq(result, result);
9386 
9387   if ((UseAVX > 2) &&
9388       VM_Version::supports_avx512vlbw()) {
9389     set_vector_masking();  // opening of the stub context for programming mask registers
9390     cmpq(length, 64);
9391     jcc(Assembler::less, VECTOR32_TAIL);
9392     movq(tmp1, length);
9393     andq(tmp1, 0x3F);      // tail count
9394     andq(length, ~(0x3F)); //vector count
9395 
9396     bind(VECTOR64_LOOP);
9397     // AVX512 code to compare 64 byte vectors.
9398     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9399     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9400     kortestql(k7, k7);
9401     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9402     addq(result, 64);
9403     subq(length, 64);
9404     jccb(Assembler::notZero, VECTOR64_LOOP);
9405 
9406     //bind(VECTOR64_TAIL);
9407     testq(tmp1, tmp1);
9408     jcc(Assembler::zero, SAME_TILL_END);
9409 
9410     bind(VECTOR64_TAIL);
9411     // AVX512 code to compare upto 63 byte vectors.
9412     // Save k1
9413     kmovql(k3, k1);
9414     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9415     shlxq(tmp2, tmp2, tmp1);
9416     notq(tmp2);
9417     kmovql(k1, tmp2);
9418 
9419     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9420     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9421 
9422     ktestql(k7, k1);
9423     // Restore k1
9424     kmovql(k1, k3);
9425     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9426 
9427     bind(VECTOR64_NOT_EQUAL);
9428     kmovql(tmp1, k7);
9429     notq(tmp1);
9430     tzcntq(tmp1, tmp1);
9431     addq(result, tmp1);
9432     shrq(result);
9433     jmp(DONE);
9434     bind(VECTOR32_TAIL);
9435     clear_vector_masking();   // closing of the stub context for programming mask registers
9436   }
9437 
9438   cmpq(length, 8);
9439   jcc(Assembler::equal, VECTOR8_LOOP);
9440   jcc(Assembler::less, VECTOR4_TAIL);
9441 
9442   if (UseAVX >= 2) {
9443 
9444     cmpq(length, 16);
9445     jcc(Assembler::equal, VECTOR16_LOOP);
9446     jcc(Assembler::less, VECTOR8_LOOP);
9447 
9448     cmpq(length, 32);
9449     jccb(Assembler::less, VECTOR16_TAIL);
9450 
9451     subq(length, 32);
9452     bind(VECTOR32_LOOP);
9453     vmovdqu(rymm0, Address(obja, result));
9454     vmovdqu(rymm1, Address(objb, result));
9455     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9456     vptest(rymm2, rymm2);
9457     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9458     addq(result, 32);
9459     subq(length, 32);
9460     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9461     addq(length, 32);
9462     jcc(Assembler::equal, SAME_TILL_END);
9463     //falling through if less than 32 bytes left //close the branch here.
9464 
9465     bind(VECTOR16_TAIL);
9466     cmpq(length, 16);
9467     jccb(Assembler::less, VECTOR8_TAIL);
9468     bind(VECTOR16_LOOP);
9469     movdqu(rymm0, Address(obja, result));
9470     movdqu(rymm1, Address(objb, result));
9471     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9472     ptest(rymm2, rymm2);
9473     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9474     addq(result, 16);
9475     subq(length, 16);
9476     jcc(Assembler::equal, SAME_TILL_END);
9477     //falling through if less than 16 bytes left
9478   } else {//regular intrinsics
9479 
9480     cmpq(length, 16);
9481     jccb(Assembler::less, VECTOR8_TAIL);
9482 
9483     subq(length, 16);
9484     bind(VECTOR16_LOOP);
9485     movdqu(rymm0, Address(obja, result));
9486     movdqu(rymm1, Address(objb, result));
9487     pxor(rymm0, rymm1);
9488     ptest(rymm0, rymm0);
9489     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9490     addq(result, 16);
9491     subq(length, 16);
9492     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9493     addq(length, 16);
9494     jcc(Assembler::equal, SAME_TILL_END);
9495     //falling through if less than 16 bytes left
9496   }
9497 
9498   bind(VECTOR8_TAIL);
9499   cmpq(length, 8);
9500   jccb(Assembler::less, VECTOR4_TAIL);
9501   bind(VECTOR8_LOOP);
9502   movq(tmp1, Address(obja, result));
9503   movq(tmp2, Address(objb, result));
9504   xorq(tmp1, tmp2);
9505   testq(tmp1, tmp1);
9506   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9507   addq(result, 8);
9508   subq(length, 8);
9509   jcc(Assembler::equal, SAME_TILL_END);
9510   //falling through if less than 8 bytes left
9511 
9512   bind(VECTOR4_TAIL);
9513   cmpq(length, 4);
9514   jccb(Assembler::less, BYTES_TAIL);
9515   bind(VECTOR4_LOOP);
9516   movl(tmp1, Address(obja, result));
9517   xorl(tmp1, Address(objb, result));
9518   testl(tmp1, tmp1);
9519   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9520   addq(result, 4);
9521   subq(length, 4);
9522   jcc(Assembler::equal, SAME_TILL_END);
9523   //falling through if less than 4 bytes left
9524 
9525   bind(BYTES_TAIL);
9526   bind(BYTES_LOOP);
9527   load_unsigned_byte(tmp1, Address(obja, result));
9528   load_unsigned_byte(tmp2, Address(objb, result));
9529   xorl(tmp1, tmp2);
9530   testl(tmp1, tmp1);
9531   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9532   decq(length);
9533   jccb(Assembler::zero, SAME_TILL_END);
9534   incq(result);
9535   load_unsigned_byte(tmp1, Address(obja, result));
9536   load_unsigned_byte(tmp2, Address(objb, result));
9537   xorl(tmp1, tmp2);
9538   testl(tmp1, tmp1);
9539   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9540   decq(length);
9541   jccb(Assembler::zero, SAME_TILL_END);
9542   incq(result);
9543   load_unsigned_byte(tmp1, Address(obja, result));
9544   load_unsigned_byte(tmp2, Address(objb, result));
9545   xorl(tmp1, tmp2);
9546   testl(tmp1, tmp1);
9547   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9548   jmpb(SAME_TILL_END);
9549 
9550   if (UseAVX >= 2) {
9551     bind(VECTOR32_NOT_EQUAL);
9552     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9553     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9554     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9555     vpmovmskb(tmp1, rymm0);
9556     bsfq(tmp1, tmp1);
9557     addq(result, tmp1);
9558     shrq(result);
9559     jmpb(DONE);
9560   }
9561 
9562   bind(VECTOR16_NOT_EQUAL);
9563   if (UseAVX >= 2) {
9564     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9565     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9566     pxor(rymm0, rymm2);
9567   } else {
9568     pcmpeqb(rymm2, rymm2);
9569     pxor(rymm0, rymm1);
9570     pcmpeqb(rymm0, rymm1);
9571     pxor(rymm0, rymm2);
9572   }
9573   pmovmskb(tmp1, rymm0);
9574   bsfq(tmp1, tmp1);
9575   addq(result, tmp1);
9576   shrq(result);
9577   jmpb(DONE);
9578 
9579   bind(VECTOR8_NOT_EQUAL);
9580   bind(VECTOR4_NOT_EQUAL);
9581   bsfq(tmp1, tmp1);
9582   shrq(tmp1, 3);
9583   addq(result, tmp1);
9584   bind(BYTES_NOT_EQUAL);
9585   shrq(result);
9586   jmpb(DONE);
9587 
9588   bind(SAME_TILL_END);
9589   mov64(result, -1);
9590 
9591   bind(DONE);
9592 }
9593 
9594 //Helper functions for square_to_len()
9595 
9596 /**
9597  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9598  * Preserves x and z and modifies rest of the registers.
9599  */
9600 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9601   // Perform square and right shift by 1
9602   // Handle odd xlen case first, then for even xlen do the following
9603   // jlong carry = 0;
9604   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9605   //     huge_128 product = x[j:j+1] * x[j:j+1];
9606   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9607   //     z[i+2:i+3] = (jlong)(product >>> 1);
9608   //     carry = (jlong)product;
9609   // }
9610 
9611   xorq(tmp5, tmp5);     // carry
9612   xorq(rdxReg, rdxReg);
9613   xorl(tmp1, tmp1);     // index for x
9614   xorl(tmp4, tmp4);     // index for z
9615 
9616   Label L_first_loop, L_first_loop_exit;
9617 
9618   testl(xlen, 1);
9619   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9620 
9621   // Square and right shift by 1 the odd element using 32 bit multiply
9622   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9623   imulq(raxReg, raxReg);
9624   shrq(raxReg, 1);
9625   adcq(tmp5, 0);
9626   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9627   incrementl(tmp1);
9628   addl(tmp4, 2);
9629 
9630   // Square and  right shift by 1 the rest using 64 bit multiply
9631   bind(L_first_loop);
9632   cmpptr(tmp1, xlen);
9633   jccb(Assembler::equal, L_first_loop_exit);
9634 
9635   // Square
9636   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9637   rorq(raxReg, 32);    // convert big-endian to little-endian
9638   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9639 
9640   // Right shift by 1 and save carry
9641   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9642   rcrq(rdxReg, 1);
9643   rcrq(raxReg, 1);
9644   adcq(tmp5, 0);
9645 
9646   // Store result in z
9647   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9648   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9649 
9650   // Update indices for x and z
9651   addl(tmp1, 2);
9652   addl(tmp4, 4);
9653   jmp(L_first_loop);
9654 
9655   bind(L_first_loop_exit);
9656 }
9657 
9658 
9659 /**
9660  * Perform the following multiply add operation using BMI2 instructions
9661  * carry:sum = sum + op1*op2 + carry
9662  * op2 should be in rdx
9663  * op2 is preserved, all other registers are modified
9664  */
9665 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9666   // assert op2 is rdx
9667   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9668   addq(sum, carry);
9669   adcq(tmp2, 0);
9670   addq(sum, op1);
9671   adcq(tmp2, 0);
9672   movq(carry, tmp2);
9673 }
9674 
9675 /**
9676  * Perform the following multiply add operation:
9677  * carry:sum = sum + op1*op2 + carry
9678  * Preserves op1, op2 and modifies rest of registers
9679  */
9680 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9681   // rdx:rax = op1 * op2
9682   movq(raxReg, op2);
9683   mulq(op1);
9684 
9685   //  rdx:rax = sum + carry + rdx:rax
9686   addq(sum, carry);
9687   adcq(rdxReg, 0);
9688   addq(sum, raxReg);
9689   adcq(rdxReg, 0);
9690 
9691   // carry:sum = rdx:sum
9692   movq(carry, rdxReg);
9693 }
9694 
9695 /**
9696  * Add 64 bit long carry into z[] with carry propogation.
9697  * Preserves z and carry register values and modifies rest of registers.
9698  *
9699  */
9700 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9701   Label L_fourth_loop, L_fourth_loop_exit;
9702 
9703   movl(tmp1, 1);
9704   subl(zlen, 2);
9705   addq(Address(z, zlen, Address::times_4, 0), carry);
9706 
9707   bind(L_fourth_loop);
9708   jccb(Assembler::carryClear, L_fourth_loop_exit);
9709   subl(zlen, 2);
9710   jccb(Assembler::negative, L_fourth_loop_exit);
9711   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9712   jmp(L_fourth_loop);
9713   bind(L_fourth_loop_exit);
9714 }
9715 
9716 /**
9717  * Shift z[] left by 1 bit.
9718  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9719  *
9720  */
9721 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9722 
9723   Label L_fifth_loop, L_fifth_loop_exit;
9724 
9725   // Fifth loop
9726   // Perform primitiveLeftShift(z, zlen, 1)
9727 
9728   const Register prev_carry = tmp1;
9729   const Register new_carry = tmp4;
9730   const Register value = tmp2;
9731   const Register zidx = tmp3;
9732 
9733   // int zidx, carry;
9734   // long value;
9735   // carry = 0;
9736   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9737   //    (carry:value)  = (z[i] << 1) | carry ;
9738   //    z[i] = value;
9739   // }
9740 
9741   movl(zidx, zlen);
9742   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9743 
9744   bind(L_fifth_loop);
9745   decl(zidx);  // Use decl to preserve carry flag
9746   decl(zidx);
9747   jccb(Assembler::negative, L_fifth_loop_exit);
9748 
9749   if (UseBMI2Instructions) {
9750      movq(value, Address(z, zidx, Address::times_4, 0));
9751      rclq(value, 1);
9752      rorxq(value, value, 32);
9753      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9754   }
9755   else {
9756     // clear new_carry
9757     xorl(new_carry, new_carry);
9758 
9759     // Shift z[i] by 1, or in previous carry and save new carry
9760     movq(value, Address(z, zidx, Address::times_4, 0));
9761     shlq(value, 1);
9762     adcl(new_carry, 0);
9763 
9764     orq(value, prev_carry);
9765     rorq(value, 0x20);
9766     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9767 
9768     // Set previous carry = new carry
9769     movl(prev_carry, new_carry);
9770   }
9771   jmp(L_fifth_loop);
9772 
9773   bind(L_fifth_loop_exit);
9774 }
9775 
9776 
9777 /**
9778  * Code for BigInteger::squareToLen() intrinsic
9779  *
9780  * rdi: x
9781  * rsi: len
9782  * r8:  z
9783  * rcx: zlen
9784  * r12: tmp1
9785  * r13: tmp2
9786  * r14: tmp3
9787  * r15: tmp4
9788  * rbx: tmp5
9789  *
9790  */
9791 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) {
9792 
9793   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, fifth_loop, fifth_loop_exit, L_last_x, L_multiply;
9794   push(tmp1);
9795   push(tmp2);
9796   push(tmp3);
9797   push(tmp4);
9798   push(tmp5);
9799 
9800   // First loop
9801   // Store the squares, right shifted one bit (i.e., divided by 2).
9802   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9803 
9804   // Add in off-diagonal sums.
9805   //
9806   // Second, third (nested) and fourth loops.
9807   // zlen +=2;
9808   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9809   //    carry = 0;
9810   //    long op2 = x[xidx:xidx+1];
9811   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9812   //       k -= 2;
9813   //       long op1 = x[j:j+1];
9814   //       long sum = z[k:k+1];
9815   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9816   //       z[k:k+1] = sum;
9817   //    }
9818   //    add_one_64(z, k, carry, tmp_regs);
9819   // }
9820 
9821   const Register carry = tmp5;
9822   const Register sum = tmp3;
9823   const Register op1 = tmp4;
9824   Register op2 = tmp2;
9825 
9826   push(zlen);
9827   push(len);
9828   addl(zlen,2);
9829   bind(L_second_loop);
9830   xorq(carry, carry);
9831   subl(zlen, 4);
9832   subl(len, 2);
9833   push(zlen);
9834   push(len);
9835   cmpl(len, 0);
9836   jccb(Assembler::lessEqual, L_second_loop_exit);
9837 
9838   // Multiply an array by one 64 bit long.
9839   if (UseBMI2Instructions) {
9840     op2 = rdxReg;
9841     movq(op2, Address(x, len, Address::times_4,  0));
9842     rorxq(op2, op2, 32);
9843   }
9844   else {
9845     movq(op2, Address(x, len, Address::times_4,  0));
9846     rorq(op2, 32);
9847   }
9848 
9849   bind(L_third_loop);
9850   decrementl(len);
9851   jccb(Assembler::negative, L_third_loop_exit);
9852   decrementl(len);
9853   jccb(Assembler::negative, L_last_x);
9854 
9855   movq(op1, Address(x, len, Address::times_4,  0));
9856   rorq(op1, 32);
9857 
9858   bind(L_multiply);
9859   subl(zlen, 2);
9860   movq(sum, Address(z, zlen, Address::times_4,  0));
9861 
9862   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9863   if (UseBMI2Instructions) {
9864     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9865   }
9866   else {
9867     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9868   }
9869 
9870   movq(Address(z, zlen, Address::times_4, 0), sum);
9871 
9872   jmp(L_third_loop);
9873   bind(L_third_loop_exit);
9874 
9875   // Fourth loop
9876   // Add 64 bit long carry into z with carry propogation.
9877   // Uses offsetted zlen.
9878   add_one_64(z, zlen, carry, tmp1);
9879 
9880   pop(len);
9881   pop(zlen);
9882   jmp(L_second_loop);
9883 
9884   // Next infrequent code is moved outside loops.
9885   bind(L_last_x);
9886   movl(op1, Address(x, 0));
9887   jmp(L_multiply);
9888 
9889   bind(L_second_loop_exit);
9890   pop(len);
9891   pop(zlen);
9892   pop(len);
9893   pop(zlen);
9894 
9895   // Fifth loop
9896   // Shift z left 1 bit.
9897   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9898 
9899   // z[zlen-1] |= x[len-1] & 1;
9900   movl(tmp3, Address(x, len, Address::times_4, -4));
9901   andl(tmp3, 1);
9902   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9903 
9904   pop(tmp5);
9905   pop(tmp4);
9906   pop(tmp3);
9907   pop(tmp2);
9908   pop(tmp1);
9909 }
9910 
9911 /**
9912  * Helper function for mul_add()
9913  * Multiply the in[] by int k and add to out[] starting at offset offs using
9914  * 128 bit by 32 bit multiply and return the carry in tmp5.
9915  * Only quad int aligned length of in[] is operated on in this function.
9916  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9917  * This function preserves out, in and k registers.
9918  * len and offset point to the appropriate index in "in" & "out" correspondingly
9919  * tmp5 has the carry.
9920  * other registers are temporary and are modified.
9921  *
9922  */
9923 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9924   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9925   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9926 
9927   Label L_first_loop, L_first_loop_exit;
9928 
9929   movl(tmp1, len);
9930   shrl(tmp1, 2);
9931 
9932   bind(L_first_loop);
9933   subl(tmp1, 1);
9934   jccb(Assembler::negative, L_first_loop_exit);
9935 
9936   subl(len, 4);
9937   subl(offset, 4);
9938 
9939   Register op2 = tmp2;
9940   const Register sum = tmp3;
9941   const Register op1 = tmp4;
9942   const Register carry = tmp5;
9943 
9944   if (UseBMI2Instructions) {
9945     op2 = rdxReg;
9946   }
9947 
9948   movq(op1, Address(in, len, Address::times_4,  8));
9949   rorq(op1, 32);
9950   movq(sum, Address(out, offset, Address::times_4,  8));
9951   rorq(sum, 32);
9952   if (UseBMI2Instructions) {
9953     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9954   }
9955   else {
9956     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9957   }
9958   // Store back in big endian from little endian
9959   rorq(sum, 0x20);
9960   movq(Address(out, offset, Address::times_4,  8), sum);
9961 
9962   movq(op1, Address(in, len, Address::times_4,  0));
9963   rorq(op1, 32);
9964   movq(sum, Address(out, offset, Address::times_4,  0));
9965   rorq(sum, 32);
9966   if (UseBMI2Instructions) {
9967     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9968   }
9969   else {
9970     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9971   }
9972   // Store back in big endian from little endian
9973   rorq(sum, 0x20);
9974   movq(Address(out, offset, Address::times_4,  0), sum);
9975 
9976   jmp(L_first_loop);
9977   bind(L_first_loop_exit);
9978 }
9979 
9980 /**
9981  * Code for BigInteger::mulAdd() intrinsic
9982  *
9983  * rdi: out
9984  * rsi: in
9985  * r11: offs (out.length - offset)
9986  * rcx: len
9987  * r8:  k
9988  * r12: tmp1
9989  * r13: tmp2
9990  * r14: tmp3
9991  * r15: tmp4
9992  * rbx: tmp5
9993  * Multiply the in[] by word k and add to out[], return the carry in rax
9994  */
9995 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9996    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9997    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9998 
9999   Label L_carry, L_last_in, L_done;
10000 
10001 // carry = 0;
10002 // for (int j=len-1; j >= 0; j--) {
10003 //    long product = (in[j] & LONG_MASK) * kLong +
10004 //                   (out[offs] & LONG_MASK) + carry;
10005 //    out[offs--] = (int)product;
10006 //    carry = product >>> 32;
10007 // }
10008 //
10009   push(tmp1);
10010   push(tmp2);
10011   push(tmp3);
10012   push(tmp4);
10013   push(tmp5);
10014 
10015   Register op2 = tmp2;
10016   const Register sum = tmp3;
10017   const Register op1 = tmp4;
10018   const Register carry =  tmp5;
10019 
10020   if (UseBMI2Instructions) {
10021     op2 = rdxReg;
10022     movl(op2, k);
10023   }
10024   else {
10025     movl(op2, k);
10026   }
10027 
10028   xorq(carry, carry);
10029 
10030   //First loop
10031 
10032   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10033   //The carry is in tmp5
10034   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10035 
10036   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10037   decrementl(len);
10038   jccb(Assembler::negative, L_carry);
10039   decrementl(len);
10040   jccb(Assembler::negative, L_last_in);
10041 
10042   movq(op1, Address(in, len, Address::times_4,  0));
10043   rorq(op1, 32);
10044 
10045   subl(offs, 2);
10046   movq(sum, Address(out, offs, Address::times_4,  0));
10047   rorq(sum, 32);
10048 
10049   if (UseBMI2Instructions) {
10050     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10051   }
10052   else {
10053     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10054   }
10055 
10056   // Store back in big endian from little endian
10057   rorq(sum, 0x20);
10058   movq(Address(out, offs, Address::times_4,  0), sum);
10059 
10060   testl(len, len);
10061   jccb(Assembler::zero, L_carry);
10062 
10063   //Multiply the last in[] entry, if any
10064   bind(L_last_in);
10065   movl(op1, Address(in, 0));
10066   movl(sum, Address(out, offs, Address::times_4,  -4));
10067 
10068   movl(raxReg, k);
10069   mull(op1); //tmp4 * eax -> edx:eax
10070   addl(sum, carry);
10071   adcl(rdxReg, 0);
10072   addl(sum, raxReg);
10073   adcl(rdxReg, 0);
10074   movl(carry, rdxReg);
10075 
10076   movl(Address(out, offs, Address::times_4,  -4), sum);
10077 
10078   bind(L_carry);
10079   //return tmp5/carry as carry in rax
10080   movl(rax, carry);
10081 
10082   bind(L_done);
10083   pop(tmp5);
10084   pop(tmp4);
10085   pop(tmp3);
10086   pop(tmp2);
10087   pop(tmp1);
10088 }
10089 #endif
10090 
10091 /**
10092  * Emits code to update CRC-32 with a byte value according to constants in table
10093  *
10094  * @param [in,out]crc   Register containing the crc.
10095  * @param [in]val       Register containing the byte to fold into the CRC.
10096  * @param [in]table     Register containing the table of crc constants.
10097  *
10098  * uint32_t crc;
10099  * val = crc_table[(val ^ crc) & 0xFF];
10100  * crc = val ^ (crc >> 8);
10101  *
10102  */
10103 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10104   xorl(val, crc);
10105   andl(val, 0xFF);
10106   shrl(crc, 8); // unsigned shift
10107   xorl(crc, Address(table, val, Address::times_4, 0));
10108 }
10109 
10110 /**
10111  * Fold 128-bit data chunk
10112  */
10113 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10114   if (UseAVX > 0) {
10115     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10116     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10117     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10118     pxor(xcrc, xtmp);
10119   } else {
10120     movdqa(xtmp, xcrc);
10121     pclmulhdq(xtmp, xK);   // [123:64]
10122     pclmulldq(xcrc, xK);   // [63:0]
10123     pxor(xcrc, xtmp);
10124     movdqu(xtmp, Address(buf, offset));
10125     pxor(xcrc, xtmp);
10126   }
10127 }
10128 
10129 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10130   if (UseAVX > 0) {
10131     vpclmulhdq(xtmp, xK, xcrc);
10132     vpclmulldq(xcrc, xK, xcrc);
10133     pxor(xcrc, xbuf);
10134     pxor(xcrc, xtmp);
10135   } else {
10136     movdqa(xtmp, xcrc);
10137     pclmulhdq(xtmp, xK);
10138     pclmulldq(xcrc, xK);
10139     pxor(xcrc, xbuf);
10140     pxor(xcrc, xtmp);
10141   }
10142 }
10143 
10144 /**
10145  * 8-bit folds to compute 32-bit CRC
10146  *
10147  * uint64_t xcrc;
10148  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10149  */
10150 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10151   movdl(tmp, xcrc);
10152   andl(tmp, 0xFF);
10153   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10154   psrldq(xcrc, 1); // unsigned shift one byte
10155   pxor(xcrc, xtmp);
10156 }
10157 
10158 /**
10159  * uint32_t crc;
10160  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10161  */
10162 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10163   movl(tmp, crc);
10164   andl(tmp, 0xFF);
10165   shrl(crc, 8);
10166   xorl(crc, Address(table, tmp, Address::times_4, 0));
10167 }
10168 
10169 /**
10170  * @param crc   register containing existing CRC (32-bit)
10171  * @param buf   register pointing to input byte buffer (byte*)
10172  * @param len   register containing number of bytes
10173  * @param table register that will contain address of CRC table
10174  * @param tmp   scratch register
10175  */
10176 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10177   assert_different_registers(crc, buf, len, table, tmp, rax);
10178 
10179   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10180   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10181 
10182   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10183   // context for the registers used, where all instructions below are using 128-bit mode
10184   // On EVEX without VL and BW, these instructions will all be AVX.
10185   if (VM_Version::supports_avx512vlbw()) {
10186     movl(tmp, 0xffff);
10187     kmovwl(k1, tmp);
10188   }
10189 
10190   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10191   notl(crc); // ~crc
10192   cmpl(len, 16);
10193   jcc(Assembler::less, L_tail);
10194 
10195   // Align buffer to 16 bytes
10196   movl(tmp, buf);
10197   andl(tmp, 0xF);
10198   jccb(Assembler::zero, L_aligned);
10199   subl(tmp,  16);
10200   addl(len, tmp);
10201 
10202   align(4);
10203   BIND(L_align_loop);
10204   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10205   update_byte_crc32(crc, rax, table);
10206   increment(buf);
10207   incrementl(tmp);
10208   jccb(Assembler::less, L_align_loop);
10209 
10210   BIND(L_aligned);
10211   movl(tmp, len); // save
10212   shrl(len, 4);
10213   jcc(Assembler::zero, L_tail_restore);
10214 
10215   // Fold crc into first bytes of vector
10216   movdqa(xmm1, Address(buf, 0));
10217   movdl(rax, xmm1);
10218   xorl(crc, rax);
10219   if (VM_Version::supports_sse4_1()) {
10220     pinsrd(xmm1, crc, 0);
10221   } else {
10222     pinsrw(xmm1, crc, 0);
10223     shrl(crc, 16);
10224     pinsrw(xmm1, crc, 1);
10225   }
10226   addptr(buf, 16);
10227   subl(len, 4); // len > 0
10228   jcc(Assembler::less, L_fold_tail);
10229 
10230   movdqa(xmm2, Address(buf,  0));
10231   movdqa(xmm3, Address(buf, 16));
10232   movdqa(xmm4, Address(buf, 32));
10233   addptr(buf, 48);
10234   subl(len, 3);
10235   jcc(Assembler::lessEqual, L_fold_512b);
10236 
10237   // Fold total 512 bits of polynomial on each iteration,
10238   // 128 bits per each of 4 parallel streams.
10239   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10240 
10241   align(32);
10242   BIND(L_fold_512b_loop);
10243   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10244   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10245   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10246   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10247   addptr(buf, 64);
10248   subl(len, 4);
10249   jcc(Assembler::greater, L_fold_512b_loop);
10250 
10251   // Fold 512 bits to 128 bits.
10252   BIND(L_fold_512b);
10253   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10254   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10255   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10256   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10257 
10258   // Fold the rest of 128 bits data chunks
10259   BIND(L_fold_tail);
10260   addl(len, 3);
10261   jccb(Assembler::lessEqual, L_fold_128b);
10262   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10263 
10264   BIND(L_fold_tail_loop);
10265   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10266   addptr(buf, 16);
10267   decrementl(len);
10268   jccb(Assembler::greater, L_fold_tail_loop);
10269 
10270   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10271   BIND(L_fold_128b);
10272   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10273   if (UseAVX > 0) {
10274     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10275     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10276     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10277   } else {
10278     movdqa(xmm2, xmm0);
10279     pclmulqdq(xmm2, xmm1, 0x1);
10280     movdqa(xmm3, xmm0);
10281     pand(xmm3, xmm2);
10282     pclmulqdq(xmm0, xmm3, 0x1);
10283   }
10284   psrldq(xmm1, 8);
10285   psrldq(xmm2, 4);
10286   pxor(xmm0, xmm1);
10287   pxor(xmm0, xmm2);
10288 
10289   // 8 8-bit folds to compute 32-bit CRC.
10290   for (int j = 0; j < 4; j++) {
10291     fold_8bit_crc32(xmm0, table, xmm1, rax);
10292   }
10293   movdl(crc, xmm0); // mov 32 bits to general register
10294   for (int j = 0; j < 4; j++) {
10295     fold_8bit_crc32(crc, table, rax);
10296   }
10297 
10298   BIND(L_tail_restore);
10299   movl(len, tmp); // restore
10300   BIND(L_tail);
10301   andl(len, 0xf);
10302   jccb(Assembler::zero, L_exit);
10303 
10304   // Fold the rest of bytes
10305   align(4);
10306   BIND(L_tail_loop);
10307   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10308   update_byte_crc32(crc, rax, table);
10309   increment(buf);
10310   decrementl(len);
10311   jccb(Assembler::greater, L_tail_loop);
10312 
10313   BIND(L_exit);
10314   notl(crc); // ~c
10315 }
10316 
10317 #ifdef _LP64
10318 // S. Gueron / Information Processing Letters 112 (2012) 184
10319 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10320 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10321 // Output: the 64-bit carry-less product of B * CONST
10322 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10323                                      Register tmp1, Register tmp2, Register tmp3) {
10324   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10325   if (n > 0) {
10326     addq(tmp3, n * 256 * 8);
10327   }
10328   //    Q1 = TABLEExt[n][B & 0xFF];
10329   movl(tmp1, in);
10330   andl(tmp1, 0x000000FF);
10331   shll(tmp1, 3);
10332   addq(tmp1, tmp3);
10333   movq(tmp1, Address(tmp1, 0));
10334 
10335   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10336   movl(tmp2, in);
10337   shrl(tmp2, 8);
10338   andl(tmp2, 0x000000FF);
10339   shll(tmp2, 3);
10340   addq(tmp2, tmp3);
10341   movq(tmp2, Address(tmp2, 0));
10342 
10343   shlq(tmp2, 8);
10344   xorq(tmp1, tmp2);
10345 
10346   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10347   movl(tmp2, in);
10348   shrl(tmp2, 16);
10349   andl(tmp2, 0x000000FF);
10350   shll(tmp2, 3);
10351   addq(tmp2, tmp3);
10352   movq(tmp2, Address(tmp2, 0));
10353 
10354   shlq(tmp2, 16);
10355   xorq(tmp1, tmp2);
10356 
10357   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10358   shrl(in, 24);
10359   andl(in, 0x000000FF);
10360   shll(in, 3);
10361   addq(in, tmp3);
10362   movq(in, Address(in, 0));
10363 
10364   shlq(in, 24);
10365   xorq(in, tmp1);
10366   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10367 }
10368 
10369 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10370                                       Register in_out,
10371                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10372                                       XMMRegister w_xtmp2,
10373                                       Register tmp1,
10374                                       Register n_tmp2, Register n_tmp3) {
10375   if (is_pclmulqdq_supported) {
10376     movdl(w_xtmp1, in_out); // modified blindly
10377 
10378     movl(tmp1, const_or_pre_comp_const_index);
10379     movdl(w_xtmp2, tmp1);
10380     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10381 
10382     movdq(in_out, w_xtmp1);
10383   } else {
10384     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10385   }
10386 }
10387 
10388 // Recombination Alternative 2: No bit-reflections
10389 // T1 = (CRC_A * U1) << 1
10390 // T2 = (CRC_B * U2) << 1
10391 // C1 = T1 >> 32
10392 // C2 = T2 >> 32
10393 // T1 = T1 & 0xFFFFFFFF
10394 // T2 = T2 & 0xFFFFFFFF
10395 // T1 = CRC32(0, T1)
10396 // T2 = CRC32(0, T2)
10397 // C1 = C1 ^ T1
10398 // C2 = C2 ^ T2
10399 // CRC = C1 ^ C2 ^ CRC_C
10400 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,
10401                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10402                                      Register tmp1, Register tmp2,
10403                                      Register n_tmp3) {
10404   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10405   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10406   shlq(in_out, 1);
10407   movl(tmp1, in_out);
10408   shrq(in_out, 32);
10409   xorl(tmp2, tmp2);
10410   crc32(tmp2, tmp1, 4);
10411   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10412   shlq(in1, 1);
10413   movl(tmp1, in1);
10414   shrq(in1, 32);
10415   xorl(tmp2, tmp2);
10416   crc32(tmp2, tmp1, 4);
10417   xorl(in1, tmp2);
10418   xorl(in_out, in1);
10419   xorl(in_out, in2);
10420 }
10421 
10422 // Set N to predefined value
10423 // Subtract from a lenght of a buffer
10424 // execute in a loop:
10425 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10426 // for i = 1 to N do
10427 //  CRC_A = CRC32(CRC_A, A[i])
10428 //  CRC_B = CRC32(CRC_B, B[i])
10429 //  CRC_C = CRC32(CRC_C, C[i])
10430 // end for
10431 // Recombine
10432 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,
10433                                        Register in_out1, Register in_out2, Register in_out3,
10434                                        Register tmp1, Register tmp2, Register tmp3,
10435                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10436                                        Register tmp4, Register tmp5,
10437                                        Register n_tmp6) {
10438   Label L_processPartitions;
10439   Label L_processPartition;
10440   Label L_exit;
10441 
10442   bind(L_processPartitions);
10443   cmpl(in_out1, 3 * size);
10444   jcc(Assembler::less, L_exit);
10445     xorl(tmp1, tmp1);
10446     xorl(tmp2, tmp2);
10447     movq(tmp3, in_out2);
10448     addq(tmp3, size);
10449 
10450     bind(L_processPartition);
10451       crc32(in_out3, Address(in_out2, 0), 8);
10452       crc32(tmp1, Address(in_out2, size), 8);
10453       crc32(tmp2, Address(in_out2, size * 2), 8);
10454       addq(in_out2, 8);
10455       cmpq(in_out2, tmp3);
10456       jcc(Assembler::less, L_processPartition);
10457     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10458             w_xtmp1, w_xtmp2, w_xtmp3,
10459             tmp4, tmp5,
10460             n_tmp6);
10461     addq(in_out2, 2 * size);
10462     subl(in_out1, 3 * size);
10463     jmp(L_processPartitions);
10464 
10465   bind(L_exit);
10466 }
10467 #else
10468 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10469                                      Register tmp1, Register tmp2, Register tmp3,
10470                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10471   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10472   if (n > 0) {
10473     addl(tmp3, n * 256 * 8);
10474   }
10475   //    Q1 = TABLEExt[n][B & 0xFF];
10476   movl(tmp1, in_out);
10477   andl(tmp1, 0x000000FF);
10478   shll(tmp1, 3);
10479   addl(tmp1, tmp3);
10480   movq(xtmp1, Address(tmp1, 0));
10481 
10482   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10483   movl(tmp2, in_out);
10484   shrl(tmp2, 8);
10485   andl(tmp2, 0x000000FF);
10486   shll(tmp2, 3);
10487   addl(tmp2, tmp3);
10488   movq(xtmp2, Address(tmp2, 0));
10489 
10490   psllq(xtmp2, 8);
10491   pxor(xtmp1, xtmp2);
10492 
10493   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10494   movl(tmp2, in_out);
10495   shrl(tmp2, 16);
10496   andl(tmp2, 0x000000FF);
10497   shll(tmp2, 3);
10498   addl(tmp2, tmp3);
10499   movq(xtmp2, Address(tmp2, 0));
10500 
10501   psllq(xtmp2, 16);
10502   pxor(xtmp1, xtmp2);
10503 
10504   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10505   shrl(in_out, 24);
10506   andl(in_out, 0x000000FF);
10507   shll(in_out, 3);
10508   addl(in_out, tmp3);
10509   movq(xtmp2, Address(in_out, 0));
10510 
10511   psllq(xtmp2, 24);
10512   pxor(xtmp1, xtmp2); // Result in CXMM
10513   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10514 }
10515 
10516 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10517                                       Register in_out,
10518                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10519                                       XMMRegister w_xtmp2,
10520                                       Register tmp1,
10521                                       Register n_tmp2, Register n_tmp3) {
10522   if (is_pclmulqdq_supported) {
10523     movdl(w_xtmp1, in_out);
10524 
10525     movl(tmp1, const_or_pre_comp_const_index);
10526     movdl(w_xtmp2, tmp1);
10527     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10528     // Keep result in XMM since GPR is 32 bit in length
10529   } else {
10530     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10531   }
10532 }
10533 
10534 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,
10535                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10536                                      Register tmp1, Register tmp2,
10537                                      Register n_tmp3) {
10538   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10539   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10540 
10541   psllq(w_xtmp1, 1);
10542   movdl(tmp1, w_xtmp1);
10543   psrlq(w_xtmp1, 32);
10544   movdl(in_out, w_xtmp1);
10545 
10546   xorl(tmp2, tmp2);
10547   crc32(tmp2, tmp1, 4);
10548   xorl(in_out, tmp2);
10549 
10550   psllq(w_xtmp2, 1);
10551   movdl(tmp1, w_xtmp2);
10552   psrlq(w_xtmp2, 32);
10553   movdl(in1, w_xtmp2);
10554 
10555   xorl(tmp2, tmp2);
10556   crc32(tmp2, tmp1, 4);
10557   xorl(in1, tmp2);
10558   xorl(in_out, in1);
10559   xorl(in_out, in2);
10560 }
10561 
10562 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,
10563                                        Register in_out1, Register in_out2, Register in_out3,
10564                                        Register tmp1, Register tmp2, Register tmp3,
10565                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10566                                        Register tmp4, Register tmp5,
10567                                        Register n_tmp6) {
10568   Label L_processPartitions;
10569   Label L_processPartition;
10570   Label L_exit;
10571 
10572   bind(L_processPartitions);
10573   cmpl(in_out1, 3 * size);
10574   jcc(Assembler::less, L_exit);
10575     xorl(tmp1, tmp1);
10576     xorl(tmp2, tmp2);
10577     movl(tmp3, in_out2);
10578     addl(tmp3, size);
10579 
10580     bind(L_processPartition);
10581       crc32(in_out3, Address(in_out2, 0), 4);
10582       crc32(tmp1, Address(in_out2, size), 4);
10583       crc32(tmp2, Address(in_out2, size*2), 4);
10584       crc32(in_out3, Address(in_out2, 0+4), 4);
10585       crc32(tmp1, Address(in_out2, size+4), 4);
10586       crc32(tmp2, Address(in_out2, size*2+4), 4);
10587       addl(in_out2, 8);
10588       cmpl(in_out2, tmp3);
10589       jcc(Assembler::less, L_processPartition);
10590 
10591         push(tmp3);
10592         push(in_out1);
10593         push(in_out2);
10594         tmp4 = tmp3;
10595         tmp5 = in_out1;
10596         n_tmp6 = in_out2;
10597 
10598       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10599             w_xtmp1, w_xtmp2, w_xtmp3,
10600             tmp4, tmp5,
10601             n_tmp6);
10602 
10603         pop(in_out2);
10604         pop(in_out1);
10605         pop(tmp3);
10606 
10607     addl(in_out2, 2 * size);
10608     subl(in_out1, 3 * size);
10609     jmp(L_processPartitions);
10610 
10611   bind(L_exit);
10612 }
10613 #endif //LP64
10614 
10615 #ifdef _LP64
10616 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10617 // Input: A buffer I of L bytes.
10618 // Output: the CRC32C value of the buffer.
10619 // Notations:
10620 // Write L = 24N + r, with N = floor (L/24).
10621 // r = L mod 24 (0 <= r < 24).
10622 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10623 // N quadwords, and R consists of r bytes.
10624 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10625 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10626 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10627 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10628 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10629                                           Register tmp1, Register tmp2, Register tmp3,
10630                                           Register tmp4, Register tmp5, Register tmp6,
10631                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10632                                           bool is_pclmulqdq_supported) {
10633   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10634   Label L_wordByWord;
10635   Label L_byteByByteProlog;
10636   Label L_byteByByte;
10637   Label L_exit;
10638 
10639   if (is_pclmulqdq_supported ) {
10640     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10641     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10642 
10643     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10644     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10645 
10646     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10647     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10648     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10649   } else {
10650     const_or_pre_comp_const_index[0] = 1;
10651     const_or_pre_comp_const_index[1] = 0;
10652 
10653     const_or_pre_comp_const_index[2] = 3;
10654     const_or_pre_comp_const_index[3] = 2;
10655 
10656     const_or_pre_comp_const_index[4] = 5;
10657     const_or_pre_comp_const_index[5] = 4;
10658    }
10659   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10660                     in2, in1, in_out,
10661                     tmp1, tmp2, tmp3,
10662                     w_xtmp1, w_xtmp2, w_xtmp3,
10663                     tmp4, tmp5,
10664                     tmp6);
10665   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10666                     in2, in1, in_out,
10667                     tmp1, tmp2, tmp3,
10668                     w_xtmp1, w_xtmp2, w_xtmp3,
10669                     tmp4, tmp5,
10670                     tmp6);
10671   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10672                     in2, in1, in_out,
10673                     tmp1, tmp2, tmp3,
10674                     w_xtmp1, w_xtmp2, w_xtmp3,
10675                     tmp4, tmp5,
10676                     tmp6);
10677   movl(tmp1, in2);
10678   andl(tmp1, 0x00000007);
10679   negl(tmp1);
10680   addl(tmp1, in2);
10681   addq(tmp1, in1);
10682 
10683   BIND(L_wordByWord);
10684   cmpq(in1, tmp1);
10685   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10686     crc32(in_out, Address(in1, 0), 4);
10687     addq(in1, 4);
10688     jmp(L_wordByWord);
10689 
10690   BIND(L_byteByByteProlog);
10691   andl(in2, 0x00000007);
10692   movl(tmp2, 1);
10693 
10694   BIND(L_byteByByte);
10695   cmpl(tmp2, in2);
10696   jccb(Assembler::greater, L_exit);
10697     crc32(in_out, Address(in1, 0), 1);
10698     incq(in1);
10699     incl(tmp2);
10700     jmp(L_byteByByte);
10701 
10702   BIND(L_exit);
10703 }
10704 #else
10705 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10706                                           Register tmp1, Register  tmp2, Register tmp3,
10707                                           Register tmp4, Register  tmp5, Register tmp6,
10708                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10709                                           bool is_pclmulqdq_supported) {
10710   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10711   Label L_wordByWord;
10712   Label L_byteByByteProlog;
10713   Label L_byteByByte;
10714   Label L_exit;
10715 
10716   if (is_pclmulqdq_supported) {
10717     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10718     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10719 
10720     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10721     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10722 
10723     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10724     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10725   } else {
10726     const_or_pre_comp_const_index[0] = 1;
10727     const_or_pre_comp_const_index[1] = 0;
10728 
10729     const_or_pre_comp_const_index[2] = 3;
10730     const_or_pre_comp_const_index[3] = 2;
10731 
10732     const_or_pre_comp_const_index[4] = 5;
10733     const_or_pre_comp_const_index[5] = 4;
10734   }
10735   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10736                     in2, in1, in_out,
10737                     tmp1, tmp2, tmp3,
10738                     w_xtmp1, w_xtmp2, w_xtmp3,
10739                     tmp4, tmp5,
10740                     tmp6);
10741   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10742                     in2, in1, in_out,
10743                     tmp1, tmp2, tmp3,
10744                     w_xtmp1, w_xtmp2, w_xtmp3,
10745                     tmp4, tmp5,
10746                     tmp6);
10747   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10748                     in2, in1, in_out,
10749                     tmp1, tmp2, tmp3,
10750                     w_xtmp1, w_xtmp2, w_xtmp3,
10751                     tmp4, tmp5,
10752                     tmp6);
10753   movl(tmp1, in2);
10754   andl(tmp1, 0x00000007);
10755   negl(tmp1);
10756   addl(tmp1, in2);
10757   addl(tmp1, in1);
10758 
10759   BIND(L_wordByWord);
10760   cmpl(in1, tmp1);
10761   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10762     crc32(in_out, Address(in1,0), 4);
10763     addl(in1, 4);
10764     jmp(L_wordByWord);
10765 
10766   BIND(L_byteByByteProlog);
10767   andl(in2, 0x00000007);
10768   movl(tmp2, 1);
10769 
10770   BIND(L_byteByByte);
10771   cmpl(tmp2, in2);
10772   jccb(Assembler::greater, L_exit);
10773     movb(tmp1, Address(in1, 0));
10774     crc32(in_out, tmp1, 1);
10775     incl(in1);
10776     incl(tmp2);
10777     jmp(L_byteByByte);
10778 
10779   BIND(L_exit);
10780 }
10781 #endif // LP64
10782 #undef BIND
10783 #undef BLOCK_COMMENT
10784 
10785 // Compress char[] array to byte[].
10786 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10787 //   @HotSpotIntrinsicCandidate
10788 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10789 //     for (int i = 0; i < len; i++) {
10790 //       int c = src[srcOff++];
10791 //       if (c >>> 8 != 0) {
10792 //         return 0;
10793 //       }
10794 //       dst[dstOff++] = (byte)c;
10795 //     }
10796 //     return len;
10797 //   }
10798 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10799   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10800   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10801   Register tmp5, Register result) {
10802   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10803 
10804   // rsi: src
10805   // rdi: dst
10806   // rdx: len
10807   // rcx: tmp5
10808   // rax: result
10809 
10810   // rsi holds start addr of source char[] to be compressed
10811   // rdi holds start addr of destination byte[]
10812   // rdx holds length
10813 
10814   assert(len != result, "");
10815 
10816   // save length for return
10817   push(len);
10818 
10819   if ((UseAVX > 2) && // AVX512
10820     VM_Version::supports_avx512vlbw() &&
10821     VM_Version::supports_bmi2()) {
10822 
10823     set_vector_masking();  // opening of the stub context for programming mask registers
10824 
10825     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10826 
10827     // alignement
10828     Label post_alignement;
10829 
10830     // if length of the string is less than 16, handle it in an old fashioned
10831     // way
10832     testl(len, -32);
10833     jcc(Assembler::zero, below_threshold);
10834 
10835     // First check whether a character is compressable ( <= 0xFF).
10836     // Create mask to test for Unicode chars inside zmm vector
10837     movl(result, 0x00FF);
10838     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10839 
10840     // Save k1
10841     kmovql(k3, k1);
10842 
10843     testl(len, -64);
10844     jcc(Assembler::zero, post_alignement);
10845 
10846     movl(tmp5, dst);
10847     andl(tmp5, (32 - 1));
10848     negl(tmp5);
10849     andl(tmp5, (32 - 1));
10850 
10851     // bail out when there is nothing to be done
10852     testl(tmp5, 0xFFFFFFFF);
10853     jcc(Assembler::zero, post_alignement);
10854 
10855     // ~(~0 << len), where len is the # of remaining elements to process
10856     movl(result, 0xFFFFFFFF);
10857     shlxl(result, result, tmp5);
10858     notl(result);
10859     kmovdl(k1, result);
10860 
10861     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10862     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10863     ktestd(k2, k1);
10864     jcc(Assembler::carryClear, restore_k1_return_zero);
10865 
10866     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10867 
10868     addptr(src, tmp5);
10869     addptr(src, tmp5);
10870     addptr(dst, tmp5);
10871     subl(len, tmp5);
10872 
10873     bind(post_alignement);
10874     // end of alignement
10875 
10876     movl(tmp5, len);
10877     andl(tmp5, (32 - 1));    // tail count (in chars)
10878     andl(len, ~(32 - 1));    // vector count (in chars)
10879     jcc(Assembler::zero, copy_loop_tail);
10880 
10881     lea(src, Address(src, len, Address::times_2));
10882     lea(dst, Address(dst, len, Address::times_1));
10883     negptr(len);
10884 
10885     bind(copy_32_loop);
10886     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10887     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10888     kortestdl(k2, k2);
10889     jcc(Assembler::carryClear, restore_k1_return_zero);
10890 
10891     // All elements in current processed chunk are valid candidates for
10892     // compression. Write a truncated byte elements to the memory.
10893     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10894     addptr(len, 32);
10895     jcc(Assembler::notZero, copy_32_loop);
10896 
10897     bind(copy_loop_tail);
10898     // bail out when there is nothing to be done
10899     testl(tmp5, 0xFFFFFFFF);
10900     // Restore k1
10901     kmovql(k1, k3);
10902     jcc(Assembler::zero, return_length);
10903 
10904     movl(len, tmp5);
10905 
10906     // ~(~0 << len), where len is the # of remaining elements to process
10907     movl(result, 0xFFFFFFFF);
10908     shlxl(result, result, len);
10909     notl(result);
10910 
10911     kmovdl(k1, result);
10912 
10913     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10914     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10915     ktestd(k2, k1);
10916     jcc(Assembler::carryClear, restore_k1_return_zero);
10917 
10918     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10919     // Restore k1
10920     kmovql(k1, k3);
10921     jmp(return_length);
10922 
10923     bind(restore_k1_return_zero);
10924     // Restore k1
10925     kmovql(k1, k3);
10926     jmp(return_zero);
10927 
10928     clear_vector_masking();   // closing of the stub context for programming mask registers
10929   }
10930   if (UseSSE42Intrinsics) {
10931     Label copy_32_loop, copy_16, copy_tail;
10932 
10933     bind(below_threshold);
10934 
10935     movl(result, len);
10936 
10937     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10938 
10939     // vectored compression
10940     andl(len, 0xfffffff0);    // vector count (in chars)
10941     andl(result, 0x0000000f);    // tail count (in chars)
10942     testl(len, len);
10943     jccb(Assembler::zero, copy_16);
10944 
10945     // compress 16 chars per iter
10946     movdl(tmp1Reg, tmp5);
10947     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10948     pxor(tmp4Reg, tmp4Reg);
10949 
10950     lea(src, Address(src, len, Address::times_2));
10951     lea(dst, Address(dst, len, Address::times_1));
10952     negptr(len);
10953 
10954     bind(copy_32_loop);
10955     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10956     por(tmp4Reg, tmp2Reg);
10957     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10958     por(tmp4Reg, tmp3Reg);
10959     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10960     jcc(Assembler::notZero, return_zero);
10961     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10962     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10963     addptr(len, 16);
10964     jcc(Assembler::notZero, copy_32_loop);
10965 
10966     // compress next vector of 8 chars (if any)
10967     bind(copy_16);
10968     movl(len, result);
10969     andl(len, 0xfffffff8);    // vector count (in chars)
10970     andl(result, 0x00000007);    // tail count (in chars)
10971     testl(len, len);
10972     jccb(Assembler::zero, copy_tail);
10973 
10974     movdl(tmp1Reg, tmp5);
10975     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10976     pxor(tmp3Reg, tmp3Reg);
10977 
10978     movdqu(tmp2Reg, Address(src, 0));
10979     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10980     jccb(Assembler::notZero, return_zero);
10981     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10982     movq(Address(dst, 0), tmp2Reg);
10983     addptr(src, 16);
10984     addptr(dst, 8);
10985 
10986     bind(copy_tail);
10987     movl(len, result);
10988   }
10989   // compress 1 char per iter
10990   testl(len, len);
10991   jccb(Assembler::zero, return_length);
10992   lea(src, Address(src, len, Address::times_2));
10993   lea(dst, Address(dst, len, Address::times_1));
10994   negptr(len);
10995 
10996   bind(copy_chars_loop);
10997   load_unsigned_short(result, Address(src, len, Address::times_2));
10998   testl(result, 0xff00);      // check if Unicode char
10999   jccb(Assembler::notZero, return_zero);
11000   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11001   increment(len);
11002   jcc(Assembler::notZero, copy_chars_loop);
11003 
11004   // if compression succeeded, return length
11005   bind(return_length);
11006   pop(result);
11007   jmpb(done);
11008 
11009   // if compression failed, return 0
11010   bind(return_zero);
11011   xorl(result, result);
11012   addptr(rsp, wordSize);
11013 
11014   bind(done);
11015 }
11016 
11017 // Inflate byte[] array to char[].
11018 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11019 //   @HotSpotIntrinsicCandidate
11020 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11021 //     for (int i = 0; i < len; i++) {
11022 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11023 //     }
11024 //   }
11025 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11026   XMMRegister tmp1, Register tmp2) {
11027   Label copy_chars_loop, done, below_threshold;
11028   // rsi: src
11029   // rdi: dst
11030   // rdx: len
11031   // rcx: tmp2
11032 
11033   // rsi holds start addr of source byte[] to be inflated
11034   // rdi holds start addr of destination char[]
11035   // rdx holds length
11036   assert_different_registers(src, dst, len, tmp2);
11037 
11038   if ((UseAVX > 2) && // AVX512
11039     VM_Version::supports_avx512vlbw() &&
11040     VM_Version::supports_bmi2()) {
11041 
11042     set_vector_masking();  // opening of the stub context for programming mask registers
11043 
11044     Label copy_32_loop, copy_tail;
11045     Register tmp3_aliased = len;
11046 
11047     // if length of the string is less than 16, handle it in an old fashioned
11048     // way
11049     testl(len, -16);
11050     jcc(Assembler::zero, below_threshold);
11051 
11052     // In order to use only one arithmetic operation for the main loop we use
11053     // this pre-calculation
11054     movl(tmp2, len);
11055     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11056     andl(len, -32);     // vector count
11057     jccb(Assembler::zero, copy_tail);
11058 
11059     lea(src, Address(src, len, Address::times_1));
11060     lea(dst, Address(dst, len, Address::times_2));
11061     negptr(len);
11062 
11063 
11064     // inflate 32 chars per iter
11065     bind(copy_32_loop);
11066     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11067     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11068     addptr(len, 32);
11069     jcc(Assembler::notZero, copy_32_loop);
11070 
11071     bind(copy_tail);
11072     // bail out when there is nothing to be done
11073     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11074     jcc(Assembler::zero, done);
11075 
11076     // Save k1
11077     kmovql(k2, k1);
11078 
11079     // ~(~0 << length), where length is the # of remaining elements to process
11080     movl(tmp3_aliased, -1);
11081     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11082     notl(tmp3_aliased);
11083     kmovdl(k1, tmp3_aliased);
11084     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11085     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11086 
11087     // Restore k1
11088     kmovql(k1, k2);
11089     jmp(done);
11090 
11091     clear_vector_masking();   // closing of the stub context for programming mask registers
11092   }
11093   if (UseSSE42Intrinsics) {
11094     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11095 
11096     movl(tmp2, len);
11097 
11098     if (UseAVX > 1) {
11099       andl(tmp2, (16 - 1));
11100       andl(len, -16);
11101       jccb(Assembler::zero, copy_new_tail);
11102     } else {
11103       andl(tmp2, 0x00000007);   // tail count (in chars)
11104       andl(len, 0xfffffff8);    // vector count (in chars)
11105       jccb(Assembler::zero, copy_tail);
11106     }
11107 
11108     // vectored inflation
11109     lea(src, Address(src, len, Address::times_1));
11110     lea(dst, Address(dst, len, Address::times_2));
11111     negptr(len);
11112 
11113     if (UseAVX > 1) {
11114       bind(copy_16_loop);
11115       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11116       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11117       addptr(len, 16);
11118       jcc(Assembler::notZero, copy_16_loop);
11119 
11120       bind(below_threshold);
11121       bind(copy_new_tail);
11122       if ((UseAVX > 2) &&
11123         VM_Version::supports_avx512vlbw() &&
11124         VM_Version::supports_bmi2()) {
11125         movl(tmp2, len);
11126       } else {
11127         movl(len, tmp2);
11128       }
11129       andl(tmp2, 0x00000007);
11130       andl(len, 0xFFFFFFF8);
11131       jccb(Assembler::zero, copy_tail);
11132 
11133       pmovzxbw(tmp1, Address(src, 0));
11134       movdqu(Address(dst, 0), tmp1);
11135       addptr(src, 8);
11136       addptr(dst, 2 * 8);
11137 
11138       jmp(copy_tail, true);
11139     }
11140 
11141     // inflate 8 chars per iter
11142     bind(copy_8_loop);
11143     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11144     movdqu(Address(dst, len, Address::times_2), tmp1);
11145     addptr(len, 8);
11146     jcc(Assembler::notZero, copy_8_loop);
11147 
11148     bind(copy_tail);
11149     movl(len, tmp2);
11150 
11151     cmpl(len, 4);
11152     jccb(Assembler::less, copy_bytes);
11153 
11154     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11155     pmovzxbw(tmp1, tmp1);
11156     movq(Address(dst, 0), tmp1);
11157     subptr(len, 4);
11158     addptr(src, 4);
11159     addptr(dst, 8);
11160 
11161     bind(copy_bytes);
11162   }
11163   testl(len, len);
11164   jccb(Assembler::zero, done);
11165   lea(src, Address(src, len, Address::times_1));
11166   lea(dst, Address(dst, len, Address::times_2));
11167   negptr(len);
11168 
11169   // inflate 1 char per iter
11170   bind(copy_chars_loop);
11171   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11172   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11173   increment(len);
11174   jcc(Assembler::notZero, copy_chars_loop);
11175 
11176   bind(done);
11177 }
11178 
11179 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11180   switch (cond) {
11181     // Note some conditions are synonyms for others
11182     case Assembler::zero:         return Assembler::notZero;
11183     case Assembler::notZero:      return Assembler::zero;
11184     case Assembler::less:         return Assembler::greaterEqual;
11185     case Assembler::lessEqual:    return Assembler::greater;
11186     case Assembler::greater:      return Assembler::lessEqual;
11187     case Assembler::greaterEqual: return Assembler::less;
11188     case Assembler::below:        return Assembler::aboveEqual;
11189     case Assembler::belowEqual:   return Assembler::above;
11190     case Assembler::above:        return Assembler::belowEqual;
11191     case Assembler::aboveEqual:   return Assembler::below;
11192     case Assembler::overflow:     return Assembler::noOverflow;
11193     case Assembler::noOverflow:   return Assembler::overflow;
11194     case Assembler::negative:     return Assembler::positive;
11195     case Assembler::positive:     return Assembler::negative;
11196     case Assembler::parity:       return Assembler::noParity;
11197     case Assembler::noParity:     return Assembler::parity;
11198   }
11199   ShouldNotReachHere(); return Assembler::overflow;
11200 }
11201 
11202 SkipIfEqual::SkipIfEqual(
11203     MacroAssembler* masm, const bool* flag_addr, bool value) {
11204   _masm = masm;
11205   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11206   _masm->jcc(Assembler::equal, _label);
11207 }
11208 
11209 SkipIfEqual::~SkipIfEqual() {
11210   _masm->bind(_label);
11211 }
11212 
11213 // 32-bit Windows has its own fast-path implementation
11214 // of get_thread
11215 #if !defined(WIN32) || defined(_LP64)
11216 
11217 // This is simply a call to Thread::current()
11218 void MacroAssembler::get_thread(Register thread) {
11219   if (thread != rax) {
11220     push(rax);
11221   }
11222   LP64_ONLY(push(rdi);)
11223   LP64_ONLY(push(rsi);)
11224   push(rdx);
11225   push(rcx);
11226 #ifdef _LP64
11227   push(r8);
11228   push(r9);
11229   push(r10);
11230   push(r11);
11231 #endif
11232 
11233   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11234 
11235 #ifdef _LP64
11236   pop(r11);
11237   pop(r10);
11238   pop(r9);
11239   pop(r8);
11240 #endif
11241   pop(rcx);
11242   pop(rdx);
11243   LP64_ONLY(pop(rsi);)
11244   LP64_ONLY(pop(rdi);)
11245   if (thread != rax) {
11246     mov(thread, rax);
11247     pop(rax);
11248   }
11249 }
11250 
11251 #endif