1 /*
   2  * Copyright (c) 1997, 2016, 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 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  49 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  50 #endif // INCLUDE_ALL_GCS
  51 #include "crc32c.h"
  52 #ifdef COMPILER2
  53 #include "opto/intrinsicnode.hpp"
  54 #endif
  55 
  56 #ifdef PRODUCT
  57 #define BLOCK_COMMENT(str) /* nothing */
  58 #define STOP(error) stop(error)
  59 #else
  60 #define BLOCK_COMMENT(str) block_comment(str)
  61 #define STOP(error) block_comment(error); stop(error)
  62 #endif
  63 
  64 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  65 
  66 #ifdef ASSERT
  67 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  68 #endif
  69 
  70 static Assembler::Condition reverse[] = {
  71     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  72     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  73     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  74     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  75     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  76     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  77     Assembler::above          /* belowEqual    = 0x6 */ ,
  78     Assembler::belowEqual     /* above         = 0x7 */ ,
  79     Assembler::positive       /* negative      = 0x8 */ ,
  80     Assembler::negative       /* positive      = 0x9 */ ,
  81     Assembler::noParity       /* parity        = 0xa */ ,
  82     Assembler::parity         /* noParity      = 0xb */ ,
  83     Assembler::greaterEqual   /* less          = 0xc */ ,
  84     Assembler::less           /* greaterEqual  = 0xd */ ,
  85     Assembler::greater        /* lessEqual     = 0xe */ ,
  86     Assembler::lessEqual      /* greater       = 0xf, */
  87 
  88 };
  89 
  90 
  91 // Implementation of MacroAssembler
  92 
  93 // First all the versions that have distinct versions depending on 32/64 bit
  94 // Unless the difference is trivial (1 line or so).
  95 
  96 #ifndef _LP64
  97 
  98 // 32bit versions
  99 
 100 Address MacroAssembler::as_Address(AddressLiteral adr) {
 101   return Address(adr.target(), adr.rspec());
 102 }
 103 
 104 Address MacroAssembler::as_Address(ArrayAddress adr) {
 105   return Address::make_array(adr);
 106 }
 107 
 108 void MacroAssembler::call_VM_leaf_base(address entry_point,
 109                                        int number_of_arguments) {
 110   call(RuntimeAddress(entry_point));
 111   increment(rsp, number_of_arguments * wordSize);
 112 }
 113 
 114 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 115   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 116 }
 117 
 118 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 119   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 120 }
 121 
 122 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 123   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 124 }
 125 
 126 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 127   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 128 }
 129 
 130 void MacroAssembler::extend_sign(Register hi, Register lo) {
 131   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 132   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 133     cdql();
 134   } else {
 135     movl(hi, lo);
 136     sarl(hi, 31);
 137   }
 138 }
 139 
 140 void MacroAssembler::jC2(Register tmp, Label& L) {
 141   // set parity bit if FPU flag C2 is set (via rax)
 142   save_rax(tmp);
 143   fwait(); fnstsw_ax();
 144   sahf();
 145   restore_rax(tmp);
 146   // branch
 147   jcc(Assembler::parity, L);
 148 }
 149 
 150 void MacroAssembler::jnC2(Register tmp, Label& L) {
 151   // set parity bit if FPU flag C2 is set (via rax)
 152   save_rax(tmp);
 153   fwait(); fnstsw_ax();
 154   sahf();
 155   restore_rax(tmp);
 156   // branch
 157   jcc(Assembler::noParity, L);
 158 }
 159 
 160 // 32bit can do a case table jump in one instruction but we no longer allow the base
 161 // to be installed in the Address class
 162 void MacroAssembler::jump(ArrayAddress entry) {
 163   jmp(as_Address(entry));
 164 }
 165 
 166 // Note: y_lo will be destroyed
 167 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 168   // Long compare for Java (semantics as described in JVM spec.)
 169   Label high, low, done;
 170 
 171   cmpl(x_hi, y_hi);
 172   jcc(Assembler::less, low);
 173   jcc(Assembler::greater, high);
 174   // x_hi is the return register
 175   xorl(x_hi, x_hi);
 176   cmpl(x_lo, y_lo);
 177   jcc(Assembler::below, low);
 178   jcc(Assembler::equal, done);
 179 
 180   bind(high);
 181   xorl(x_hi, x_hi);
 182   increment(x_hi);
 183   jmp(done);
 184 
 185   bind(low);
 186   xorl(x_hi, x_hi);
 187   decrementl(x_hi);
 188 
 189   bind(done);
 190 }
 191 
 192 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 193     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 194 }
 195 
 196 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 197   // leal(dst, as_Address(adr));
 198   // see note in movl as to why we must use a move
 199   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 200 }
 201 
 202 void MacroAssembler::leave() {
 203   mov(rsp, rbp);
 204   pop(rbp);
 205 }
 206 
 207 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 208   // Multiplication of two Java long values stored on the stack
 209   // as illustrated below. Result is in rdx:rax.
 210   //
 211   // rsp ---> [  ??  ] \               \
 212   //            ....    | y_rsp_offset  |
 213   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 214   //          [ y_hi ]                  | (in bytes)
 215   //            ....                    |
 216   //          [ x_lo ]                 /
 217   //          [ x_hi ]
 218   //            ....
 219   //
 220   // Basic idea: lo(result) = lo(x_lo * y_lo)
 221   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 222   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 223   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 224   Label quick;
 225   // load x_hi, y_hi and check if quick
 226   // multiplication is possible
 227   movl(rbx, x_hi);
 228   movl(rcx, y_hi);
 229   movl(rax, rbx);
 230   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 231   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 232   // do full multiplication
 233   // 1st step
 234   mull(y_lo);                                    // x_hi * y_lo
 235   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 236   // 2nd step
 237   movl(rax, x_lo);
 238   mull(rcx);                                     // x_lo * y_hi
 239   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 240   // 3rd step
 241   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 242   movl(rax, x_lo);
 243   mull(y_lo);                                    // x_lo * y_lo
 244   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 245 }
 246 
 247 void MacroAssembler::lneg(Register hi, Register lo) {
 248   negl(lo);
 249   adcl(hi, 0);
 250   negl(hi);
 251 }
 252 
 253 void MacroAssembler::lshl(Register hi, Register lo) {
 254   // Java shift left long support (semantics as described in JVM spec., p.305)
 255   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 256   // shift value is in rcx !
 257   assert(hi != rcx, "must not use rcx");
 258   assert(lo != rcx, "must not use rcx");
 259   const Register s = rcx;                        // shift count
 260   const int      n = BitsPerWord;
 261   Label L;
 262   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 263   cmpl(s, n);                                    // if (s < n)
 264   jcc(Assembler::less, L);                       // else (s >= n)
 265   movl(hi, lo);                                  // x := x << n
 266   xorl(lo, lo);
 267   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 268   bind(L);                                       // s (mod n) < n
 269   shldl(hi, lo);                                 // x := x << s
 270   shll(lo);
 271 }
 272 
 273 
 274 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 275   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 276   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 277   assert(hi != rcx, "must not use rcx");
 278   assert(lo != rcx, "must not use rcx");
 279   const Register s = rcx;                        // shift count
 280   const int      n = BitsPerWord;
 281   Label L;
 282   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 283   cmpl(s, n);                                    // if (s < n)
 284   jcc(Assembler::less, L);                       // else (s >= n)
 285   movl(lo, hi);                                  // x := x >> n
 286   if (sign_extension) sarl(hi, 31);
 287   else                xorl(hi, hi);
 288   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 289   bind(L);                                       // s (mod n) < n
 290   shrdl(lo, hi);                                 // x := x >> s
 291   if (sign_extension) sarl(hi);
 292   else                shrl(hi);
 293 }
 294 
 295 void MacroAssembler::movoop(Register dst, jobject obj) {
 296   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 297 }
 298 
 299 void MacroAssembler::movoop(Address dst, jobject obj) {
 300   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 301 }
 302 
 303 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 304   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 305 }
 306 
 307 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 308   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 309 }
 310 
 311 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 312   // scratch register is not used,
 313   // it is defined to match parameters of 64-bit version of this method.
 314   if (src.is_lval()) {
 315     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 316   } else {
 317     movl(dst, as_Address(src));
 318   }
 319 }
 320 
 321 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 322   movl(as_Address(dst), src);
 323 }
 324 
 325 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 326   movl(dst, as_Address(src));
 327 }
 328 
 329 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 330 void MacroAssembler::movptr(Address dst, intptr_t src) {
 331   movl(dst, src);
 332 }
 333 
 334 
 335 void MacroAssembler::pop_callee_saved_registers() {
 336   pop(rcx);
 337   pop(rdx);
 338   pop(rdi);
 339   pop(rsi);
 340 }
 341 
 342 void MacroAssembler::pop_fTOS() {
 343   fld_d(Address(rsp, 0));
 344   addl(rsp, 2 * wordSize);
 345 }
 346 
 347 void MacroAssembler::push_callee_saved_registers() {
 348   push(rsi);
 349   push(rdi);
 350   push(rdx);
 351   push(rcx);
 352 }
 353 
 354 void MacroAssembler::push_fTOS() {
 355   subl(rsp, 2 * wordSize);
 356   fstp_d(Address(rsp, 0));
 357 }
 358 
 359 
 360 void MacroAssembler::pushoop(jobject obj) {
 361   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 362 }
 363 
 364 void MacroAssembler::pushklass(Metadata* obj) {
 365   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 366 }
 367 
 368 void MacroAssembler::pushptr(AddressLiteral src) {
 369   if (src.is_lval()) {
 370     push_literal32((int32_t)src.target(), src.rspec());
 371   } else {
 372     pushl(as_Address(src));
 373   }
 374 }
 375 
 376 void MacroAssembler::set_word_if_not_zero(Register dst) {
 377   xorl(dst, dst);
 378   set_byte_if_not_zero(dst);
 379 }
 380 
 381 static void pass_arg0(MacroAssembler* masm, Register arg) {
 382   masm->push(arg);
 383 }
 384 
 385 static void pass_arg1(MacroAssembler* masm, Register arg) {
 386   masm->push(arg);
 387 }
 388 
 389 static void pass_arg2(MacroAssembler* masm, Register arg) {
 390   masm->push(arg);
 391 }
 392 
 393 static void pass_arg3(MacroAssembler* masm, Register arg) {
 394   masm->push(arg);
 395 }
 396 
 397 #ifndef PRODUCT
 398 extern "C" void findpc(intptr_t x);
 399 #endif
 400 
 401 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 402   // In order to get locks to work, we need to fake a in_VM state
 403   JavaThread* thread = JavaThread::current();
 404   JavaThreadState saved_state = thread->thread_state();
 405   thread->set_thread_state(_thread_in_vm);
 406   if (ShowMessageBoxOnError) {
 407     JavaThread* thread = JavaThread::current();
 408     JavaThreadState saved_state = thread->thread_state();
 409     thread->set_thread_state(_thread_in_vm);
 410     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 411       ttyLocker ttyl;
 412       BytecodeCounter::print();
 413     }
 414     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 415     // This is the value of eip which points to where verify_oop will return.
 416     if (os::message_box(msg, "Execution stopped, print registers?")) {
 417       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 418       BREAKPOINT;
 419     }
 420   } else {
 421     ttyLocker ttyl;
 422     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 423   }
 424   // Don't assert holding the ttyLock
 425     assert(false, "DEBUG MESSAGE: %s", msg);
 426   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 427 }
 428 
 429 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 430   ttyLocker ttyl;
 431   FlagSetting fs(Debugging, true);
 432   tty->print_cr("eip = 0x%08x", eip);
 433 #ifndef PRODUCT
 434   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 435     tty->cr();
 436     findpc(eip);
 437     tty->cr();
 438   }
 439 #endif
 440 #define PRINT_REG(rax) \
 441   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 442   PRINT_REG(rax);
 443   PRINT_REG(rbx);
 444   PRINT_REG(rcx);
 445   PRINT_REG(rdx);
 446   PRINT_REG(rdi);
 447   PRINT_REG(rsi);
 448   PRINT_REG(rbp);
 449   PRINT_REG(rsp);
 450 #undef PRINT_REG
 451   // Print some words near top of staack.
 452   int* dump_sp = (int*) rsp;
 453   for (int col1 = 0; col1 < 8; col1++) {
 454     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 455     os::print_location(tty, *dump_sp++);
 456   }
 457   for (int row = 0; row < 16; row++) {
 458     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 459     for (int col = 0; col < 8; col++) {
 460       tty->print(" 0x%08x", *dump_sp++);
 461     }
 462     tty->cr();
 463   }
 464   // Print some instructions around pc:
 465   Disassembler::decode((address)eip-64, (address)eip);
 466   tty->print_cr("--------");
 467   Disassembler::decode((address)eip, (address)eip+32);
 468 }
 469 
 470 void MacroAssembler::stop(const char* msg) {
 471   ExternalAddress message((address)msg);
 472   // push address of message
 473   pushptr(message.addr());
 474   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 475   pusha();                                            // push registers
 476   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 477   hlt();
 478 }
 479 
 480 void MacroAssembler::warn(const char* msg) {
 481   push_CPU_state();
 482 
 483   ExternalAddress message((address) msg);
 484   // push address of message
 485   pushptr(message.addr());
 486 
 487   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 488   addl(rsp, wordSize);       // discard argument
 489   pop_CPU_state();
 490 }
 491 
 492 void MacroAssembler::print_state() {
 493   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 494   pusha();                                            // push registers
 495 
 496   push_CPU_state();
 497   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 498   pop_CPU_state();
 499 
 500   popa();
 501   addl(rsp, wordSize);
 502 }
 503 
 504 #else // _LP64
 505 
 506 // 64 bit versions
 507 
 508 Address MacroAssembler::as_Address(AddressLiteral adr) {
 509   // amd64 always does this as a pc-rel
 510   // we can be absolute or disp based on the instruction type
 511   // jmp/call are displacements others are absolute
 512   assert(!adr.is_lval(), "must be rval");
 513   assert(reachable(adr), "must be");
 514   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 515 
 516 }
 517 
 518 Address MacroAssembler::as_Address(ArrayAddress adr) {
 519   AddressLiteral base = adr.base();
 520   lea(rscratch1, base);
 521   Address index = adr.index();
 522   assert(index._disp == 0, "must not have disp"); // maybe it can?
 523   Address array(rscratch1, index._index, index._scale, index._disp);
 524   return array;
 525 }
 526 
 527 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 528   Label L, E;
 529 
 530 #ifdef _WIN64
 531   // Windows always allocates space for it's register args
 532   assert(num_args <= 4, "only register arguments supported");
 533   subq(rsp,  frame::arg_reg_save_area_bytes);
 534 #endif
 535 
 536   // Align stack if necessary
 537   testl(rsp, 15);
 538   jcc(Assembler::zero, L);
 539 
 540   subq(rsp, 8);
 541   {
 542     call(RuntimeAddress(entry_point));
 543   }
 544   addq(rsp, 8);
 545   jmp(E);
 546 
 547   bind(L);
 548   {
 549     call(RuntimeAddress(entry_point));
 550   }
 551 
 552   bind(E);
 553 
 554 #ifdef _WIN64
 555   // restore stack pointer
 556   addq(rsp, frame::arg_reg_save_area_bytes);
 557 #endif
 558 
 559 }
 560 
 561 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 562   assert(!src2.is_lval(), "should use cmpptr");
 563 
 564   if (reachable(src2)) {
 565     cmpq(src1, as_Address(src2));
 566   } else {
 567     lea(rscratch1, src2);
 568     Assembler::cmpq(src1, Address(rscratch1, 0));
 569   }
 570 }
 571 
 572 int MacroAssembler::corrected_idivq(Register reg) {
 573   // Full implementation of Java ldiv and lrem; checks for special
 574   // case as described in JVM spec., p.243 & p.271.  The function
 575   // returns the (pc) offset of the idivl instruction - may be needed
 576   // for implicit exceptions.
 577   //
 578   //         normal case                           special case
 579   //
 580   // input : rax: dividend                         min_long
 581   //         reg: divisor   (may not be eax/edx)   -1
 582   //
 583   // output: rax: quotient  (= rax idiv reg)       min_long
 584   //         rdx: remainder (= rax irem reg)       0
 585   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 586   static const int64_t min_long = 0x8000000000000000;
 587   Label normal_case, special_case;
 588 
 589   // check for special case
 590   cmp64(rax, ExternalAddress((address) &min_long));
 591   jcc(Assembler::notEqual, normal_case);
 592   xorl(rdx, rdx); // prepare rdx for possible special case (where
 593                   // remainder = 0)
 594   cmpq(reg, -1);
 595   jcc(Assembler::equal, special_case);
 596 
 597   // handle normal case
 598   bind(normal_case);
 599   cdqq();
 600   int idivq_offset = offset();
 601   idivq(reg);
 602 
 603   // normal and special case exit
 604   bind(special_case);
 605 
 606   return idivq_offset;
 607 }
 608 
 609 void MacroAssembler::decrementq(Register reg, int value) {
 610   if (value == min_jint) { subq(reg, value); return; }
 611   if (value <  0) { incrementq(reg, -value); return; }
 612   if (value == 0) {                        ; return; }
 613   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 614   /* else */      { subq(reg, value)       ; return; }
 615 }
 616 
 617 void MacroAssembler::decrementq(Address dst, int value) {
 618   if (value == min_jint) { subq(dst, value); return; }
 619   if (value <  0) { incrementq(dst, -value); return; }
 620   if (value == 0) {                        ; return; }
 621   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 622   /* else */      { subq(dst, value)       ; return; }
 623 }
 624 
 625 void MacroAssembler::incrementq(AddressLiteral dst) {
 626   if (reachable(dst)) {
 627     incrementq(as_Address(dst));
 628   } else {
 629     lea(rscratch1, dst);
 630     incrementq(Address(rscratch1, 0));
 631   }
 632 }
 633 
 634 void MacroAssembler::incrementq(Register reg, int value) {
 635   if (value == min_jint) { addq(reg, value); return; }
 636   if (value <  0) { decrementq(reg, -value); return; }
 637   if (value == 0) {                        ; return; }
 638   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 639   /* else */      { addq(reg, value)       ; return; }
 640 }
 641 
 642 void MacroAssembler::incrementq(Address dst, int value) {
 643   if (value == min_jint) { addq(dst, value); return; }
 644   if (value <  0) { decrementq(dst, -value); return; }
 645   if (value == 0) {                        ; return; }
 646   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 647   /* else */      { addq(dst, value)       ; return; }
 648 }
 649 
 650 // 32bit can do a case table jump in one instruction but we no longer allow the base
 651 // to be installed in the Address class
 652 void MacroAssembler::jump(ArrayAddress entry) {
 653   lea(rscratch1, entry.base());
 654   Address dispatch = entry.index();
 655   assert(dispatch._base == noreg, "must be");
 656   dispatch._base = rscratch1;
 657   jmp(dispatch);
 658 }
 659 
 660 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 661   ShouldNotReachHere(); // 64bit doesn't use two regs
 662   cmpq(x_lo, y_lo);
 663 }
 664 
 665 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 666     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 667 }
 668 
 669 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 670   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 671   movptr(dst, rscratch1);
 672 }
 673 
 674 void MacroAssembler::leave() {
 675   // %%% is this really better? Why not on 32bit too?
 676   emit_int8((unsigned char)0xC9); // LEAVE
 677 }
 678 
 679 void MacroAssembler::lneg(Register hi, Register lo) {
 680   ShouldNotReachHere(); // 64bit doesn't use two regs
 681   negq(lo);
 682 }
 683 
 684 void MacroAssembler::movoop(Register dst, jobject obj) {
 685   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 686 }
 687 
 688 void MacroAssembler::movoop(Address dst, jobject obj) {
 689   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 690   movq(dst, rscratch1);
 691 }
 692 
 693 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 694   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 695 }
 696 
 697 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 698   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 699   movq(dst, rscratch1);
 700 }
 701 
 702 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 703   if (src.is_lval()) {
 704     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 705   } else {
 706     if (reachable(src)) {
 707       movq(dst, as_Address(src));
 708     } else {
 709       lea(scratch, src);
 710       movq(dst, Address(scratch, 0));
 711     }
 712   }
 713 }
 714 
 715 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 716   movq(as_Address(dst), src);
 717 }
 718 
 719 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 720   movq(dst, as_Address(src));
 721 }
 722 
 723 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 724 void MacroAssembler::movptr(Address dst, intptr_t src) {
 725   mov64(rscratch1, src);
 726   movq(dst, rscratch1);
 727 }
 728 
 729 // These are mostly for initializing NULL
 730 void MacroAssembler::movptr(Address dst, int32_t src) {
 731   movslq(dst, src);
 732 }
 733 
 734 void MacroAssembler::movptr(Register dst, int32_t src) {
 735   mov64(dst, (intptr_t)src);
 736 }
 737 
 738 void MacroAssembler::pushoop(jobject obj) {
 739   movoop(rscratch1, obj);
 740   push(rscratch1);
 741 }
 742 
 743 void MacroAssembler::pushklass(Metadata* obj) {
 744   mov_metadata(rscratch1, obj);
 745   push(rscratch1);
 746 }
 747 
 748 void MacroAssembler::pushptr(AddressLiteral src) {
 749   lea(rscratch1, src);
 750   if (src.is_lval()) {
 751     push(rscratch1);
 752   } else {
 753     pushq(Address(rscratch1, 0));
 754   }
 755 }
 756 
 757 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 758   // we must set sp to zero to clear frame
 759   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 760   // must clear fp, so that compiled frames are not confused; it is
 761   // possible that we need it only for debugging
 762   if (clear_fp) {
 763     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 764   }
 765 
 766   // Always clear the pc because it could have been set by make_walkable()
 767   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 768 }
 769 
 770 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 771                                          Register last_java_fp,
 772                                          address  last_java_pc) {
 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   shenandoah_store_addr_check(obj_reg);
1112 
1113   if (PrintBiasedLockingStatistics && counters == NULL) {
1114     counters = BiasedLocking::counters();
1115   }
1116   // Biased locking
1117   // See whether the lock is currently biased toward our thread and
1118   // whether the epoch is still valid
1119   // Note that the runtime guarantees sufficient alignment of JavaThread
1120   // pointers to allow age to be placed into low bits
1121   // First check to see whether biasing is even enabled for this object
1122   Label cas_label;
1123   int null_check_offset = -1;
1124   if (!swap_reg_contains_mark) {
1125     null_check_offset = offset();
1126     movptr(swap_reg, mark_addr);
1127   }
1128   movptr(tmp_reg, swap_reg);
1129   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1130   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1131   jcc(Assembler::notEqual, cas_label);
1132   // The bias pattern is present in the object's header. Need to check
1133   // whether the bias owner and the epoch are both still current.
1134 #ifndef _LP64
1135   // Note that because there is no current thread register on x86_32 we
1136   // need to store off the mark word we read out of the object to
1137   // avoid reloading it and needing to recheck invariants below. This
1138   // store is unfortunate but it makes the overall code shorter and
1139   // simpler.
1140   movptr(saved_mark_addr, swap_reg);
1141 #endif
1142   if (swap_reg_contains_mark) {
1143     null_check_offset = offset();
1144   }
1145   load_prototype_header(tmp_reg, obj_reg);
1146 #ifdef _LP64
1147   orptr(tmp_reg, r15_thread);
1148   xorptr(tmp_reg, swap_reg);
1149   Register header_reg = tmp_reg;
1150 #else
1151   xorptr(tmp_reg, swap_reg);
1152   get_thread(swap_reg);
1153   xorptr(swap_reg, tmp_reg);
1154   Register header_reg = swap_reg;
1155 #endif
1156   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1157   if (counters != NULL) {
1158     cond_inc32(Assembler::zero,
1159                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1160   }
1161   jcc(Assembler::equal, done);
1162 
1163   Label try_revoke_bias;
1164   Label try_rebias;
1165 
1166   // At this point we know that the header has the bias pattern and
1167   // that we are not the bias owner in the current epoch. We need to
1168   // figure out more details about the state of the header in order to
1169   // know what operations can be legally performed on the object's
1170   // header.
1171 
1172   // If the low three bits in the xor result aren't clear, that means
1173   // the prototype header is no longer biased and we have to revoke
1174   // the bias on this object.
1175   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1176   jccb_if_possible(Assembler::notZero, try_revoke_bias);
1177 
1178   // Biasing is still enabled for this data type. See whether the
1179   // epoch of the current bias is still valid, meaning that the epoch
1180   // bits of the mark word are equal to the epoch bits of the
1181   // prototype header. (Note that the prototype header's epoch bits
1182   // only change at a safepoint.) If not, attempt to rebias the object
1183   // toward the current thread. Note that we must be absolutely sure
1184   // that the current epoch is invalid in order to do this because
1185   // otherwise the manipulations it performs on the mark word are
1186   // illegal.
1187   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1188   jccb_if_possible(Assembler::notZero, try_rebias);
1189 
1190   // The epoch of the current bias is still valid but we know nothing
1191   // about the owner; it might be set or it might be clear. Try to
1192   // acquire the bias of the object using an atomic operation. If this
1193   // fails we will go in to the runtime to revoke the object's bias.
1194   // Note that we first construct the presumed unbiased header so we
1195   // don't accidentally blow away another thread's valid bias.
1196   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1197   andptr(swap_reg,
1198          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1199 #ifdef _LP64
1200   movptr(tmp_reg, swap_reg);
1201   orptr(tmp_reg, r15_thread);
1202 #else
1203   get_thread(tmp_reg);
1204   orptr(tmp_reg, swap_reg);
1205 #endif
1206   if (os::is_MP()) {
1207     lock();
1208   }
1209   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1210   // If the biasing toward our thread failed, this means that
1211   // another thread succeeded in biasing it toward itself and we
1212   // need to revoke that bias. The revocation will occur in the
1213   // interpreter runtime in the slow case.
1214   if (counters != NULL) {
1215     cond_inc32(Assembler::zero,
1216                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1217   }
1218   if (slow_case != NULL) {
1219     jcc(Assembler::notZero, *slow_case);
1220   }
1221   jmp(done);
1222 
1223   bind(try_rebias);
1224   // At this point we know the epoch has expired, meaning that the
1225   // current "bias owner", if any, is actually invalid. Under these
1226   // circumstances _only_, we are allowed to use the current header's
1227   // value as the comparison value when doing the cas to acquire the
1228   // bias in the current epoch. In other words, we allow transfer of
1229   // the bias from one thread to another directly in this situation.
1230   //
1231   // FIXME: due to a lack of registers we currently blow away the age
1232   // bits in this situation. Should attempt to preserve them.
1233   load_prototype_header(tmp_reg, obj_reg);
1234 #ifdef _LP64
1235   orptr(tmp_reg, r15_thread);
1236 #else
1237   get_thread(swap_reg);
1238   orptr(tmp_reg, swap_reg);
1239   movptr(swap_reg, saved_mark_addr);
1240 #endif
1241   if (os::is_MP()) {
1242     lock();
1243   }
1244   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1245   // If the biasing toward our thread failed, then another thread
1246   // succeeded in biasing it toward itself and we need to revoke that
1247   // bias. The revocation will occur in the runtime in the slow case.
1248   if (counters != NULL) {
1249     cond_inc32(Assembler::zero,
1250                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1251   }
1252   if (slow_case != NULL) {
1253     jcc(Assembler::notZero, *slow_case);
1254   }
1255   jmp(done);
1256 
1257   bind(try_revoke_bias);
1258   // The prototype mark in the klass doesn't have the bias bit set any
1259   // more, indicating that objects of this data type are not supposed
1260   // to be biased any more. We are going to try to reset the mark of
1261   // this object to the prototype value and fall through to the
1262   // CAS-based locking scheme. Note that if our CAS fails, it means
1263   // that another thread raced us for the privilege of revoking the
1264   // bias of this particular object, so it's okay to continue in the
1265   // normal locking code.
1266   //
1267   // FIXME: due to a lack of registers we currently blow away the age
1268   // bits in this situation. Should attempt to preserve them.
1269   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1270   load_prototype_header(tmp_reg, obj_reg);
1271   if (os::is_MP()) {
1272     lock();
1273   }
1274   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1275   // Fall through to the normal CAS-based lock, because no matter what
1276   // the result of the above CAS, some thread must have succeeded in
1277   // removing the bias bit from the object's header.
1278   if (counters != NULL) {
1279     cond_inc32(Assembler::zero,
1280                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1281   }
1282 
1283   bind(cas_label);
1284 
1285   return null_check_offset;
1286 }
1287 
1288 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1289   assert(UseBiasedLocking, "why call this otherwise?");
1290 
1291   // Check for biased locking unlock case, which is a no-op
1292   // Note: we do not have to check the thread ID for two reasons.
1293   // First, the interpreter checks for IllegalMonitorStateException at
1294   // a higher level. Second, if the bias was revoked while we held the
1295   // lock, the object could not be rebiased toward another thread, so
1296   // the bias bit would be clear.
1297   shenandoah_store_addr_check(obj_reg); // Access mark word
1298   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1299   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1300   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1301   jcc(Assembler::equal, done);
1302 }
1303 
1304 #ifdef COMPILER2
1305 
1306 #if INCLUDE_RTM_OPT
1307 
1308 // Update rtm_counters based on abort status
1309 // input: abort_status
1310 //        rtm_counters (RTMLockingCounters*)
1311 // flags are killed
1312 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1313 
1314   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1315   if (PrintPreciseRTMLockingStatistics) {
1316     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1317       Label check_abort;
1318       testl(abort_status, (1<<i));
1319       jccb(Assembler::equal, check_abort);
1320       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1321       bind(check_abort);
1322     }
1323   }
1324 }
1325 
1326 // Branch if (random & (count-1) != 0), count is 2^n
1327 // tmp, scr and flags are killed
1328 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1329   assert(tmp == rax, "");
1330   assert(scr == rdx, "");
1331   rdtsc(); // modifies EDX:EAX
1332   andptr(tmp, count-1);
1333   jccb(Assembler::notZero, brLabel);
1334 }
1335 
1336 // Perform abort ratio calculation, set no_rtm bit if high ratio
1337 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1338 // tmpReg, rtm_counters_Reg and flags are killed
1339 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1340                                                  Register rtm_counters_Reg,
1341                                                  RTMLockingCounters* rtm_counters,
1342                                                  Metadata* method_data) {
1343   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1344 
1345   if (RTMLockingCalculationDelay > 0) {
1346     // Delay calculation
1347     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1348     testptr(tmpReg, tmpReg);
1349     jccb(Assembler::equal, L_done);
1350   }
1351   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1352   //   Aborted transactions = abort_count * 100
1353   //   All transactions = total_count *  RTMTotalCountIncrRate
1354   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1355 
1356   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1357   cmpptr(tmpReg, RTMAbortThreshold);
1358   jccb(Assembler::below, L_check_always_rtm2);
1359   imulptr(tmpReg, tmpReg, 100);
1360 
1361   Register scrReg = rtm_counters_Reg;
1362   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1363   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1364   imulptr(scrReg, scrReg, RTMAbortRatio);
1365   cmpptr(tmpReg, scrReg);
1366   jccb(Assembler::below, L_check_always_rtm1);
1367   if (method_data != NULL) {
1368     // set rtm_state to "no rtm" in MDO
1369     mov_metadata(tmpReg, method_data);
1370     if (os::is_MP()) {
1371       lock();
1372     }
1373     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1374   }
1375   jmpb(L_done);
1376   bind(L_check_always_rtm1);
1377   // Reload RTMLockingCounters* address
1378   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1379   bind(L_check_always_rtm2);
1380   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1381   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1382   jccb(Assembler::below, L_done);
1383   if (method_data != NULL) {
1384     // set rtm_state to "always rtm" in MDO
1385     mov_metadata(tmpReg, method_data);
1386     if (os::is_MP()) {
1387       lock();
1388     }
1389     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1390   }
1391   bind(L_done);
1392 }
1393 
1394 // Update counters and perform abort ratio calculation
1395 // input:  abort_status_Reg
1396 // rtm_counters_Reg, flags are killed
1397 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1398                                    Register rtm_counters_Reg,
1399                                    RTMLockingCounters* rtm_counters,
1400                                    Metadata* method_data,
1401                                    bool profile_rtm) {
1402 
1403   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1404   // update rtm counters based on rax value at abort
1405   // reads abort_status_Reg, updates flags
1406   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1407   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1408   if (profile_rtm) {
1409     // Save abort status because abort_status_Reg is used by following code.
1410     if (RTMRetryCount > 0) {
1411       push(abort_status_Reg);
1412     }
1413     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1414     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1415     // restore abort status
1416     if (RTMRetryCount > 0) {
1417       pop(abort_status_Reg);
1418     }
1419   }
1420 }
1421 
1422 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1423 // inputs: retry_count_Reg
1424 //       : abort_status_Reg
1425 // output: retry_count_Reg decremented by 1
1426 // flags are killed
1427 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1428   Label doneRetry;
1429   assert(abort_status_Reg == rax, "");
1430   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1431   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1432   // if reason is in 0x6 and retry count != 0 then retry
1433   andptr(abort_status_Reg, 0x6);
1434   jccb(Assembler::zero, doneRetry);
1435   testl(retry_count_Reg, retry_count_Reg);
1436   jccb(Assembler::zero, doneRetry);
1437   pause();
1438   decrementl(retry_count_Reg);
1439   jmp(retryLabel);
1440   bind(doneRetry);
1441 }
1442 
1443 // Spin and retry if lock is busy,
1444 // inputs: box_Reg (monitor address)
1445 //       : retry_count_Reg
1446 // output: retry_count_Reg decremented by 1
1447 //       : clear z flag if retry count exceeded
1448 // tmp_Reg, scr_Reg, flags are killed
1449 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1450                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1451   Label SpinLoop, SpinExit, doneRetry;
1452   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1453 
1454   testl(retry_count_Reg, retry_count_Reg);
1455   jccb(Assembler::zero, doneRetry);
1456   decrementl(retry_count_Reg);
1457   movptr(scr_Reg, RTMSpinLoopCount);
1458 
1459   bind(SpinLoop);
1460   pause();
1461   decrementl(scr_Reg);
1462   jccb(Assembler::lessEqual, SpinExit);
1463   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1464   testptr(tmp_Reg, tmp_Reg);
1465   jccb(Assembler::notZero, SpinLoop);
1466 
1467   bind(SpinExit);
1468   jmp(retryLabel);
1469   bind(doneRetry);
1470   incrementl(retry_count_Reg); // clear z flag
1471 }
1472 
1473 // Use RTM for normal stack locks
1474 // Input: objReg (object to lock)
1475 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1476                                        Register retry_on_abort_count_Reg,
1477                                        RTMLockingCounters* stack_rtm_counters,
1478                                        Metadata* method_data, bool profile_rtm,
1479                                        Label& DONE_LABEL, Label& IsInflated) {
1480   assert(UseRTMForStackLocks, "why call this otherwise?");
1481   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1482   assert(tmpReg == rax, "");
1483   assert(scrReg == rdx, "");
1484   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1485 
1486   if (RTMRetryCount > 0) {
1487     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1488     bind(L_rtm_retry);
1489   }
1490   shenandoah_store_addr_check(objReg); // Access mark word
1491   movptr(tmpReg, Address(objReg, 0));
1492   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1493   jcc(Assembler::notZero, IsInflated);
1494 
1495   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1496     Label L_noincrement;
1497     if (RTMTotalCountIncrRate > 1) {
1498       // tmpReg, scrReg and flags are killed
1499       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1500     }
1501     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1502     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1503     bind(L_noincrement);
1504   }
1505   xbegin(L_on_abort);
1506   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1507   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1508   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1509   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1510 
1511   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1512   if (UseRTMXendForLockBusy) {
1513     xend();
1514     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1515     jmp(L_decrement_retry);
1516   }
1517   else {
1518     xabort(0);
1519   }
1520   bind(L_on_abort);
1521   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1522     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1523   }
1524   bind(L_decrement_retry);
1525   if (RTMRetryCount > 0) {
1526     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1527     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1528   }
1529 }
1530 
1531 // Use RTM for inflating locks
1532 // inputs: objReg (object to lock)
1533 //         boxReg (on-stack box address (displaced header location) - KILLED)
1534 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1535 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1536                                           Register scrReg, Register retry_on_busy_count_Reg,
1537                                           Register retry_on_abort_count_Reg,
1538                                           RTMLockingCounters* rtm_counters,
1539                                           Metadata* method_data, bool profile_rtm,
1540                                           Label& DONE_LABEL) {
1541   assert(UseRTMLocking, "why call this otherwise?");
1542   assert(tmpReg == rax, "");
1543   assert(scrReg == rdx, "");
1544   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1545   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1546 
1547   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1548   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1549   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1550 
1551   if (RTMRetryCount > 0) {
1552     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1553     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1554     bind(L_rtm_retry);
1555   }
1556   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1557     Label L_noincrement;
1558     if (RTMTotalCountIncrRate > 1) {
1559       // tmpReg, scrReg and flags are killed
1560       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1561     }
1562     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1563     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1564     bind(L_noincrement);
1565   }
1566   xbegin(L_on_abort);
1567   shenandoah_store_addr_check(objReg); // Access mark word
1568   movptr(tmpReg, Address(objReg, 0));
1569   movptr(tmpReg, Address(tmpReg, owner_offset));
1570   testptr(tmpReg, tmpReg);
1571   jcc(Assembler::zero, DONE_LABEL);
1572   if (UseRTMXendForLockBusy) {
1573     xend();
1574     jmp(L_decrement_retry);
1575   }
1576   else {
1577     xabort(0);
1578   }
1579   bind(L_on_abort);
1580   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1581   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1582     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1583   }
1584   if (RTMRetryCount > 0) {
1585     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1586     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1587   }
1588 
1589   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1590   testptr(tmpReg, tmpReg) ;
1591   jccb(Assembler::notZero, L_decrement_retry) ;
1592 
1593   // Appears unlocked - try to swing _owner from null to non-null.
1594   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1595 #ifdef _LP64
1596   Register threadReg = r15_thread;
1597 #else
1598   get_thread(scrReg);
1599   Register threadReg = scrReg;
1600 #endif
1601   if (os::is_MP()) {
1602     lock();
1603   }
1604   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1605 
1606   if (RTMRetryCount > 0) {
1607     // success done else retry
1608     jccb(Assembler::equal, DONE_LABEL) ;
1609     bind(L_decrement_retry);
1610     // Spin and retry if lock is busy.
1611     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1612   }
1613   else {
1614     bind(L_decrement_retry);
1615   }
1616 }
1617 
1618 #endif //  INCLUDE_RTM_OPT
1619 
1620 // Fast_Lock and Fast_Unlock used by C2
1621 
1622 // Because the transitions from emitted code to the runtime
1623 // monitorenter/exit helper stubs are so slow it's critical that
1624 // we inline both the stack-locking fast-path and the inflated fast path.
1625 //
1626 // See also: cmpFastLock and cmpFastUnlock.
1627 //
1628 // What follows is a specialized inline transliteration of the code
1629 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1630 // another option would be to emit TrySlowEnter and TrySlowExit methods
1631 // at startup-time.  These methods would accept arguments as
1632 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1633 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1634 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1635 // In practice, however, the # of lock sites is bounded and is usually small.
1636 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1637 // if the processor uses simple bimodal branch predictors keyed by EIP
1638 // Since the helper routines would be called from multiple synchronization
1639 // sites.
1640 //
1641 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1642 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1643 // to those specialized methods.  That'd give us a mostly platform-independent
1644 // implementation that the JITs could optimize and inline at their pleasure.
1645 // Done correctly, the only time we'd need to cross to native could would be
1646 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1647 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1648 // (b) explicit barriers or fence operations.
1649 //
1650 // TODO:
1651 //
1652 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1653 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1654 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1655 //    the lock operators would typically be faster than reifying Self.
1656 //
1657 // *  Ideally I'd define the primitives as:
1658 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1659 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1660 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1661 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1662 //    Furthermore the register assignments are overconstrained, possibly resulting in
1663 //    sub-optimal code near the synchronization site.
1664 //
1665 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1666 //    Alternately, use a better sp-proximity test.
1667 //
1668 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1669 //    Either one is sufficient to uniquely identify a thread.
1670 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1671 //
1672 // *  Intrinsify notify() and notifyAll() for the common cases where the
1673 //    object is locked by the calling thread but the waitlist is empty.
1674 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1675 //
1676 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1677 //    But beware of excessive branch density on AMD Opterons.
1678 //
1679 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1680 //    or failure of the fast-path.  If the fast-path fails then we pass
1681 //    control to the slow-path, typically in C.  In Fast_Lock and
1682 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1683 //    will emit a conditional branch immediately after the node.
1684 //    So we have branches to branches and lots of ICC.ZF games.
1685 //    Instead, it might be better to have C2 pass a "FailureLabel"
1686 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1687 //    will drop through the node.  ICC.ZF is undefined at exit.
1688 //    In the case of failure, the node will branch directly to the
1689 //    FailureLabel
1690 
1691 
1692 // obj: object to lock
1693 // box: on-stack box address (displaced header location) - KILLED
1694 // rax,: tmp -- KILLED
1695 // scr: tmp -- KILLED
1696 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1697                                Register scrReg, Register cx1Reg, Register cx2Reg,
1698                                BiasedLockingCounters* counters,
1699                                RTMLockingCounters* rtm_counters,
1700                                RTMLockingCounters* stack_rtm_counters,
1701                                Metadata* method_data,
1702                                bool use_rtm, bool profile_rtm) {
1703   // Ensure the register assignments are disjoint
1704   assert(tmpReg == rax, "");
1705 
1706   if (use_rtm) {
1707     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1708   } else {
1709     assert(cx1Reg == noreg, "");
1710     assert(cx2Reg == noreg, "");
1711     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1712   }
1713 
1714   shenandoah_store_addr_check(objReg); // Access mark word
1715 
1716   if (counters != NULL) {
1717     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1718   }
1719   if (EmitSync & 1) {
1720       // set box->dhw = markOopDesc::unused_mark()
1721       // Force all sync thru slow-path: slow_enter() and slow_exit()
1722       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1723       cmpptr (rsp, (int32_t)NULL_WORD);
1724   } else {
1725     // Possible cases that we'll encounter in fast_lock
1726     // ------------------------------------------------
1727     // * Inflated
1728     //    -- unlocked
1729     //    -- Locked
1730     //       = by self
1731     //       = by other
1732     // * biased
1733     //    -- by Self
1734     //    -- by other
1735     // * neutral
1736     // * stack-locked
1737     //    -- by self
1738     //       = sp-proximity test hits
1739     //       = sp-proximity test generates false-negative
1740     //    -- by other
1741     //
1742 
1743     Label IsInflated, DONE_LABEL;
1744 
1745     // it's stack-locked, biased or neutral
1746     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1747     // order to reduce the number of conditional branches in the most common cases.
1748     // Beware -- there's a subtle invariant that fetch of the markword
1749     // at [FETCH], below, will never observe a biased encoding (*101b).
1750     // If this invariant is not held we risk exclusion (safety) failure.
1751     if (UseBiasedLocking && !UseOptoBiasInlining) {
1752       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1753     }
1754 
1755 #if INCLUDE_RTM_OPT
1756     if (UseRTMForStackLocks && use_rtm) {
1757       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1758                         stack_rtm_counters, method_data, profile_rtm,
1759                         DONE_LABEL, IsInflated);
1760     }
1761 #endif // INCLUDE_RTM_OPT
1762 
1763     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1764     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1765     jccb_if_possible(Assembler::notZero, IsInflated);
1766 
1767     // Attempt stack-locking ...
1768     orptr (tmpReg, markOopDesc::unlocked_value);
1769     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1770     if (os::is_MP()) {
1771       lock();
1772     }
1773     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1774     if (counters != NULL) {
1775       cond_inc32(Assembler::equal,
1776                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1777     }
1778     jcc(Assembler::equal, DONE_LABEL);           // Success
1779 
1780     // Recursive locking.
1781     // The object is stack-locked: markword contains stack pointer to BasicLock.
1782     // Locked by current thread if difference with current SP is less than one page.
1783     subptr(tmpReg, rsp);
1784     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1785     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1786     movptr(Address(boxReg, 0), tmpReg);
1787     if (counters != NULL) {
1788       cond_inc32(Assembler::equal,
1789                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1790     }
1791     jmp(DONE_LABEL);
1792 
1793     bind(IsInflated);
1794     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1795 
1796 #if INCLUDE_RTM_OPT
1797     // Use the same RTM locking code in 32- and 64-bit VM.
1798     if (use_rtm) {
1799       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1800                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1801     } else {
1802 #endif // INCLUDE_RTM_OPT
1803 
1804 #ifndef _LP64
1805     // The object is inflated.
1806 
1807     // boxReg refers to the on-stack BasicLock in the current frame.
1808     // We'd like to write:
1809     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1810     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1811     // additional latency as we have another ST in the store buffer that must drain.
1812 
1813     if (EmitSync & 8192) {
1814        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1815        get_thread (scrReg);
1816        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1817        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1818        if (os::is_MP()) {
1819          lock();
1820        }
1821        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1822     } else
1823     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1824        // register juggle because we need tmpReg for cmpxchgptr below
1825        movptr(scrReg, boxReg);
1826        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1827 
1828        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1829        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1830           // prefetchw [eax + Offset(_owner)-2]
1831           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1832        }
1833 
1834        if ((EmitSync & 64) == 0) {
1835          // Optimistic form: consider XORL tmpReg,tmpReg
1836          movptr(tmpReg, NULL_WORD);
1837        } else {
1838          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1839          // Test-And-CAS instead of CAS
1840          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1841          testptr(tmpReg, tmpReg);                   // Locked ?
1842          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1843        }
1844 
1845        // Appears unlocked - try to swing _owner from null to non-null.
1846        // Ideally, I'd manifest "Self" with get_thread and then attempt
1847        // to CAS the register containing Self into m->Owner.
1848        // But we don't have enough registers, so instead we can either try to CAS
1849        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1850        // we later store "Self" into m->Owner.  Transiently storing a stack address
1851        // (rsp or the address of the box) into  m->owner is harmless.
1852        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1853        if (os::is_MP()) {
1854          lock();
1855        }
1856        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1857        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1858        // If we weren't able to swing _owner from NULL to the BasicLock
1859        // then take the slow path.
1860        jccb_if_possible(Assembler::notZero, DONE_LABEL);
1861        // update _owner from BasicLock to thread
1862        get_thread (scrReg);                    // beware: clobbers ICCs
1863        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1864        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1865 
1866        // If the CAS fails we can either retry or pass control to the slow-path.
1867        // We use the latter tactic.
1868        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1869        // If the CAS was successful ...
1870        //   Self has acquired the lock
1871        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1872        // Intentional fall-through into DONE_LABEL ...
1873     } else {
1874        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1875        movptr(boxReg, tmpReg);
1876 
1877        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1878        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1879           // prefetchw [eax + Offset(_owner)-2]
1880           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1881        }
1882 
1883        if ((EmitSync & 64) == 0) {
1884          // Optimistic form
1885          xorptr  (tmpReg, tmpReg);
1886        } else {
1887          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1888          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1889          testptr(tmpReg, tmpReg);                   // Locked ?
1890          jccb_if_possible(Assembler::notZero, DONE_LABEL);
1891        }
1892 
1893        // Appears unlocked - try to swing _owner from null to non-null.
1894        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1895        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1896        get_thread (scrReg);
1897        if (os::is_MP()) {
1898          lock();
1899        }
1900        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1901 
1902        // If the CAS fails we can either retry or pass control to the slow-path.
1903        // We use the latter tactic.
1904        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1905        // If the CAS was successful ...
1906        //   Self has acquired the lock
1907        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1908        // Intentional fall-through into DONE_LABEL ...
1909     }
1910 #else // _LP64
1911     // It's inflated
1912     movq(scrReg, tmpReg);
1913     xorq(tmpReg, tmpReg);
1914 
1915     if (os::is_MP()) {
1916       lock();
1917     }
1918     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1919     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1920     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1921     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1922     // Intentional fall-through into DONE_LABEL ...
1923     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1924 #endif // _LP64
1925 #if INCLUDE_RTM_OPT
1926     } // use_rtm()
1927 #endif
1928     // DONE_LABEL is a hot target - we'd really like to place it at the
1929     // start of cache line by padding with NOPs.
1930     // See the AMD and Intel software optimization manuals for the
1931     // most efficient "long" NOP encodings.
1932     // Unfortunately none of our alignment mechanisms suffice.
1933     bind(DONE_LABEL);
1934 
1935     // At DONE_LABEL the icc ZFlag is set as follows ...
1936     // Fast_Unlock uses the same protocol.
1937     // ZFlag == 1 -> Success
1938     // ZFlag == 0 -> Failure - force control through the slow-path
1939   }
1940 }
1941 
1942 // obj: object to unlock
1943 // box: box address (displaced header location), killed.  Must be EAX.
1944 // tmp: killed, cannot be obj nor box.
1945 //
1946 // Some commentary on balanced locking:
1947 //
1948 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1949 // Methods that don't have provably balanced locking are forced to run in the
1950 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1951 // The interpreter provides two properties:
1952 // I1:  At return-time the interpreter automatically and quietly unlocks any
1953 //      objects acquired the current activation (frame).  Recall that the
1954 //      interpreter maintains an on-stack list of locks currently held by
1955 //      a frame.
1956 // I2:  If a method attempts to unlock an object that is not held by the
1957 //      the frame the interpreter throws IMSX.
1958 //
1959 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1960 // B() doesn't have provably balanced locking so it runs in the interpreter.
1961 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1962 // is still locked by A().
1963 //
1964 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1965 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1966 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1967 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1968 // Arguably given that the spec legislates the JNI case as undefined our implementation
1969 // could reasonably *avoid* checking owner in Fast_Unlock().
1970 // In the interest of performance we elide m->Owner==Self check in unlock.
1971 // A perfectly viable alternative is to elide the owner check except when
1972 // Xcheck:jni is enabled.
1973 
1974 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1975   assert(boxReg == rax, "");
1976   assert_different_registers(objReg, boxReg, tmpReg);
1977 
1978   shenandoah_store_addr_check(objReg); // Access mark word
1979 
1980   if (EmitSync & 4) {
1981     // Disable - inhibit all inlining.  Force control through the slow-path
1982     cmpptr (rsp, 0);
1983   } else {
1984     Label DONE_LABEL, Stacked, CheckSucc;
1985 
1986     // Critically, the biased locking test must have precedence over
1987     // and appear before the (box->dhw == 0) recursive stack-lock test.
1988     if (UseBiasedLocking && !UseOptoBiasInlining) {
1989        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1990     }
1991 
1992 #if INCLUDE_RTM_OPT
1993     if (UseRTMForStackLocks && use_rtm) {
1994       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1995       Label L_regular_unlock;
1996       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1997       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1998       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1999       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
2000       xend();                                       // otherwise end...
2001       jmp(DONE_LABEL);                              // ... and we're done
2002       bind(L_regular_unlock);
2003     }
2004 #endif
2005 
2006     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2007     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2008     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
2009     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2010     jccb  (Assembler::zero, Stacked);
2011 
2012     // It's inflated.
2013 #if INCLUDE_RTM_OPT
2014     if (use_rtm) {
2015       Label L_regular_inflated_unlock;
2016       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2017       movptr(boxReg, Address(tmpReg, owner_offset));
2018       testptr(boxReg, boxReg);
2019       jccb(Assembler::notZero, L_regular_inflated_unlock);
2020       xend();
2021       jmpb_if_possible(DONE_LABEL);
2022       bind(L_regular_inflated_unlock);
2023     }
2024 #endif
2025 
2026     // Despite our balanced locking property we still check that m->_owner == Self
2027     // as java routines or native JNI code called by this thread might
2028     // have released the lock.
2029     // Refer to the comments in synchronizer.cpp for how we might encode extra
2030     // state in _succ so we can avoid fetching EntryList|cxq.
2031     //
2032     // I'd like to add more cases in fast_lock() and fast_unlock() --
2033     // such as recursive enter and exit -- but we have to be wary of
2034     // I$ bloat, T$ effects and BP$ effects.
2035     //
2036     // If there's no contention try a 1-0 exit.  That is, exit without
2037     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2038     // we detect and recover from the race that the 1-0 exit admits.
2039     //
2040     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2041     // before it STs null into _owner, releasing the lock.  Updates
2042     // to data protected by the critical section must be visible before
2043     // we drop the lock (and thus before any other thread could acquire
2044     // the lock and observe the fields protected by the lock).
2045     // IA32's memory-model is SPO, so STs are ordered with respect to
2046     // each other and there's no need for an explicit barrier (fence).
2047     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2048 #ifndef _LP64
2049     get_thread (boxReg);
2050     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2051       // prefetchw [ebx + Offset(_owner)-2]
2052       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2053     }
2054 
2055     // Note that we could employ various encoding schemes to reduce
2056     // the number of loads below (currently 4) to just 2 or 3.
2057     // Refer to the comments in synchronizer.cpp.
2058     // In practice the chain of fetches doesn't seem to impact performance, however.
2059     xorptr(boxReg, boxReg);
2060     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2061        // Attempt to reduce branch density - AMD's branch predictor.
2062        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2063        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2064        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2065        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2066        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2067        jmpb_if_possible(DONE_LABEL);
2068     } else {
2069        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2070        jccb_if_possible(Assembler::notZero, DONE_LABEL);
2071        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2072        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2073        jccb  (Assembler::notZero, CheckSucc);
2074        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2075        jmpb_if_possible(DONE_LABEL);
2076     }
2077 
2078     // The Following code fragment (EmitSync & 65536) improves the performance of
2079     // contended applications and contended synchronization microbenchmarks.
2080     // Unfortunately the emission of the code - even though not executed - causes regressions
2081     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2082     // with an equal number of never-executed NOPs results in the same regression.
2083     // We leave it off by default.
2084 
2085     if ((EmitSync & 65536) != 0) {
2086        Label LSuccess, LGoSlowPath ;
2087 
2088        bind  (CheckSucc);
2089 
2090        // Optional pre-test ... it's safe to elide this
2091        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2092        jccb(Assembler::zero, LGoSlowPath);
2093 
2094        // We have a classic Dekker-style idiom:
2095        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2096        // There are a number of ways to implement the barrier:
2097        // (1) lock:andl &m->_owner, 0
2098        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2099        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2100        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2101        // (2) If supported, an explicit MFENCE is appealing.
2102        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2103        //     particularly if the write-buffer is full as might be the case if
2104        //     if stores closely precede the fence or fence-equivalent instruction.
2105        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2106        //     as the situation has changed with Nehalem and Shanghai.
2107        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2108        //     The $lines underlying the top-of-stack should be in M-state.
2109        //     The locked add instruction is serializing, of course.
2110        // (4) Use xchg, which is serializing
2111        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2112        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2113        //     The integer condition codes will tell us if succ was 0.
2114        //     Since _succ and _owner should reside in the same $line and
2115        //     we just stored into _owner, it's likely that the $line
2116        //     remains in M-state for the lock:orl.
2117        //
2118        // We currently use (3), although it's likely that switching to (2)
2119        // is correct for the future.
2120 
2121        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2122        if (os::is_MP()) {
2123          lock(); addptr(Address(rsp, 0), 0);
2124        }
2125        // Ratify _succ remains non-null
2126        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2127        jccb  (Assembler::notZero, LSuccess);
2128 
2129        xorptr(boxReg, boxReg);                  // box is really EAX
2130        if (os::is_MP()) { lock(); }
2131        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2132        // There's no successor so we tried to regrab the lock with the
2133        // placeholder value. If that didn't work, then another thread
2134        // grabbed the lock so we're done (and exit was a success).
2135        jccb  (Assembler::notEqual, LSuccess);
2136        // Since we're low on registers we installed rsp as a placeholding in _owner.
2137        // Now install Self over rsp.  This is safe as we're transitioning from
2138        // non-null to non=null
2139        get_thread (boxReg);
2140        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2141        // Intentional fall-through into LGoSlowPath ...
2142 
2143        bind  (LGoSlowPath);
2144        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2145        jmpb_if_possible(DONE_LABEL);
2146 
2147        bind  (LSuccess);
2148        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2149        jmpb_if_possible(DONE_LABEL);
2150     }
2151 
2152     bind (Stacked);
2153     // It's not inflated and it's not recursively stack-locked and it's not biased.
2154     // It must be stack-locked.
2155     // Try to reset the header to displaced header.
2156     // The "box" value on the stack is stable, so we can reload
2157     // and be assured we observe the same value as above.
2158     movptr(tmpReg, Address(boxReg, 0));
2159     if (os::is_MP()) {
2160       lock();
2161     }
2162     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2163     // Intention fall-thru into DONE_LABEL
2164 
2165     // DONE_LABEL is a hot target - we'd really like to place it at the
2166     // start of cache line by padding with NOPs.
2167     // See the AMD and Intel software optimization manuals for the
2168     // most efficient "long" NOP encodings.
2169     // Unfortunately none of our alignment mechanisms suffice.
2170     if ((EmitSync & 65536) == 0) {
2171        bind (CheckSucc);
2172     }
2173 #else // _LP64
2174     // It's inflated
2175     if (EmitSync & 1024) {
2176       // Emit code to check that _owner == Self
2177       // We could fold the _owner test into subsequent code more efficiently
2178       // than using a stand-alone check, but since _owner checking is off by
2179       // default we don't bother. We also might consider predicating the
2180       // _owner==Self check on Xcheck:jni or running on a debug build.
2181       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2182       xorptr(boxReg, r15_thread);
2183     } else {
2184       xorptr(boxReg, boxReg);
2185     }
2186     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2187     jccb_if_possible(Assembler::notZero, DONE_LABEL);
2188     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2189     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2190     jccb  (Assembler::notZero, CheckSucc);
2191     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2192     jmpb_if_possible(DONE_LABEL);
2193 
2194     if ((EmitSync & 65536) == 0) {
2195       // Try to avoid passing control into the slow_path ...
2196       Label LSuccess, LGoSlowPath ;
2197       bind  (CheckSucc);
2198 
2199       // The following optional optimization can be elided if necessary
2200       // Effectively: if (succ == null) goto SlowPath
2201       // The code reduces the window for a race, however,
2202       // and thus benefits performance.
2203       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2204       jccb  (Assembler::zero, LGoSlowPath);
2205 
2206       xorptr(boxReg, boxReg);
2207       if ((EmitSync & 16) && os::is_MP()) {
2208         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2209       } else {
2210         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2211         if (os::is_MP()) {
2212           // Memory barrier/fence
2213           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2214           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2215           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2216           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2217           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2218           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2219           lock(); addl(Address(rsp, 0), 0);
2220         }
2221       }
2222       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2223       jccb  (Assembler::notZero, LSuccess);
2224 
2225       // Rare inopportune interleaving - race.
2226       // The successor vanished in the small window above.
2227       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2228       // We need to ensure progress and succession.
2229       // Try to reacquire the lock.
2230       // If that fails then the new owner is responsible for succession and this
2231       // thread needs to take no further action and can exit via the fast path (success).
2232       // If the re-acquire succeeds then pass control into the slow path.
2233       // As implemented, this latter mode is horrible because we generated more
2234       // coherence traffic on the lock *and* artifically extended the critical section
2235       // length while by virtue of passing control into the slow path.
2236 
2237       // box is really RAX -- the following CMPXCHG depends on that binding
2238       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2239       if (os::is_MP()) { lock(); }
2240       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2241       // There's no successor so we tried to regrab the lock.
2242       // If that didn't work, then another thread grabbed the
2243       // lock so we're done (and exit was a success).
2244       jccb  (Assembler::notEqual, LSuccess);
2245       // Intentional fall-through into slow-path
2246 
2247       bind  (LGoSlowPath);
2248       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2249       jmpb_if_possible(DONE_LABEL);
2250 
2251       bind  (LSuccess);
2252       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2253       jmpb_if_possible  (DONE_LABEL);
2254     }
2255 
2256     bind  (Stacked);
2257     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2258     if (os::is_MP()) { lock(); }
2259     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2260 
2261     if (EmitSync & 65536) {
2262        bind (CheckSucc);
2263     }
2264 #endif
2265     bind(DONE_LABEL);
2266   }
2267 }
2268 #endif // COMPILER2
2269 
2270 void MacroAssembler::c2bool(Register x) {
2271   // implements x == 0 ? 0 : 1
2272   // note: must only look at least-significant byte of x
2273   //       since C-style booleans are stored in one byte
2274   //       only! (was bug)
2275   andl(x, 0xFF);
2276   setb(Assembler::notZero, x);
2277 }
2278 
2279 // Wouldn't need if AddressLiteral version had new name
2280 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2281   Assembler::call(L, rtype);
2282 }
2283 
2284 void MacroAssembler::call(Register entry) {
2285   Assembler::call(entry);
2286 }
2287 
2288 void MacroAssembler::call(AddressLiteral entry) {
2289   if (reachable(entry)) {
2290     Assembler::call_literal(entry.target(), entry.rspec());
2291   } else {
2292     lea(rscratch1, entry);
2293     Assembler::call(rscratch1);
2294   }
2295 }
2296 
2297 void MacroAssembler::ic_call(address entry, jint method_index) {
2298   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2299   movptr(rax, (intptr_t)Universe::non_oop_word());
2300   call(AddressLiteral(entry, rh));
2301 }
2302 
2303 // Implementation of call_VM versions
2304 
2305 void MacroAssembler::call_VM(Register oop_result,
2306                              address entry_point,
2307                              bool check_exceptions) {
2308   Label C, E;
2309   call(C, relocInfo::none);
2310   jmp(E);
2311 
2312   bind(C);
2313   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2314   ret(0);
2315 
2316   bind(E);
2317 }
2318 
2319 void MacroAssembler::call_VM(Register oop_result,
2320                              address entry_point,
2321                              Register arg_1,
2322                              bool check_exceptions) {
2323   Label C, E;
2324   call(C, relocInfo::none);
2325   jmp(E);
2326 
2327   bind(C);
2328   pass_arg1(this, arg_1);
2329   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2330   ret(0);
2331 
2332   bind(E);
2333 }
2334 
2335 void MacroAssembler::call_VM(Register oop_result,
2336                              address entry_point,
2337                              Register arg_1,
2338                              Register arg_2,
2339                              bool check_exceptions) {
2340   Label C, E;
2341   call(C, relocInfo::none);
2342   jmp(E);
2343 
2344   bind(C);
2345 
2346   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2347 
2348   pass_arg2(this, arg_2);
2349   pass_arg1(this, arg_1);
2350   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2351   ret(0);
2352 
2353   bind(E);
2354 }
2355 
2356 void MacroAssembler::call_VM(Register oop_result,
2357                              address entry_point,
2358                              Register arg_1,
2359                              Register arg_2,
2360                              Register arg_3,
2361                              bool check_exceptions) {
2362   Label C, E;
2363   call(C, relocInfo::none);
2364   jmp(E);
2365 
2366   bind(C);
2367 
2368   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2369   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2370   pass_arg3(this, arg_3);
2371 
2372   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2373   pass_arg2(this, arg_2);
2374 
2375   pass_arg1(this, arg_1);
2376   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2377   ret(0);
2378 
2379   bind(E);
2380 }
2381 
2382 void MacroAssembler::call_VM(Register oop_result,
2383                              Register last_java_sp,
2384                              address entry_point,
2385                              int number_of_arguments,
2386                              bool check_exceptions) {
2387   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2388   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, 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                              bool check_exceptions) {
2396   pass_arg1(this, arg_1);
2397   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2398 }
2399 
2400 void MacroAssembler::call_VM(Register oop_result,
2401                              Register last_java_sp,
2402                              address entry_point,
2403                              Register arg_1,
2404                              Register arg_2,
2405                              bool check_exceptions) {
2406 
2407   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2408   pass_arg2(this, arg_2);
2409   pass_arg1(this, arg_1);
2410   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2411 }
2412 
2413 void MacroAssembler::call_VM(Register oop_result,
2414                              Register last_java_sp,
2415                              address entry_point,
2416                              Register arg_1,
2417                              Register arg_2,
2418                              Register arg_3,
2419                              bool check_exceptions) {
2420   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2421   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2422   pass_arg3(this, arg_3);
2423   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2424   pass_arg2(this, arg_2);
2425   pass_arg1(this, arg_1);
2426   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2427 }
2428 
2429 void MacroAssembler::super_call_VM(Register oop_result,
2430                                    Register last_java_sp,
2431                                    address entry_point,
2432                                    int number_of_arguments,
2433                                    bool check_exceptions) {
2434   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2435   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, 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                                    bool check_exceptions) {
2443   pass_arg1(this, arg_1);
2444   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2445 }
2446 
2447 void MacroAssembler::super_call_VM(Register oop_result,
2448                                    Register last_java_sp,
2449                                    address entry_point,
2450                                    Register arg_1,
2451                                    Register arg_2,
2452                                    bool check_exceptions) {
2453 
2454   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2455   pass_arg2(this, arg_2);
2456   pass_arg1(this, arg_1);
2457   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2458 }
2459 
2460 void MacroAssembler::super_call_VM(Register oop_result,
2461                                    Register last_java_sp,
2462                                    address entry_point,
2463                                    Register arg_1,
2464                                    Register arg_2,
2465                                    Register arg_3,
2466                                    bool check_exceptions) {
2467   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2468   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2469   pass_arg3(this, arg_3);
2470   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2471   pass_arg2(this, arg_2);
2472   pass_arg1(this, arg_1);
2473   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2474 }
2475 
2476 void MacroAssembler::call_VM_base(Register oop_result,
2477                                   Register java_thread,
2478                                   Register last_java_sp,
2479                                   address  entry_point,
2480                                   int      number_of_arguments,
2481                                   bool     check_exceptions) {
2482   // determine java_thread register
2483   if (!java_thread->is_valid()) {
2484 #ifdef _LP64
2485     java_thread = r15_thread;
2486 #else
2487     java_thread = rdi;
2488     get_thread(java_thread);
2489 #endif // LP64
2490   }
2491   // determine last_java_sp register
2492   if (!last_java_sp->is_valid()) {
2493     last_java_sp = rsp;
2494   }
2495   // debugging support
2496   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2497   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2498 #ifdef ASSERT
2499   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2500   // r12 is the heapbase.
2501   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2502 #endif // ASSERT
2503 
2504   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2505   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2506 
2507   // push java thread (becomes first argument of C function)
2508 
2509   NOT_LP64(push(java_thread); number_of_arguments++);
2510   LP64_ONLY(mov(c_rarg0, r15_thread));
2511 
2512   // set last Java frame before call
2513   assert(last_java_sp != rbp, "can't use ebp/rbp");
2514 
2515   // Only interpreter should have to set fp
2516   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2517 
2518   // do the call, remove parameters
2519   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2520 
2521   // restore the thread (cannot use the pushed argument since arguments
2522   // may be overwritten by C code generated by an optimizing compiler);
2523   // however can use the register value directly if it is callee saved.
2524   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2525     // rdi & rsi (also r15) are callee saved -> nothing to do
2526 #ifdef ASSERT
2527     guarantee(java_thread != rax, "change this code");
2528     push(rax);
2529     { Label L;
2530       get_thread(rax);
2531       cmpptr(java_thread, rax);
2532       jcc(Assembler::equal, L);
2533       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2534       bind(L);
2535     }
2536     pop(rax);
2537 #endif
2538   } else {
2539     get_thread(java_thread);
2540   }
2541   // reset last Java frame
2542   // Only interpreter should have to clear fp
2543   reset_last_Java_frame(java_thread, true);
2544 
2545    // C++ interp handles this in the interpreter
2546   check_and_handle_popframe(java_thread);
2547   check_and_handle_earlyret(java_thread);
2548 
2549   if (check_exceptions) {
2550     // check for pending exceptions (java_thread is set upon return)
2551     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2552 #ifndef _LP64
2553     jump_cc(Assembler::notEqual,
2554             RuntimeAddress(StubRoutines::forward_exception_entry()));
2555 #else
2556     // This used to conditionally jump to forward_exception however it is
2557     // possible if we relocate that the branch will not reach. So we must jump
2558     // around so we can always reach
2559 
2560     Label ok;
2561     jcc(Assembler::equal, ok);
2562     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2563     bind(ok);
2564 #endif // LP64
2565   }
2566 
2567   // get oop result if there is one and reset the value in the thread
2568   if (oop_result->is_valid()) {
2569     get_vm_result(oop_result, java_thread);
2570   }
2571 }
2572 
2573 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2574 
2575   // Calculate the value for last_Java_sp
2576   // somewhat subtle. call_VM does an intermediate call
2577   // which places a return address on the stack just under the
2578   // stack pointer as the user finsihed with it. This allows
2579   // use to retrieve last_Java_pc from last_Java_sp[-1].
2580   // On 32bit we then have to push additional args on the stack to accomplish
2581   // the actual requested call. On 64bit call_VM only can use register args
2582   // so the only extra space is the return address that call_VM created.
2583   // This hopefully explains the calculations here.
2584 
2585 #ifdef _LP64
2586   // We've pushed one address, correct last_Java_sp
2587   lea(rax, Address(rsp, wordSize));
2588 #else
2589   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2590 #endif // LP64
2591 
2592   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2593 
2594 }
2595 
2596 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2597 void MacroAssembler::call_VM_leaf0(address entry_point) {
2598   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2599 }
2600 
2601 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2602   call_VM_leaf_base(entry_point, number_of_arguments);
2603 }
2604 
2605 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2606   pass_arg0(this, arg_0);
2607   call_VM_leaf(entry_point, 1);
2608 }
2609 
2610 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2611 
2612   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2613   pass_arg1(this, arg_1);
2614   pass_arg0(this, arg_0);
2615   call_VM_leaf(entry_point, 2);
2616 }
2617 
2618 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2619   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2620   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2621   pass_arg2(this, arg_2);
2622   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2623   pass_arg1(this, arg_1);
2624   pass_arg0(this, arg_0);
2625   call_VM_leaf(entry_point, 3);
2626 }
2627 
2628 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2629   pass_arg0(this, arg_0);
2630   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2631 }
2632 
2633 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2634 
2635   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2636   pass_arg1(this, arg_1);
2637   pass_arg0(this, arg_0);
2638   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2639 }
2640 
2641 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2642   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2643   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2644   pass_arg2(this, arg_2);
2645   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2646   pass_arg1(this, arg_1);
2647   pass_arg0(this, arg_0);
2648   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2649 }
2650 
2651 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2652   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2653   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2654   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2655   pass_arg3(this, arg_3);
2656   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2657   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2658   pass_arg2(this, arg_2);
2659   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2660   pass_arg1(this, arg_1);
2661   pass_arg0(this, arg_0);
2662   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2663 }
2664 
2665 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2666   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2667   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2668   verify_oop(oop_result, "broken oop in call_VM_base");
2669 }
2670 
2671 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2672   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2673   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2674 }
2675 
2676 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2677 }
2678 
2679 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2680 }
2681 
2682 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2683   if (reachable(src1)) {
2684     cmpl(as_Address(src1), imm);
2685   } else {
2686     lea(rscratch1, src1);
2687     cmpl(Address(rscratch1, 0), imm);
2688   }
2689 }
2690 
2691 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2692   assert(!src2.is_lval(), "use cmpptr");
2693   if (reachable(src2)) {
2694     cmpl(src1, as_Address(src2));
2695   } else {
2696     lea(rscratch1, src2);
2697     cmpl(src1, Address(rscratch1, 0));
2698   }
2699 }
2700 
2701 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2702   Assembler::cmpl(src1, imm);
2703 }
2704 
2705 void MacroAssembler::cmp32(Register src1, Address src2) {
2706   Assembler::cmpl(src1, src2);
2707 }
2708 
2709 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2710   ucomisd(opr1, opr2);
2711 
2712   Label L;
2713   if (unordered_is_less) {
2714     movl(dst, -1);
2715     jcc(Assembler::parity, L);
2716     jcc(Assembler::below , L);
2717     movl(dst, 0);
2718     jcc(Assembler::equal , L);
2719     increment(dst);
2720   } else { // unordered is greater
2721     movl(dst, 1);
2722     jcc(Assembler::parity, L);
2723     jcc(Assembler::above , L);
2724     movl(dst, 0);
2725     jcc(Assembler::equal , L);
2726     decrementl(dst);
2727   }
2728   bind(L);
2729 }
2730 
2731 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2732   ucomiss(opr1, opr2);
2733 
2734   Label L;
2735   if (unordered_is_less) {
2736     movl(dst, -1);
2737     jcc(Assembler::parity, L);
2738     jcc(Assembler::below , L);
2739     movl(dst, 0);
2740     jcc(Assembler::equal , L);
2741     increment(dst);
2742   } else { // unordered is greater
2743     movl(dst, 1);
2744     jcc(Assembler::parity, L);
2745     jcc(Assembler::above , L);
2746     movl(dst, 0);
2747     jcc(Assembler::equal , L);
2748     decrementl(dst);
2749   }
2750   bind(L);
2751 }
2752 
2753 
2754 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2755   if (reachable(src1)) {
2756     cmpb(as_Address(src1), imm);
2757   } else {
2758     lea(rscratch1, src1);
2759     cmpb(Address(rscratch1, 0), imm);
2760   }
2761 }
2762 
2763 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2764 #ifdef _LP64
2765   if (src2.is_lval()) {
2766     movptr(rscratch1, src2);
2767     Assembler::cmpq(src1, rscratch1);
2768   } else if (reachable(src2)) {
2769     cmpq(src1, as_Address(src2));
2770   } else {
2771     lea(rscratch1, src2);
2772     Assembler::cmpq(src1, Address(rscratch1, 0));
2773   }
2774 #else
2775   if (src2.is_lval()) {
2776     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2777   } else {
2778     cmpl(src1, as_Address(src2));
2779   }
2780 #endif // _LP64
2781 }
2782 
2783 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2784   assert(src2.is_lval(), "not a mem-mem compare");
2785 #ifdef _LP64
2786   // moves src2's literal address
2787   movptr(rscratch1, src2);
2788   Assembler::cmpq(src1, rscratch1);
2789 #else
2790   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2791 #endif // _LP64
2792 }
2793 
2794 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2795   if (reachable(adr)) {
2796     if (os::is_MP())
2797       lock();
2798     cmpxchgptr(reg, as_Address(adr));
2799   } else {
2800     lea(rscratch1, adr);
2801     if (os::is_MP())
2802       lock();
2803     cmpxchgptr(reg, Address(rscratch1, 0));
2804   }
2805 }
2806 
2807 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2808   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2809 }
2810 
2811 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2812   if (reachable(src)) {
2813     Assembler::comisd(dst, as_Address(src));
2814   } else {
2815     lea(rscratch1, src);
2816     Assembler::comisd(dst, Address(rscratch1, 0));
2817   }
2818 }
2819 
2820 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2821   if (reachable(src)) {
2822     Assembler::comiss(dst, as_Address(src));
2823   } else {
2824     lea(rscratch1, src);
2825     Assembler::comiss(dst, Address(rscratch1, 0));
2826   }
2827 }
2828 
2829 
2830 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2831   Condition negated_cond = negate_condition(cond);
2832   Label L;
2833   jcc(negated_cond, L);
2834   pushf(); // Preserve flags
2835   atomic_incl(counter_addr);
2836   popf();
2837   bind(L);
2838 }
2839 
2840 int MacroAssembler::corrected_idivl(Register reg) {
2841   // Full implementation of Java idiv and irem; checks for
2842   // special case as described in JVM spec., p.243 & p.271.
2843   // The function returns the (pc) offset of the idivl
2844   // instruction - may be needed for implicit exceptions.
2845   //
2846   //         normal case                           special case
2847   //
2848   // input : rax,: dividend                         min_int
2849   //         reg: divisor   (may not be rax,/rdx)   -1
2850   //
2851   // output: rax,: quotient  (= rax, idiv reg)       min_int
2852   //         rdx: remainder (= rax, irem reg)       0
2853   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2854   const int min_int = 0x80000000;
2855   Label normal_case, special_case;
2856 
2857   // check for special case
2858   cmpl(rax, min_int);
2859   jcc(Assembler::notEqual, normal_case);
2860   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2861   cmpl(reg, -1);
2862   jcc(Assembler::equal, special_case);
2863 
2864   // handle normal case
2865   bind(normal_case);
2866   cdql();
2867   int idivl_offset = offset();
2868   idivl(reg);
2869 
2870   // normal and special case exit
2871   bind(special_case);
2872 
2873   return idivl_offset;
2874 }
2875 
2876 
2877 
2878 void MacroAssembler::decrementl(Register reg, int value) {
2879   if (value == min_jint) {subl(reg, value) ; return; }
2880   if (value <  0) { incrementl(reg, -value); return; }
2881   if (value == 0) {                        ; return; }
2882   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2883   /* else */      { subl(reg, value)       ; return; }
2884 }
2885 
2886 void MacroAssembler::decrementl(Address dst, int value) {
2887   if (value == min_jint) {subl(dst, value) ; return; }
2888   if (value <  0) { incrementl(dst, -value); return; }
2889   if (value == 0) {                        ; return; }
2890   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2891   /* else */      { subl(dst, value)       ; return; }
2892 }
2893 
2894 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2895   assert (shift_value > 0, "illegal shift value");
2896   Label _is_positive;
2897   testl (reg, reg);
2898   jcc (Assembler::positive, _is_positive);
2899   int offset = (1 << shift_value) - 1 ;
2900 
2901   if (offset == 1) {
2902     incrementl(reg);
2903   } else {
2904     addl(reg, offset);
2905   }
2906 
2907   bind (_is_positive);
2908   sarl(reg, shift_value);
2909 }
2910 
2911 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2912   if (reachable(src)) {
2913     Assembler::divsd(dst, as_Address(src));
2914   } else {
2915     lea(rscratch1, src);
2916     Assembler::divsd(dst, Address(rscratch1, 0));
2917   }
2918 }
2919 
2920 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2921   if (reachable(src)) {
2922     Assembler::divss(dst, as_Address(src));
2923   } else {
2924     lea(rscratch1, src);
2925     Assembler::divss(dst, Address(rscratch1, 0));
2926   }
2927 }
2928 
2929 // !defined(COMPILER2) is because of stupid core builds
2930 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2931 void MacroAssembler::empty_FPU_stack() {
2932   if (VM_Version::supports_mmx()) {
2933     emms();
2934   } else {
2935     for (int i = 8; i-- > 0; ) ffree(i);
2936   }
2937 }
2938 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2939 
2940 
2941 // Defines obj, preserves var_size_in_bytes
2942 void MacroAssembler::eden_allocate(Register obj,
2943                                    Register var_size_in_bytes,
2944                                    int con_size_in_bytes,
2945                                    Register t1,
2946                                    Label& slow_case) {
2947   assert(obj == rax, "obj must be in rax, for cmpxchg");
2948   assert_different_registers(obj, var_size_in_bytes, t1);
2949   if (!Universe::heap()->supports_inline_contig_alloc()) {
2950     jmp(slow_case);
2951   } else {
2952     Register end = t1;
2953     Label retry;
2954     bind(retry);
2955     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2956     movptr(obj, heap_top);
2957     if (var_size_in_bytes == noreg) {
2958       lea(end, Address(obj, con_size_in_bytes));
2959     } else {
2960       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2961     }
2962     // if end < obj then we wrapped around => object too long => slow case
2963     cmpptr(end, obj);
2964     jcc(Assembler::below, slow_case);
2965     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2966     jcc(Assembler::above, slow_case);
2967     // Compare obj with the top addr, and if still equal, store the new top addr in
2968     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2969     // it otherwise. Use lock prefix for atomicity on MPs.
2970     locked_cmpxchgptr(end, heap_top);
2971     jcc(Assembler::notEqual, retry);
2972   }
2973 }
2974 
2975 void MacroAssembler::enter() {
2976   push(rbp);
2977   mov(rbp, rsp);
2978 }
2979 
2980 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2981 void MacroAssembler::fat_nop() {
2982   if (UseAddressNop) {
2983     addr_nop_5();
2984   } else {
2985     emit_int8(0x26); // es:
2986     emit_int8(0x2e); // cs:
2987     emit_int8(0x64); // fs:
2988     emit_int8(0x65); // gs:
2989     emit_int8((unsigned char)0x90);
2990   }
2991 }
2992 
2993 void MacroAssembler::fcmp(Register tmp) {
2994   fcmp(tmp, 1, true, true);
2995 }
2996 
2997 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2998   assert(!pop_right || pop_left, "usage error");
2999   if (VM_Version::supports_cmov()) {
3000     assert(tmp == noreg, "unneeded temp");
3001     if (pop_left) {
3002       fucomip(index);
3003     } else {
3004       fucomi(index);
3005     }
3006     if (pop_right) {
3007       fpop();
3008     }
3009   } else {
3010     assert(tmp != noreg, "need temp");
3011     if (pop_left) {
3012       if (pop_right) {
3013         fcompp();
3014       } else {
3015         fcomp(index);
3016       }
3017     } else {
3018       fcom(index);
3019     }
3020     // convert FPU condition into eflags condition via rax,
3021     save_rax(tmp);
3022     fwait(); fnstsw_ax();
3023     sahf();
3024     restore_rax(tmp);
3025   }
3026   // condition codes set as follows:
3027   //
3028   // CF (corresponds to C0) if x < y
3029   // PF (corresponds to C2) if unordered
3030   // ZF (corresponds to C3) if x = y
3031 }
3032 
3033 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3034   fcmp2int(dst, unordered_is_less, 1, true, true);
3035 }
3036 
3037 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3038   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3039   Label L;
3040   if (unordered_is_less) {
3041     movl(dst, -1);
3042     jcc(Assembler::parity, L);
3043     jcc(Assembler::below , L);
3044     movl(dst, 0);
3045     jcc(Assembler::equal , L);
3046     increment(dst);
3047   } else { // unordered is greater
3048     movl(dst, 1);
3049     jcc(Assembler::parity, L);
3050     jcc(Assembler::above , L);
3051     movl(dst, 0);
3052     jcc(Assembler::equal , L);
3053     decrementl(dst);
3054   }
3055   bind(L);
3056 }
3057 
3058 void MacroAssembler::fld_d(AddressLiteral src) {
3059   fld_d(as_Address(src));
3060 }
3061 
3062 void MacroAssembler::fld_s(AddressLiteral src) {
3063   fld_s(as_Address(src));
3064 }
3065 
3066 void MacroAssembler::fld_x(AddressLiteral src) {
3067   Assembler::fld_x(as_Address(src));
3068 }
3069 
3070 void MacroAssembler::fldcw(AddressLiteral src) {
3071   Assembler::fldcw(as_Address(src));
3072 }
3073 
3074 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3075   if (reachable(src)) {
3076     Assembler::mulpd(dst, as_Address(src));
3077   } else {
3078     lea(rscratch1, src);
3079     Assembler::mulpd(dst, Address(rscratch1, 0));
3080   }
3081 }
3082 
3083 void MacroAssembler::increase_precision() {
3084   subptr(rsp, BytesPerWord);
3085   fnstcw(Address(rsp, 0));
3086   movl(rax, Address(rsp, 0));
3087   orl(rax, 0x300);
3088   push(rax);
3089   fldcw(Address(rsp, 0));
3090   pop(rax);
3091 }
3092 
3093 void MacroAssembler::restore_precision() {
3094   fldcw(Address(rsp, 0));
3095   addptr(rsp, BytesPerWord);
3096 }
3097 
3098 void MacroAssembler::fpop() {
3099   ffree();
3100   fincstp();
3101 }
3102 
3103 void MacroAssembler::load_float(Address src) {
3104   if (UseSSE >= 1) {
3105     movflt(xmm0, src);
3106   } else {
3107     LP64_ONLY(ShouldNotReachHere());
3108     NOT_LP64(fld_s(src));
3109   }
3110 }
3111 
3112 void MacroAssembler::store_float(Address dst) {
3113   if (UseSSE >= 1) {
3114     movflt(dst, xmm0);
3115   } else {
3116     LP64_ONLY(ShouldNotReachHere());
3117     NOT_LP64(fstp_s(dst));
3118   }
3119 }
3120 
3121 void MacroAssembler::load_double(Address src) {
3122   if (UseSSE >= 2) {
3123     movdbl(xmm0, src);
3124   } else {
3125     LP64_ONLY(ShouldNotReachHere());
3126     NOT_LP64(fld_d(src));
3127   }
3128 }
3129 
3130 void MacroAssembler::store_double(Address dst) {
3131   if (UseSSE >= 2) {
3132     movdbl(dst, xmm0);
3133   } else {
3134     LP64_ONLY(ShouldNotReachHere());
3135     NOT_LP64(fstp_d(dst));
3136   }
3137 }
3138 
3139 void MacroAssembler::fremr(Register tmp) {
3140   save_rax(tmp);
3141   { Label L;
3142     bind(L);
3143     fprem();
3144     fwait(); fnstsw_ax();
3145 #ifdef _LP64
3146     testl(rax, 0x400);
3147     jcc(Assembler::notEqual, L);
3148 #else
3149     sahf();
3150     jcc(Assembler::parity, L);
3151 #endif // _LP64
3152   }
3153   restore_rax(tmp);
3154   // Result is in ST0.
3155   // Note: fxch & fpop to get rid of ST1
3156   // (otherwise FPU stack could overflow eventually)
3157   fxch(1);
3158   fpop();
3159 }
3160 
3161 
3162 void MacroAssembler::incrementl(AddressLiteral dst) {
3163   if (reachable(dst)) {
3164     incrementl(as_Address(dst));
3165   } else {
3166     lea(rscratch1, dst);
3167     incrementl(Address(rscratch1, 0));
3168   }
3169 }
3170 
3171 void MacroAssembler::incrementl(ArrayAddress dst) {
3172   incrementl(as_Address(dst));
3173 }
3174 
3175 void MacroAssembler::incrementl(Register reg, int value) {
3176   if (value == min_jint) {addl(reg, value) ; return; }
3177   if (value <  0) { decrementl(reg, -value); return; }
3178   if (value == 0) {                        ; return; }
3179   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3180   /* else */      { addl(reg, value)       ; return; }
3181 }
3182 
3183 void MacroAssembler::incrementl(Address dst, int value) {
3184   if (value == min_jint) {addl(dst, value) ; return; }
3185   if (value <  0) { decrementl(dst, -value); return; }
3186   if (value == 0) {                        ; return; }
3187   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3188   /* else */      { addl(dst, value)       ; return; }
3189 }
3190 
3191 void MacroAssembler::jump(AddressLiteral dst) {
3192   if (reachable(dst)) {
3193     jmp_literal(dst.target(), dst.rspec());
3194   } else {
3195     lea(rscratch1, dst);
3196     jmp(rscratch1);
3197   }
3198 }
3199 
3200 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3201   if (reachable(dst)) {
3202     InstructionMark im(this);
3203     relocate(dst.reloc());
3204     const int short_size = 2;
3205     const int long_size = 6;
3206     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3207     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3208       // 0111 tttn #8-bit disp
3209       emit_int8(0x70 | cc);
3210       emit_int8((offs - short_size) & 0xFF);
3211     } else {
3212       // 0000 1111 1000 tttn #32-bit disp
3213       emit_int8(0x0F);
3214       emit_int8((unsigned char)(0x80 | cc));
3215       emit_int32(offs - long_size);
3216     }
3217   } else {
3218 #ifdef ASSERT
3219     warning("reversing conditional branch");
3220 #endif /* ASSERT */
3221     Label skip;
3222     jccb(reverse[cc], skip);
3223     lea(rscratch1, dst);
3224     Assembler::jmp(rscratch1);
3225     bind(skip);
3226   }
3227 }
3228 
3229 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3230   if (reachable(src)) {
3231     Assembler::ldmxcsr(as_Address(src));
3232   } else {
3233     lea(rscratch1, src);
3234     Assembler::ldmxcsr(Address(rscratch1, 0));
3235   }
3236 }
3237 
3238 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3239   int off;
3240   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3241     off = offset();
3242     movsbl(dst, src); // movsxb
3243   } else {
3244     off = load_unsigned_byte(dst, src);
3245     shll(dst, 24);
3246     sarl(dst, 24);
3247   }
3248   return off;
3249 }
3250 
3251 // Note: load_signed_short used to be called load_signed_word.
3252 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3253 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3254 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3255 int MacroAssembler::load_signed_short(Register dst, Address src) {
3256   int off;
3257   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3258     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3259     // version but this is what 64bit has always done. This seems to imply
3260     // that users are only using 32bits worth.
3261     off = offset();
3262     movswl(dst, src); // movsxw
3263   } else {
3264     off = load_unsigned_short(dst, src);
3265     shll(dst, 16);
3266     sarl(dst, 16);
3267   }
3268   return off;
3269 }
3270 
3271 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3272   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3273   // and "3.9 Partial Register Penalties", p. 22).
3274   int off;
3275   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3276     off = offset();
3277     movzbl(dst, src); // movzxb
3278   } else {
3279     xorl(dst, dst);
3280     off = offset();
3281     movb(dst, src);
3282   }
3283   return off;
3284 }
3285 
3286 // Note: load_unsigned_short used to be called load_unsigned_word.
3287 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3288   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3289   // and "3.9 Partial Register Penalties", p. 22).
3290   int off;
3291   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3292     off = offset();
3293     movzwl(dst, src); // movzxw
3294   } else {
3295     xorl(dst, dst);
3296     off = offset();
3297     movw(dst, src);
3298   }
3299   return off;
3300 }
3301 
3302 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3303   switch (size_in_bytes) {
3304 #ifndef _LP64
3305   case  8:
3306     assert(dst2 != noreg, "second dest register required");
3307     movl(dst,  src);
3308     movl(dst2, src.plus_disp(BytesPerInt));
3309     break;
3310 #else
3311   case  8:  movq(dst, src); break;
3312 #endif
3313   case  4:  movl(dst, src); break;
3314   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3315   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3316   default:  ShouldNotReachHere();
3317   }
3318 }
3319 
3320 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3321   switch (size_in_bytes) {
3322 #ifndef _LP64
3323   case  8:
3324     assert(src2 != noreg, "second source register required");
3325     movl(dst,                        src);
3326     movl(dst.plus_disp(BytesPerInt), src2);
3327     break;
3328 #else
3329   case  8:  movq(dst, src); break;
3330 #endif
3331   case  4:  movl(dst, src); break;
3332   case  2:  movw(dst, src); break;
3333   case  1:  movb(dst, src); break;
3334   default:  ShouldNotReachHere();
3335   }
3336 }
3337 
3338 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3339   if (reachable(dst)) {
3340     movl(as_Address(dst), src);
3341   } else {
3342     lea(rscratch1, dst);
3343     movl(Address(rscratch1, 0), src);
3344   }
3345 }
3346 
3347 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3348   if (reachable(src)) {
3349     movl(dst, as_Address(src));
3350   } else {
3351     lea(rscratch1, src);
3352     movl(dst, Address(rscratch1, 0));
3353   }
3354 }
3355 
3356 // C++ bool manipulation
3357 
3358 void MacroAssembler::movbool(Register dst, Address src) {
3359   if(sizeof(bool) == 1)
3360     movb(dst, src);
3361   else if(sizeof(bool) == 2)
3362     movw(dst, src);
3363   else if(sizeof(bool) == 4)
3364     movl(dst, src);
3365   else
3366     // unsupported
3367     ShouldNotReachHere();
3368 }
3369 
3370 void MacroAssembler::movbool(Address dst, bool boolconst) {
3371   if(sizeof(bool) == 1)
3372     movb(dst, (int) boolconst);
3373   else if(sizeof(bool) == 2)
3374     movw(dst, (int) boolconst);
3375   else if(sizeof(bool) == 4)
3376     movl(dst, (int) boolconst);
3377   else
3378     // unsupported
3379     ShouldNotReachHere();
3380 }
3381 
3382 void MacroAssembler::movbool(Address dst, Register src) {
3383   if(sizeof(bool) == 1)
3384     movb(dst, src);
3385   else if(sizeof(bool) == 2)
3386     movw(dst, src);
3387   else if(sizeof(bool) == 4)
3388     movl(dst, src);
3389   else
3390     // unsupported
3391     ShouldNotReachHere();
3392 }
3393 
3394 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3395   movb(as_Address(dst), src);
3396 }
3397 
3398 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3399   if (reachable(src)) {
3400     movdl(dst, as_Address(src));
3401   } else {
3402     lea(rscratch1, src);
3403     movdl(dst, Address(rscratch1, 0));
3404   }
3405 }
3406 
3407 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3408   if (reachable(src)) {
3409     movq(dst, as_Address(src));
3410   } else {
3411     lea(rscratch1, src);
3412     movq(dst, Address(rscratch1, 0));
3413   }
3414 }
3415 
3416 void MacroAssembler::setvectmask(Register dst, Register src) {
3417   Assembler::movl(dst, 1);
3418   Assembler::shlxl(dst, dst, src);
3419   Assembler::decl(dst);
3420   Assembler::kmovdl(k1, dst);
3421   Assembler::movl(dst, src);
3422 }
3423 
3424 void MacroAssembler::restorevectmask() {
3425   Assembler::knotwl(k1, k0);
3426 }
3427 
3428 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3429   if (reachable(src)) {
3430     if (UseXmmLoadAndClearUpper) {
3431       movsd (dst, as_Address(src));
3432     } else {
3433       movlpd(dst, as_Address(src));
3434     }
3435   } else {
3436     lea(rscratch1, src);
3437     if (UseXmmLoadAndClearUpper) {
3438       movsd (dst, Address(rscratch1, 0));
3439     } else {
3440       movlpd(dst, Address(rscratch1, 0));
3441     }
3442   }
3443 }
3444 
3445 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3446   if (reachable(src)) {
3447     movss(dst, as_Address(src));
3448   } else {
3449     lea(rscratch1, src);
3450     movss(dst, Address(rscratch1, 0));
3451   }
3452 }
3453 
3454 void MacroAssembler::movptr(Register dst, Register src) {
3455   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3456 }
3457 
3458 void MacroAssembler::movptr(Register dst, Address src) {
3459   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3460 }
3461 
3462 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3463 void MacroAssembler::movptr(Register dst, intptr_t src) {
3464   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3465 }
3466 
3467 void MacroAssembler::movptr(Address dst, Register src) {
3468   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3469 }
3470 
3471 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3472   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3473     Assembler::vextractf32x4(dst, src, 0);
3474   } else {
3475     Assembler::movdqu(dst, src);
3476   }
3477 }
3478 
3479 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3480   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3481     Assembler::vinsertf32x4(dst, dst, src, 0);
3482   } else {
3483     Assembler::movdqu(dst, src);
3484   }
3485 }
3486 
3487 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3488   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3489     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3490   } else {
3491     Assembler::movdqu(dst, src);
3492   }
3493 }
3494 
3495 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3496   if (reachable(src)) {
3497     movdqu(dst, as_Address(src));
3498   } else {
3499     lea(rscratch1, src);
3500     movdqu(dst, Address(rscratch1, 0));
3501   }
3502 }
3503 
3504 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3505   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3506     vextractf64x4_low(dst, src);
3507   } else {
3508     Assembler::vmovdqu(dst, src);
3509   }
3510 }
3511 
3512 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3513   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3514     vinsertf64x4_low(dst, src);
3515   } else {
3516     Assembler::vmovdqu(dst, src);
3517   }
3518 }
3519 
3520 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3521   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3522     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3523   }
3524   else {
3525     Assembler::vmovdqu(dst, src);
3526   }
3527 }
3528 
3529 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3530   if (reachable(src)) {
3531     vmovdqu(dst, as_Address(src));
3532   }
3533   else {
3534     lea(rscratch1, src);
3535     vmovdqu(dst, Address(rscratch1, 0));
3536   }
3537 }
3538 
3539 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3540   if (reachable(src)) {
3541     Assembler::movdqa(dst, as_Address(src));
3542   } else {
3543     lea(rscratch1, src);
3544     Assembler::movdqa(dst, Address(rscratch1, 0));
3545   }
3546 }
3547 
3548 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3549   if (reachable(src)) {
3550     Assembler::movsd(dst, as_Address(src));
3551   } else {
3552     lea(rscratch1, src);
3553     Assembler::movsd(dst, Address(rscratch1, 0));
3554   }
3555 }
3556 
3557 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3558   if (reachable(src)) {
3559     Assembler::movss(dst, as_Address(src));
3560   } else {
3561     lea(rscratch1, src);
3562     Assembler::movss(dst, Address(rscratch1, 0));
3563   }
3564 }
3565 
3566 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3567   if (reachable(src)) {
3568     Assembler::mulsd(dst, as_Address(src));
3569   } else {
3570     lea(rscratch1, src);
3571     Assembler::mulsd(dst, Address(rscratch1, 0));
3572   }
3573 }
3574 
3575 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3576   if (reachable(src)) {
3577     Assembler::mulss(dst, as_Address(src));
3578   } else {
3579     lea(rscratch1, src);
3580     Assembler::mulss(dst, Address(rscratch1, 0));
3581   }
3582 }
3583 
3584 void MacroAssembler::null_check(Register reg, int offset) {
3585   if (needs_explicit_null_check(offset)) {
3586     // provoke OS NULL exception if reg = NULL by
3587     // accessing M[reg] w/o changing any (non-CC) registers
3588     // NOTE: cmpl is plenty here to provoke a segv
3589 
3590     if (ShenandoahVerifyReadsToFromSpace) {
3591       oopDesc::bs()->interpreter_read_barrier(this, reg);
3592     }
3593 
3594     cmpptr(rax, Address(reg, 0));
3595     // Note: should probably use testl(rax, Address(reg, 0));
3596     //       may be shorter code (however, this version of
3597     //       testl needs to be implemented first)
3598   } else {
3599     // nothing to do, (later) access of M[reg + offset]
3600     // will provoke OS NULL exception if reg = NULL
3601   }
3602 }
3603 
3604 void MacroAssembler::os_breakpoint() {
3605   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3606   // (e.g., MSVC can't call ps() otherwise)
3607   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3608 }
3609 
3610 #ifdef _LP64
3611 #define XSTATE_BV 0x200
3612 #endif
3613 
3614 void MacroAssembler::pop_CPU_state() {
3615   pop_FPU_state();
3616   pop_IU_state();
3617 }
3618 
3619 void MacroAssembler::pop_FPU_state() {
3620 #ifndef _LP64
3621   frstor(Address(rsp, 0));
3622 #else
3623   fxrstor(Address(rsp, 0));
3624 #endif
3625   addptr(rsp, FPUStateSizeInWords * wordSize);
3626 }
3627 
3628 void MacroAssembler::pop_IU_state() {
3629   popa();
3630   LP64_ONLY(addq(rsp, 8));
3631   popf();
3632 }
3633 
3634 // Save Integer and Float state
3635 // Warning: Stack must be 16 byte aligned (64bit)
3636 void MacroAssembler::push_CPU_state() {
3637   push_IU_state();
3638   push_FPU_state();
3639 }
3640 
3641 void MacroAssembler::push_FPU_state() {
3642   subptr(rsp, FPUStateSizeInWords * wordSize);
3643 #ifndef _LP64
3644   fnsave(Address(rsp, 0));
3645   fwait();
3646 #else
3647   fxsave(Address(rsp, 0));
3648 #endif // LP64
3649 }
3650 
3651 void MacroAssembler::push_IU_state() {
3652   // Push flags first because pusha kills them
3653   pushf();
3654   // Make sure rsp stays 16-byte aligned
3655   LP64_ONLY(subq(rsp, 8));
3656   pusha();
3657 }
3658 
3659 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3660   if (!java_thread->is_valid()) {
3661     java_thread = rdi;
3662     get_thread(java_thread);
3663   }
3664   // we must set sp to zero to clear frame
3665   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3666   if (clear_fp) {
3667     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3668   }
3669 
3670   // Always clear the pc because it could have been set by make_walkable()
3671   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3672 
3673 }
3674 
3675 void MacroAssembler::restore_rax(Register tmp) {
3676   if (tmp == noreg) pop(rax);
3677   else if (tmp != rax) mov(rax, tmp);
3678 }
3679 
3680 void MacroAssembler::round_to(Register reg, int modulus) {
3681   addptr(reg, modulus - 1);
3682   andptr(reg, -modulus);
3683 }
3684 
3685 void MacroAssembler::save_rax(Register tmp) {
3686   if (tmp == noreg) push(rax);
3687   else if (tmp != rax) mov(tmp, rax);
3688 }
3689 
3690 // Write serialization page so VM thread can do a pseudo remote membar.
3691 // We use the current thread pointer to calculate a thread specific
3692 // offset to write to within the page. This minimizes bus traffic
3693 // due to cache line collision.
3694 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3695   movl(tmp, thread);
3696   shrl(tmp, os::get_serialize_page_shift_count());
3697   andl(tmp, (os::vm_page_size() - sizeof(int)));
3698 
3699   Address index(noreg, tmp, Address::times_1);
3700   ExternalAddress page(os::get_memory_serialize_page());
3701 
3702   // Size of store must match masking code above
3703   movl(as_Address(ArrayAddress(page, index)), tmp);
3704 }
3705 
3706 // Special Shenandoah CAS implementation that handles false negatives
3707 // due to concurrent evacuation.
3708 void MacroAssembler::cmpxchg_oop_shenandoah(Register res, Address addr, Register oldval, Register newval,
3709                               bool exchange,
3710                               Register tmp1, Register tmp2) {
3711   assert (UseShenandoahGC, "Should only be used with Shenandoah");
3712   assert(oldval == rax, "must be in rax for implicit use in cmpxchg");
3713 
3714   Label retry, done;
3715 
3716   // Remember oldval for retry logic below
3717   if (UseCompressedOops) {
3718     movl(tmp1, oldval);
3719   } else {
3720     movptr(tmp1, oldval);
3721   }
3722 
3723   // Step 1. Try to CAS with given arguments. If successful, then we are done,
3724   // and can safely return.
3725   if (os::is_MP()) lock();
3726   if (UseCompressedOops) {
3727     cmpxchgl(newval, addr);
3728   } else {
3729     cmpxchgptr(newval, addr);
3730   }
3731   jcc(Assembler::equal, done, true);
3732 
3733   // Step 2. CAS had failed. This may be a false negative.
3734   //
3735   // The trouble comes when we compare the to-space pointer with the from-space
3736   // pointer to the same object. To resolve this, it will suffice to read both
3737   // oldval and the value from memory through the read barriers -- this will give
3738   // both to-space pointers. If they mismatch, then it was a legitimate failure.
3739   //
3740   if (UseCompressedOops) {
3741     decode_heap_oop(tmp1);
3742   }
3743   oopDesc::bs()->interpreter_read_barrier(this, tmp1);
3744 
3745   if (UseCompressedOops) {
3746     movl(tmp2, oldval);
3747     decode_heap_oop(tmp2);
3748   } else {
3749     movptr(tmp2, oldval);
3750   }
3751   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3752 
3753   cmpptr(tmp1, tmp2);
3754   jcc(Assembler::notEqual, done, true);
3755 
3756   // Step 3. Try to CAS again with resolved to-space pointers.
3757   //
3758   // Corner case: it may happen that somebody stored the from-space pointer
3759   // to memory while we were preparing for retry. Therefore, we can fail again
3760   // on retry, and so need to do this in loop, always re-reading the failure
3761   // witness through the read barrier.
3762   bind(retry);
3763   if (os::is_MP()) lock();
3764   if (UseCompressedOops) {
3765     cmpxchgl(newval, addr);
3766   } else {
3767     cmpxchgptr(newval, addr);
3768   }
3769   jcc(Assembler::equal, done, true);
3770 
3771   if (UseCompressedOops) {
3772     movl(tmp2, oldval);
3773     decode_heap_oop(tmp2);
3774   } else {
3775     movptr(tmp2, oldval);
3776   }
3777   oopDesc::bs()->interpreter_read_barrier(this, tmp2);
3778 
3779   cmpptr(tmp1, tmp2);
3780   jcc(Assembler::equal, retry, true);
3781 
3782   // Step 4. If we need a boolean result out of CAS, check the flag again,
3783   // and promote the result. Note that we handle the flag from both the CAS
3784   // itself and from the retry loop.
3785   bind(done);
3786   if (!exchange) {
3787     setb(Assembler::equal, res);
3788     movzbl(res, res);
3789   }
3790 }
3791 
3792 // Calls to C land
3793 //
3794 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3795 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3796 // has to be reset to 0. This is required to allow proper stack traversal.
3797 void MacroAssembler::set_last_Java_frame(Register java_thread,
3798                                          Register last_java_sp,
3799                                          Register last_java_fp,
3800                                          address  last_java_pc) {
3801   // determine java_thread register
3802   if (!java_thread->is_valid()) {
3803     java_thread = rdi;
3804     get_thread(java_thread);
3805   }
3806   // determine last_java_sp register
3807   if (!last_java_sp->is_valid()) {
3808     last_java_sp = rsp;
3809   }
3810 
3811   // last_java_fp is optional
3812 
3813   if (last_java_fp->is_valid()) {
3814     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3815   }
3816 
3817   // last_java_pc is optional
3818 
3819   if (last_java_pc != NULL) {
3820     lea(Address(java_thread,
3821                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3822         InternalAddress(last_java_pc));
3823 
3824   }
3825   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3826 }
3827 
3828 void MacroAssembler::shlptr(Register dst, int imm8) {
3829   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3830 }
3831 
3832 void MacroAssembler::shrptr(Register dst, int imm8) {
3833   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3834 }
3835 
3836 void MacroAssembler::sign_extend_byte(Register reg) {
3837   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3838     movsbl(reg, reg); // movsxb
3839   } else {
3840     shll(reg, 24);
3841     sarl(reg, 24);
3842   }
3843 }
3844 
3845 void MacroAssembler::sign_extend_short(Register reg) {
3846   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3847     movswl(reg, reg); // movsxw
3848   } else {
3849     shll(reg, 16);
3850     sarl(reg, 16);
3851   }
3852 }
3853 
3854 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3855   assert(reachable(src), "Address should be reachable");
3856   testl(dst, as_Address(src));
3857 }
3858 
3859 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3860   int dst_enc = dst->encoding();
3861   int src_enc = src->encoding();
3862   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3863     Assembler::pcmpeqb(dst, src);
3864   } else if ((dst_enc < 16) && (src_enc < 16)) {
3865     Assembler::pcmpeqb(dst, src);
3866   } else if (src_enc < 16) {
3867     subptr(rsp, 64);
3868     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3869     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3870     Assembler::pcmpeqb(xmm0, src);
3871     movdqu(dst, xmm0);
3872     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3873     addptr(rsp, 64);
3874   } else if (dst_enc < 16) {
3875     subptr(rsp, 64);
3876     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3877     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3878     Assembler::pcmpeqb(dst, xmm0);
3879     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3880     addptr(rsp, 64);
3881   } else {
3882     subptr(rsp, 64);
3883     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3884     subptr(rsp, 64);
3885     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3886     movdqu(xmm0, src);
3887     movdqu(xmm1, dst);
3888     Assembler::pcmpeqb(xmm1, xmm0);
3889     movdqu(dst, xmm1);
3890     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3891     addptr(rsp, 64);
3892     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3893     addptr(rsp, 64);
3894   }
3895 }
3896 
3897 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3898   int dst_enc = dst->encoding();
3899   int src_enc = src->encoding();
3900   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3901     Assembler::pcmpeqw(dst, src);
3902   } else if ((dst_enc < 16) && (src_enc < 16)) {
3903     Assembler::pcmpeqw(dst, src);
3904   } else if (src_enc < 16) {
3905     subptr(rsp, 64);
3906     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3907     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3908     Assembler::pcmpeqw(xmm0, src);
3909     movdqu(dst, xmm0);
3910     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3911     addptr(rsp, 64);
3912   } else if (dst_enc < 16) {
3913     subptr(rsp, 64);
3914     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3915     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3916     Assembler::pcmpeqw(dst, xmm0);
3917     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3918     addptr(rsp, 64);
3919   } else {
3920     subptr(rsp, 64);
3921     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3922     subptr(rsp, 64);
3923     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3924     movdqu(xmm0, src);
3925     movdqu(xmm1, dst);
3926     Assembler::pcmpeqw(xmm1, xmm0);
3927     movdqu(dst, xmm1);
3928     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3929     addptr(rsp, 64);
3930     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3931     addptr(rsp, 64);
3932   }
3933 }
3934 
3935 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3936   int dst_enc = dst->encoding();
3937   if (dst_enc < 16) {
3938     Assembler::pcmpestri(dst, src, imm8);
3939   } else {
3940     subptr(rsp, 64);
3941     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3942     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3943     Assembler::pcmpestri(xmm0, src, imm8);
3944     movdqu(dst, xmm0);
3945     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3946     addptr(rsp, 64);
3947   }
3948 }
3949 
3950 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3951   int dst_enc = dst->encoding();
3952   int src_enc = src->encoding();
3953   if ((dst_enc < 16) && (src_enc < 16)) {
3954     Assembler::pcmpestri(dst, src, imm8);
3955   } else if (src_enc < 16) {
3956     subptr(rsp, 64);
3957     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3958     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3959     Assembler::pcmpestri(xmm0, src, imm8);
3960     movdqu(dst, xmm0);
3961     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3962     addptr(rsp, 64);
3963   } else if (dst_enc < 16) {
3964     subptr(rsp, 64);
3965     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3966     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3967     Assembler::pcmpestri(dst, xmm0, imm8);
3968     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3969     addptr(rsp, 64);
3970   } else {
3971     subptr(rsp, 64);
3972     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3973     subptr(rsp, 64);
3974     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3975     movdqu(xmm0, src);
3976     movdqu(xmm1, dst);
3977     Assembler::pcmpestri(xmm1, xmm0, imm8);
3978     movdqu(dst, xmm1);
3979     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3980     addptr(rsp, 64);
3981     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3982     addptr(rsp, 64);
3983   }
3984 }
3985 
3986 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3987   int dst_enc = dst->encoding();
3988   int src_enc = src->encoding();
3989   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3990     Assembler::pmovzxbw(dst, src);
3991   } else if ((dst_enc < 16) && (src_enc < 16)) {
3992     Assembler::pmovzxbw(dst, src);
3993   } else if (src_enc < 16) {
3994     subptr(rsp, 64);
3995     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3996     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3997     Assembler::pmovzxbw(xmm0, src);
3998     movdqu(dst, xmm0);
3999     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4000     addptr(rsp, 64);
4001   } else if (dst_enc < 16) {
4002     subptr(rsp, 64);
4003     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4004     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4005     Assembler::pmovzxbw(dst, xmm0);
4006     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4007     addptr(rsp, 64);
4008   } else {
4009     subptr(rsp, 64);
4010     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4011     subptr(rsp, 64);
4012     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4013     movdqu(xmm0, src);
4014     movdqu(xmm1, dst);
4015     Assembler::pmovzxbw(xmm1, xmm0);
4016     movdqu(dst, xmm1);
4017     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4018     addptr(rsp, 64);
4019     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4020     addptr(rsp, 64);
4021   }
4022 }
4023 
4024 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4025   int dst_enc = dst->encoding();
4026   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4027     Assembler::pmovzxbw(dst, src);
4028   } else if (dst_enc < 16) {
4029     Assembler::pmovzxbw(dst, src);
4030   } else {
4031     subptr(rsp, 64);
4032     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4033     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4034     Assembler::pmovzxbw(xmm0, src);
4035     movdqu(dst, xmm0);
4036     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4037     addptr(rsp, 64);
4038   }
4039 }
4040 
4041 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4042   int src_enc = src->encoding();
4043   if (src_enc < 16) {
4044     Assembler::pmovmskb(dst, src);
4045   } else {
4046     subptr(rsp, 64);
4047     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4048     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4049     Assembler::pmovmskb(dst, xmm0);
4050     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4051     addptr(rsp, 64);
4052   }
4053 }
4054 
4055 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4056   int dst_enc = dst->encoding();
4057   int src_enc = src->encoding();
4058   if ((dst_enc < 16) && (src_enc < 16)) {
4059     Assembler::ptest(dst, src);
4060   } else if (src_enc < 16) {
4061     subptr(rsp, 64);
4062     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4063     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4064     Assembler::ptest(xmm0, src);
4065     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4066     addptr(rsp, 64);
4067   } else if (dst_enc < 16) {
4068     subptr(rsp, 64);
4069     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4070     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4071     Assembler::ptest(dst, xmm0);
4072     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4073     addptr(rsp, 64);
4074   } else {
4075     subptr(rsp, 64);
4076     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4077     subptr(rsp, 64);
4078     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4079     movdqu(xmm0, src);
4080     movdqu(xmm1, dst);
4081     Assembler::ptest(xmm1, xmm0);
4082     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4083     addptr(rsp, 64);
4084     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4085     addptr(rsp, 64);
4086   }
4087 }
4088 
4089 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4090   if (reachable(src)) {
4091     Assembler::sqrtsd(dst, as_Address(src));
4092   } else {
4093     lea(rscratch1, src);
4094     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4095   }
4096 }
4097 
4098 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4099   if (reachable(src)) {
4100     Assembler::sqrtss(dst, as_Address(src));
4101   } else {
4102     lea(rscratch1, src);
4103     Assembler::sqrtss(dst, Address(rscratch1, 0));
4104   }
4105 }
4106 
4107 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4108   if (reachable(src)) {
4109     Assembler::subsd(dst, as_Address(src));
4110   } else {
4111     lea(rscratch1, src);
4112     Assembler::subsd(dst, Address(rscratch1, 0));
4113   }
4114 }
4115 
4116 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4117   if (reachable(src)) {
4118     Assembler::subss(dst, as_Address(src));
4119   } else {
4120     lea(rscratch1, src);
4121     Assembler::subss(dst, Address(rscratch1, 0));
4122   }
4123 }
4124 
4125 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4126   if (reachable(src)) {
4127     Assembler::ucomisd(dst, as_Address(src));
4128   } else {
4129     lea(rscratch1, src);
4130     Assembler::ucomisd(dst, Address(rscratch1, 0));
4131   }
4132 }
4133 
4134 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4135   if (reachable(src)) {
4136     Assembler::ucomiss(dst, as_Address(src));
4137   } else {
4138     lea(rscratch1, src);
4139     Assembler::ucomiss(dst, Address(rscratch1, 0));
4140   }
4141 }
4142 
4143 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4144   // Used in sign-bit flipping with aligned address.
4145   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4146   if (reachable(src)) {
4147     Assembler::xorpd(dst, as_Address(src));
4148   } else {
4149     lea(rscratch1, src);
4150     Assembler::xorpd(dst, Address(rscratch1, 0));
4151   }
4152 }
4153 
4154 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4155   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4156     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4157   }
4158   else {
4159     Assembler::xorpd(dst, src);
4160   }
4161 }
4162 
4163 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4164   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4165     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4166   } else {
4167     Assembler::xorps(dst, src);
4168   }
4169 }
4170 
4171 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4172   // Used in sign-bit flipping with aligned address.
4173   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4174   if (reachable(src)) {
4175     Assembler::xorps(dst, as_Address(src));
4176   } else {
4177     lea(rscratch1, src);
4178     Assembler::xorps(dst, Address(rscratch1, 0));
4179   }
4180 }
4181 
4182 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4183   // Used in sign-bit flipping with aligned address.
4184   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4185   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4186   if (reachable(src)) {
4187     Assembler::pshufb(dst, as_Address(src));
4188   } else {
4189     lea(rscratch1, src);
4190     Assembler::pshufb(dst, Address(rscratch1, 0));
4191   }
4192 }
4193 
4194 // AVX 3-operands instructions
4195 
4196 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4197   if (reachable(src)) {
4198     vaddsd(dst, nds, as_Address(src));
4199   } else {
4200     lea(rscratch1, src);
4201     vaddsd(dst, nds, Address(rscratch1, 0));
4202   }
4203 }
4204 
4205 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4206   if (reachable(src)) {
4207     vaddss(dst, nds, as_Address(src));
4208   } else {
4209     lea(rscratch1, src);
4210     vaddss(dst, nds, Address(rscratch1, 0));
4211   }
4212 }
4213 
4214 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4215   int dst_enc = dst->encoding();
4216   int nds_enc = nds->encoding();
4217   int src_enc = src->encoding();
4218   if ((dst_enc < 16) && (nds_enc < 16)) {
4219     vandps(dst, nds, negate_field, vector_len);
4220   } else if ((src_enc < 16) && (dst_enc < 16)) {
4221     movss(src, nds);
4222     vandps(dst, src, negate_field, vector_len);
4223   } else if (src_enc < 16) {
4224     movss(src, nds);
4225     vandps(src, src, negate_field, vector_len);
4226     movss(dst, src);
4227   } else if (dst_enc < 16) {
4228     movdqu(src, xmm0);
4229     movss(xmm0, nds);
4230     vandps(dst, xmm0, negate_field, vector_len);
4231     movdqu(xmm0, src);
4232   } else if (nds_enc < 16) {
4233     movdqu(src, xmm0);
4234     vandps(xmm0, nds, negate_field, vector_len);
4235     movss(dst, xmm0);
4236     movdqu(xmm0, src);
4237   } else {
4238     movdqu(src, xmm0);
4239     movss(xmm0, nds);
4240     vandps(xmm0, xmm0, negate_field, vector_len);
4241     movss(dst, xmm0);
4242     movdqu(xmm0, src);
4243   }
4244 }
4245 
4246 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4247   int dst_enc = dst->encoding();
4248   int nds_enc = nds->encoding();
4249   int src_enc = src->encoding();
4250   if ((dst_enc < 16) && (nds_enc < 16)) {
4251     vandpd(dst, nds, negate_field, vector_len);
4252   } else if ((src_enc < 16) && (dst_enc < 16)) {
4253     movsd(src, nds);
4254     vandpd(dst, src, negate_field, vector_len);
4255   } else if (src_enc < 16) {
4256     movsd(src, nds);
4257     vandpd(src, src, negate_field, vector_len);
4258     movsd(dst, src);
4259   } else if (dst_enc < 16) {
4260     movdqu(src, xmm0);
4261     movsd(xmm0, nds);
4262     vandpd(dst, xmm0, negate_field, vector_len);
4263     movdqu(xmm0, src);
4264   } else if (nds_enc < 16) {
4265     movdqu(src, xmm0);
4266     vandpd(xmm0, nds, negate_field, vector_len);
4267     movsd(dst, xmm0);
4268     movdqu(xmm0, src);
4269   } else {
4270     movdqu(src, xmm0);
4271     movsd(xmm0, nds);
4272     vandpd(xmm0, xmm0, negate_field, vector_len);
4273     movsd(dst, xmm0);
4274     movdqu(xmm0, src);
4275   }
4276 }
4277 
4278 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4279   int dst_enc = dst->encoding();
4280   int nds_enc = nds->encoding();
4281   int src_enc = src->encoding();
4282   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4283     Assembler::vpaddb(dst, nds, src, vector_len);
4284   } else if ((dst_enc < 16) && (src_enc < 16)) {
4285     Assembler::vpaddb(dst, dst, src, vector_len);
4286   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4287     // use nds as scratch for src
4288     evmovdqul(nds, src, Assembler::AVX_512bit);
4289     Assembler::vpaddb(dst, dst, nds, vector_len);
4290   } else if ((src_enc < 16) && (nds_enc < 16)) {
4291     // use nds as scratch for dst
4292     evmovdqul(nds, dst, Assembler::AVX_512bit);
4293     Assembler::vpaddb(nds, nds, src, vector_len);
4294     evmovdqul(dst, nds, Assembler::AVX_512bit);
4295   } else if (dst_enc < 16) {
4296     // use nds as scatch for xmm0 to hold src
4297     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4298     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4299     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4300     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4301   } else {
4302     // worse case scenario, all regs are in the upper bank
4303     subptr(rsp, 64);
4304     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4305     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4306     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4307     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4308     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4309     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4310     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4311     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4312     addptr(rsp, 64);
4313   }
4314 }
4315 
4316 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4317   int dst_enc = dst->encoding();
4318   int nds_enc = nds->encoding();
4319   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4320     Assembler::vpaddb(dst, nds, src, vector_len);
4321   } else if (dst_enc < 16) {
4322     Assembler::vpaddb(dst, dst, src, vector_len);
4323   } else if (nds_enc < 16) {
4324     // implies dst_enc in upper bank with src as scratch
4325     evmovdqul(nds, dst, Assembler::AVX_512bit);
4326     Assembler::vpaddb(nds, nds, src, vector_len);
4327     evmovdqul(dst, nds, Assembler::AVX_512bit);
4328   } else {
4329     // worse case scenario, all regs in upper bank
4330     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4331     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4332     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4333     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4334   }
4335 }
4336 
4337 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4338   int dst_enc = dst->encoding();
4339   int nds_enc = nds->encoding();
4340   int src_enc = src->encoding();
4341   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4342     Assembler::vpaddw(dst, nds, src, vector_len);
4343   } else if ((dst_enc < 16) && (src_enc < 16)) {
4344     Assembler::vpaddw(dst, dst, src, vector_len);
4345   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4346     // use nds as scratch for src
4347     evmovdqul(nds, src, Assembler::AVX_512bit);
4348     Assembler::vpaddw(dst, dst, nds, vector_len);
4349   } else if ((src_enc < 16) && (nds_enc < 16)) {
4350     // use nds as scratch for dst
4351     evmovdqul(nds, dst, Assembler::AVX_512bit);
4352     Assembler::vpaddw(nds, nds, src, vector_len);
4353     evmovdqul(dst, nds, Assembler::AVX_512bit);
4354   } else if (dst_enc < 16) {
4355     // use nds as scatch for xmm0 to hold src
4356     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4357     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4358     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4359     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4360   } else {
4361     // worse case scenario, all regs are in the upper bank
4362     subptr(rsp, 64);
4363     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4364     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4365     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4366     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4367     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4368     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4369     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4370     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4371     addptr(rsp, 64);
4372   }
4373 }
4374 
4375 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4376   int dst_enc = dst->encoding();
4377   int nds_enc = nds->encoding();
4378   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4379     Assembler::vpaddw(dst, nds, src, vector_len);
4380   } else if (dst_enc < 16) {
4381     Assembler::vpaddw(dst, dst, src, vector_len);
4382   } else if (nds_enc < 16) {
4383     // implies dst_enc in upper bank with src as scratch
4384     evmovdqul(nds, dst, Assembler::AVX_512bit);
4385     Assembler::vpaddw(nds, nds, src, vector_len);
4386     evmovdqul(dst, nds, Assembler::AVX_512bit);
4387   } else {
4388     // worse case scenario, all regs in upper bank
4389     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4390     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4391     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4392     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4393   }
4394 }
4395 
4396 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4397   int dst_enc = dst->encoding();
4398   int src_enc = src->encoding();
4399   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4400     Assembler::vpbroadcastw(dst, src);
4401   } else if ((dst_enc < 16) && (src_enc < 16)) {
4402     Assembler::vpbroadcastw(dst, src);
4403   } else if (src_enc < 16) {
4404     subptr(rsp, 64);
4405     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4406     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4407     Assembler::vpbroadcastw(xmm0, src);
4408     movdqu(dst, xmm0);
4409     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4410     addptr(rsp, 64);
4411   } else if (dst_enc < 16) {
4412     subptr(rsp, 64);
4413     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4414     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4415     Assembler::vpbroadcastw(dst, xmm0);
4416     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4417     addptr(rsp, 64);
4418   } else {
4419     subptr(rsp, 64);
4420     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4421     subptr(rsp, 64);
4422     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4423     movdqu(xmm0, src);
4424     movdqu(xmm1, dst);
4425     Assembler::vpbroadcastw(xmm1, xmm0);
4426     movdqu(dst, xmm1);
4427     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4428     addptr(rsp, 64);
4429     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4430     addptr(rsp, 64);
4431   }
4432 }
4433 
4434 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4435   int dst_enc = dst->encoding();
4436   int nds_enc = nds->encoding();
4437   int src_enc = src->encoding();
4438   assert(dst_enc == nds_enc, "");
4439   if ((dst_enc < 16) && (src_enc < 16)) {
4440     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4441   } else if (src_enc < 16) {
4442     subptr(rsp, 64);
4443     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4444     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4445     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4446     movdqu(dst, xmm0);
4447     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4448     addptr(rsp, 64);
4449   } else if (dst_enc < 16) {
4450     subptr(rsp, 64);
4451     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4452     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4453     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4454     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4455     addptr(rsp, 64);
4456   } else {
4457     subptr(rsp, 64);
4458     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4459     subptr(rsp, 64);
4460     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4461     movdqu(xmm0, src);
4462     movdqu(xmm1, dst);
4463     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4464     movdqu(dst, xmm1);
4465     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4466     addptr(rsp, 64);
4467     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4468     addptr(rsp, 64);
4469   }
4470 }
4471 
4472 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4473   int dst_enc = dst->encoding();
4474   int nds_enc = nds->encoding();
4475   int src_enc = src->encoding();
4476   assert(dst_enc == nds_enc, "");
4477   if ((dst_enc < 16) && (src_enc < 16)) {
4478     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4479   } else if (src_enc < 16) {
4480     subptr(rsp, 64);
4481     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4482     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4483     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4484     movdqu(dst, xmm0);
4485     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4486     addptr(rsp, 64);
4487   } else if (dst_enc < 16) {
4488     subptr(rsp, 64);
4489     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4490     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4491     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4492     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4493     addptr(rsp, 64);
4494   } else {
4495     subptr(rsp, 64);
4496     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4497     subptr(rsp, 64);
4498     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4499     movdqu(xmm0, src);
4500     movdqu(xmm1, dst);
4501     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4502     movdqu(dst, xmm1);
4503     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4504     addptr(rsp, 64);
4505     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4506     addptr(rsp, 64);
4507   }
4508 }
4509 
4510 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4511   int dst_enc = dst->encoding();
4512   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4513     Assembler::vpmovzxbw(dst, src, vector_len);
4514   } else if (dst_enc < 16) {
4515     Assembler::vpmovzxbw(dst, src, vector_len);
4516   } else {
4517     subptr(rsp, 64);
4518     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4519     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4520     Assembler::vpmovzxbw(xmm0, src, vector_len);
4521     movdqu(dst, xmm0);
4522     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4523     addptr(rsp, 64);
4524   }
4525 }
4526 
4527 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4528   int src_enc = src->encoding();
4529   if (src_enc < 16) {
4530     Assembler::vpmovmskb(dst, src);
4531   } else {
4532     subptr(rsp, 64);
4533     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4534     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4535     Assembler::vpmovmskb(dst, xmm0);
4536     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4537     addptr(rsp, 64);
4538   }
4539 }
4540 
4541 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4542   int dst_enc = dst->encoding();
4543   int nds_enc = nds->encoding();
4544   int src_enc = src->encoding();
4545   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4546     Assembler::vpmullw(dst, nds, src, vector_len);
4547   } else if ((dst_enc < 16) && (src_enc < 16)) {
4548     Assembler::vpmullw(dst, dst, src, vector_len);
4549   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4550     // use nds as scratch for src
4551     evmovdqul(nds, src, Assembler::AVX_512bit);
4552     Assembler::vpmullw(dst, dst, nds, vector_len);
4553   } else if ((src_enc < 16) && (nds_enc < 16)) {
4554     // use nds as scratch for dst
4555     evmovdqul(nds, dst, Assembler::AVX_512bit);
4556     Assembler::vpmullw(nds, nds, src, vector_len);
4557     evmovdqul(dst, nds, Assembler::AVX_512bit);
4558   } else if (dst_enc < 16) {
4559     // use nds as scatch for xmm0 to hold src
4560     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4561     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4562     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4563     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4564   } else {
4565     // worse case scenario, all regs are in the upper bank
4566     subptr(rsp, 64);
4567     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4568     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4569     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4570     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4571     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4572     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4573     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4574     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4575     addptr(rsp, 64);
4576   }
4577 }
4578 
4579 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4580   int dst_enc = dst->encoding();
4581   int nds_enc = nds->encoding();
4582   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4583     Assembler::vpmullw(dst, nds, src, vector_len);
4584   } else if (dst_enc < 16) {
4585     Assembler::vpmullw(dst, dst, src, vector_len);
4586   } else if (nds_enc < 16) {
4587     // implies dst_enc in upper bank with src as scratch
4588     evmovdqul(nds, dst, Assembler::AVX_512bit);
4589     Assembler::vpmullw(nds, nds, src, vector_len);
4590     evmovdqul(dst, nds, Assembler::AVX_512bit);
4591   } else {
4592     // worse case scenario, all regs in upper bank
4593     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4594     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4595     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4596     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4597   }
4598 }
4599 
4600 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4601   int dst_enc = dst->encoding();
4602   int nds_enc = nds->encoding();
4603   int src_enc = src->encoding();
4604   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4605     Assembler::vpsubb(dst, nds, src, vector_len);
4606   } else if ((dst_enc < 16) && (src_enc < 16)) {
4607     Assembler::vpsubb(dst, dst, src, vector_len);
4608   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4609     // use nds as scratch for src
4610     evmovdqul(nds, src, Assembler::AVX_512bit);
4611     Assembler::vpsubb(dst, dst, nds, vector_len);
4612   } else if ((src_enc < 16) && (nds_enc < 16)) {
4613     // use nds as scratch for dst
4614     evmovdqul(nds, dst, Assembler::AVX_512bit);
4615     Assembler::vpsubb(nds, nds, src, vector_len);
4616     evmovdqul(dst, nds, Assembler::AVX_512bit);
4617   } else if (dst_enc < 16) {
4618     // use nds as scatch for xmm0 to hold src
4619     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4620     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4621     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4622     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4623   } else {
4624     // worse case scenario, all regs are in the upper bank
4625     subptr(rsp, 64);
4626     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4627     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4628     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4629     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4630     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4631     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4632     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4633     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4634     addptr(rsp, 64);
4635   }
4636 }
4637 
4638 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4639   int dst_enc = dst->encoding();
4640   int nds_enc = nds->encoding();
4641   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4642     Assembler::vpsubb(dst, nds, src, vector_len);
4643   } else if (dst_enc < 16) {
4644     Assembler::vpsubb(dst, dst, src, vector_len);
4645   } else if (nds_enc < 16) {
4646     // implies dst_enc in upper bank with src as scratch
4647     evmovdqul(nds, dst, Assembler::AVX_512bit);
4648     Assembler::vpsubb(nds, nds, src, vector_len);
4649     evmovdqul(dst, nds, Assembler::AVX_512bit);
4650   } else {
4651     // worse case scenario, all regs in upper bank
4652     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4653     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4654     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4655     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4656   }
4657 }
4658 
4659 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4660   int dst_enc = dst->encoding();
4661   int nds_enc = nds->encoding();
4662   int src_enc = src->encoding();
4663   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4664     Assembler::vpsubw(dst, nds, src, vector_len);
4665   } else if ((dst_enc < 16) && (src_enc < 16)) {
4666     Assembler::vpsubw(dst, dst, src, vector_len);
4667   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4668     // use nds as scratch for src
4669     evmovdqul(nds, src, Assembler::AVX_512bit);
4670     Assembler::vpsubw(dst, dst, nds, vector_len);
4671   } else if ((src_enc < 16) && (nds_enc < 16)) {
4672     // use nds as scratch for dst
4673     evmovdqul(nds, dst, Assembler::AVX_512bit);
4674     Assembler::vpsubw(nds, nds, src, vector_len);
4675     evmovdqul(dst, nds, Assembler::AVX_512bit);
4676   } else if (dst_enc < 16) {
4677     // use nds as scatch for xmm0 to hold src
4678     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4679     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4680     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4681     evmovdqul(xmm0, 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, src, Assembler::AVX_512bit);
4688     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4689     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4690     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4691     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4692     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4693     addptr(rsp, 64);
4694   }
4695 }
4696 
4697 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4698   int dst_enc = dst->encoding();
4699   int nds_enc = nds->encoding();
4700   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4701     Assembler::vpsubw(dst, nds, src, vector_len);
4702   } else if (dst_enc < 16) {
4703     Assembler::vpsubw(dst, dst, src, vector_len);
4704   } else if (nds_enc < 16) {
4705     // implies dst_enc in upper bank with src as scratch
4706     evmovdqul(nds, dst, Assembler::AVX_512bit);
4707     Assembler::vpsubw(nds, nds, src, vector_len);
4708     evmovdqul(dst, nds, Assembler::AVX_512bit);
4709   } else {
4710     // worse case scenario, all regs in upper bank
4711     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4712     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4713     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4714     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4715   }
4716 }
4717 
4718 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4719   int dst_enc = dst->encoding();
4720   int nds_enc = nds->encoding();
4721   int shift_enc = shift->encoding();
4722   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4723     Assembler::vpsraw(dst, nds, shift, vector_len);
4724   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4725     Assembler::vpsraw(dst, dst, shift, vector_len);
4726   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4727     // use nds_enc as scratch with shift
4728     evmovdqul(nds, shift, Assembler::AVX_512bit);
4729     Assembler::vpsraw(dst, dst, nds, vector_len);
4730   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4731     // use nds as scratch with dst
4732     evmovdqul(nds, dst, Assembler::AVX_512bit);
4733     Assembler::vpsraw(nds, nds, shift, vector_len);
4734     evmovdqul(dst, nds, Assembler::AVX_512bit);
4735   } else if (dst_enc < 16) {
4736     // use nds to save a copy of xmm0 and hold shift
4737     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4738     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4739     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4740     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4741   } else if (nds_enc < 16) {
4742     // use nds as dest as temps
4743     evmovdqul(nds, dst, Assembler::AVX_512bit);
4744     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4745     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4746     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4747     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4748     evmovdqul(dst, nds, Assembler::AVX_512bit);
4749   } else {
4750     // worse case scenario, all regs are in the upper bank
4751     subptr(rsp, 64);
4752     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4753     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4754     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4755     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4756     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4757     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4758     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4759     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4760     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4761     addptr(rsp, 64);
4762   }
4763 }
4764 
4765 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4766   int dst_enc = dst->encoding();
4767   int nds_enc = nds->encoding();
4768   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4769     Assembler::vpsraw(dst, nds, shift, vector_len);
4770   } else if (dst_enc < 16) {
4771     Assembler::vpsraw(dst, dst, shift, vector_len);
4772   } else if (nds_enc < 16) {
4773     // use nds as scratch
4774     evmovdqul(nds, dst, Assembler::AVX_512bit);
4775     Assembler::vpsraw(nds, nds, shift, vector_len);
4776     evmovdqul(dst, nds, Assembler::AVX_512bit);
4777   } else {
4778     // use nds as scratch for xmm0
4779     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4780     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4781     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4782     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4783   }
4784 }
4785 
4786 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4787   int dst_enc = dst->encoding();
4788   int nds_enc = nds->encoding();
4789   int shift_enc = shift->encoding();
4790   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4791     Assembler::vpsrlw(dst, nds, shift, vector_len);
4792   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4793     Assembler::vpsrlw(dst, dst, shift, vector_len);
4794   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4795     // use nds_enc as scratch with shift
4796     evmovdqul(nds, shift, Assembler::AVX_512bit);
4797     Assembler::vpsrlw(dst, dst, nds, vector_len);
4798   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4799     // use nds as scratch with dst
4800     evmovdqul(nds, dst, Assembler::AVX_512bit);
4801     Assembler::vpsrlw(nds, nds, shift, vector_len);
4802     evmovdqul(dst, nds, Assembler::AVX_512bit);
4803   } else if (dst_enc < 16) {
4804     // use nds to save a copy of xmm0 and hold shift
4805     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4806     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4807     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4808     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4809   } else if (nds_enc < 16) {
4810     // use nds as dest as temps
4811     evmovdqul(nds, dst, Assembler::AVX_512bit);
4812     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4813     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4814     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4815     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4816     evmovdqul(dst, nds, Assembler::AVX_512bit);
4817   } else {
4818     // worse case scenario, all regs are in the upper bank
4819     subptr(rsp, 64);
4820     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4821     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4822     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4823     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4824     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4825     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4826     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4827     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4828     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4829     addptr(rsp, 64);
4830   }
4831 }
4832 
4833 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4834   int dst_enc = dst->encoding();
4835   int nds_enc = nds->encoding();
4836   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4837     Assembler::vpsrlw(dst, nds, shift, vector_len);
4838   } else if (dst_enc < 16) {
4839     Assembler::vpsrlw(dst, dst, shift, vector_len);
4840   } else if (nds_enc < 16) {
4841     // use nds as scratch
4842     evmovdqul(nds, dst, Assembler::AVX_512bit);
4843     Assembler::vpsrlw(nds, nds, shift, vector_len);
4844     evmovdqul(dst, nds, Assembler::AVX_512bit);
4845   } else {
4846     // use nds as scratch for xmm0
4847     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4848     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4849     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4850     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4851   }
4852 }
4853 
4854 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4855   int dst_enc = dst->encoding();
4856   int nds_enc = nds->encoding();
4857   int shift_enc = shift->encoding();
4858   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4859     Assembler::vpsllw(dst, nds, shift, vector_len);
4860   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4861     Assembler::vpsllw(dst, dst, shift, vector_len);
4862   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4863     // use nds_enc as scratch with shift
4864     evmovdqul(nds, shift, Assembler::AVX_512bit);
4865     Assembler::vpsllw(dst, dst, nds, vector_len);
4866   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4867     // use nds as scratch with dst
4868     evmovdqul(nds, dst, Assembler::AVX_512bit);
4869     Assembler::vpsllw(nds, nds, shift, vector_len);
4870     evmovdqul(dst, nds, Assembler::AVX_512bit);
4871   } else if (dst_enc < 16) {
4872     // use nds to save a copy of xmm0 and hold shift
4873     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4874     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4875     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4876     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4877   } else if (nds_enc < 16) {
4878     // use nds as dest as temps
4879     evmovdqul(nds, dst, Assembler::AVX_512bit);
4880     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4881     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4882     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4883     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4884     evmovdqul(dst, nds, Assembler::AVX_512bit);
4885   } else {
4886     // worse case scenario, all regs are in the upper bank
4887     subptr(rsp, 64);
4888     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4889     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4890     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4891     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4892     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4893     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4894     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4895     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4896     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4897     addptr(rsp, 64);
4898   }
4899 }
4900 
4901 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4902   int dst_enc = dst->encoding();
4903   int nds_enc = nds->encoding();
4904   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4905     Assembler::vpsllw(dst, nds, shift, vector_len);
4906   } else if (dst_enc < 16) {
4907     Assembler::vpsllw(dst, dst, shift, vector_len);
4908   } else if (nds_enc < 16) {
4909     // use nds as scratch
4910     evmovdqul(nds, dst, Assembler::AVX_512bit);
4911     Assembler::vpsllw(nds, nds, shift, vector_len);
4912     evmovdqul(dst, nds, Assembler::AVX_512bit);
4913   } else {
4914     // use nds as scratch for xmm0
4915     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4916     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4917     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4918     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4919   }
4920 }
4921 
4922 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4923   int dst_enc = dst->encoding();
4924   int src_enc = src->encoding();
4925   if ((dst_enc < 16) && (src_enc < 16)) {
4926     Assembler::vptest(dst, src);
4927   } else if (src_enc < 16) {
4928     subptr(rsp, 64);
4929     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4930     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4931     Assembler::vptest(xmm0, src);
4932     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4933     addptr(rsp, 64);
4934   } else if (dst_enc < 16) {
4935     subptr(rsp, 64);
4936     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4937     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4938     Assembler::vptest(dst, xmm0);
4939     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4940     addptr(rsp, 64);
4941   } else {
4942     subptr(rsp, 64);
4943     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4944     subptr(rsp, 64);
4945     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4946     movdqu(xmm0, src);
4947     movdqu(xmm1, dst);
4948     Assembler::vptest(xmm1, xmm0);
4949     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4950     addptr(rsp, 64);
4951     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4952     addptr(rsp, 64);
4953   }
4954 }
4955 
4956 // This instruction exists within macros, ergo we cannot control its input
4957 // when emitted through those patterns.
4958 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4959   if (VM_Version::supports_avx512nobw()) {
4960     int dst_enc = dst->encoding();
4961     int src_enc = src->encoding();
4962     if (dst_enc == src_enc) {
4963       if (dst_enc < 16) {
4964         Assembler::punpcklbw(dst, src);
4965       } else {
4966         subptr(rsp, 64);
4967         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4968         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4969         Assembler::punpcklbw(xmm0, xmm0);
4970         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4971         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4972         addptr(rsp, 64);
4973       }
4974     } else {
4975       if ((src_enc < 16) && (dst_enc < 16)) {
4976         Assembler::punpcklbw(dst, src);
4977       } else if (src_enc < 16) {
4978         subptr(rsp, 64);
4979         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4980         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4981         Assembler::punpcklbw(xmm0, src);
4982         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4983         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4984         addptr(rsp, 64);
4985       } else if (dst_enc < 16) {
4986         subptr(rsp, 64);
4987         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4988         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4989         Assembler::punpcklbw(dst, xmm0);
4990         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4991         addptr(rsp, 64);
4992       } else {
4993         subptr(rsp, 64);
4994         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4995         subptr(rsp, 64);
4996         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4997         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4998         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4999         Assembler::punpcklbw(xmm0, xmm1);
5000         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5001         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5002         addptr(rsp, 64);
5003         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5004         addptr(rsp, 64);
5005       }
5006     }
5007   } else {
5008     Assembler::punpcklbw(dst, src);
5009   }
5010 }
5011 
5012 // This instruction exists within macros, ergo we cannot control its input
5013 // when emitted through those patterns.
5014 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5015   if (VM_Version::supports_avx512nobw()) {
5016     int dst_enc = dst->encoding();
5017     int src_enc = src->encoding();
5018     if (dst_enc == src_enc) {
5019       if (dst_enc < 16) {
5020         Assembler::pshuflw(dst, src, mode);
5021       } else {
5022         subptr(rsp, 64);
5023         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5024         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5025         Assembler::pshuflw(xmm0, xmm0, mode);
5026         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5027         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5028         addptr(rsp, 64);
5029       }
5030     } else {
5031       if ((src_enc < 16) && (dst_enc < 16)) {
5032         Assembler::pshuflw(dst, src, mode);
5033       } else if (src_enc < 16) {
5034         subptr(rsp, 64);
5035         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5036         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5037         Assembler::pshuflw(xmm0, src, mode);
5038         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5039         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5040         addptr(rsp, 64);
5041       } else if (dst_enc < 16) {
5042         subptr(rsp, 64);
5043         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5044         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5045         Assembler::pshuflw(dst, xmm0, mode);
5046         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5047         addptr(rsp, 64);
5048       } else {
5049         subptr(rsp, 64);
5050         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5051         subptr(rsp, 64);
5052         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5053         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5054         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5055         Assembler::pshuflw(xmm0, xmm1, mode);
5056         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5057         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5058         addptr(rsp, 64);
5059         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5060         addptr(rsp, 64);
5061       }
5062     }
5063   } else {
5064     Assembler::pshuflw(dst, src, mode);
5065   }
5066 }
5067 
5068 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5069   if (reachable(src)) {
5070     vandpd(dst, nds, as_Address(src), vector_len);
5071   } else {
5072     lea(rscratch1, src);
5073     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5074   }
5075 }
5076 
5077 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5078   if (reachable(src)) {
5079     vandps(dst, nds, as_Address(src), vector_len);
5080   } else {
5081     lea(rscratch1, src);
5082     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5083   }
5084 }
5085 
5086 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5087   if (reachable(src)) {
5088     vdivsd(dst, nds, as_Address(src));
5089   } else {
5090     lea(rscratch1, src);
5091     vdivsd(dst, nds, Address(rscratch1, 0));
5092   }
5093 }
5094 
5095 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5096   if (reachable(src)) {
5097     vdivss(dst, nds, as_Address(src));
5098   } else {
5099     lea(rscratch1, src);
5100     vdivss(dst, nds, Address(rscratch1, 0));
5101   }
5102 }
5103 
5104 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5105   if (reachable(src)) {
5106     vmulsd(dst, nds, as_Address(src));
5107   } else {
5108     lea(rscratch1, src);
5109     vmulsd(dst, nds, Address(rscratch1, 0));
5110   }
5111 }
5112 
5113 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5114   if (reachable(src)) {
5115     vmulss(dst, nds, as_Address(src));
5116   } else {
5117     lea(rscratch1, src);
5118     vmulss(dst, nds, Address(rscratch1, 0));
5119   }
5120 }
5121 
5122 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5123   if (reachable(src)) {
5124     vsubsd(dst, nds, as_Address(src));
5125   } else {
5126     lea(rscratch1, src);
5127     vsubsd(dst, nds, Address(rscratch1, 0));
5128   }
5129 }
5130 
5131 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5132   if (reachable(src)) {
5133     vsubss(dst, nds, as_Address(src));
5134   } else {
5135     lea(rscratch1, src);
5136     vsubss(dst, nds, Address(rscratch1, 0));
5137   }
5138 }
5139 
5140 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5141   int nds_enc = nds->encoding();
5142   int dst_enc = dst->encoding();
5143   bool dst_upper_bank = (dst_enc > 15);
5144   bool nds_upper_bank = (nds_enc > 15);
5145   if (VM_Version::supports_avx512novl() &&
5146       (nds_upper_bank || dst_upper_bank)) {
5147     if (dst_upper_bank) {
5148       subptr(rsp, 64);
5149       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5150       movflt(xmm0, nds);
5151       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5152       movflt(dst, xmm0);
5153       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5154       addptr(rsp, 64);
5155     } else {
5156       movflt(dst, nds);
5157       vxorps(dst, dst, src, Assembler::AVX_128bit);
5158     }
5159   } else {
5160     vxorps(dst, nds, src, Assembler::AVX_128bit);
5161   }
5162 }
5163 
5164 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5165   int nds_enc = nds->encoding();
5166   int dst_enc = dst->encoding();
5167   bool dst_upper_bank = (dst_enc > 15);
5168   bool nds_upper_bank = (nds_enc > 15);
5169   if (VM_Version::supports_avx512novl() &&
5170       (nds_upper_bank || dst_upper_bank)) {
5171     if (dst_upper_bank) {
5172       subptr(rsp, 64);
5173       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5174       movdbl(xmm0, nds);
5175       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5176       movdbl(dst, xmm0);
5177       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5178       addptr(rsp, 64);
5179     } else {
5180       movdbl(dst, nds);
5181       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5182     }
5183   } else {
5184     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5185   }
5186 }
5187 
5188 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5189   if (reachable(src)) {
5190     vxorpd(dst, nds, as_Address(src), vector_len);
5191   } else {
5192     lea(rscratch1, src);
5193     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5194   }
5195 }
5196 
5197 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5198   if (reachable(src)) {
5199     vxorps(dst, nds, as_Address(src), vector_len);
5200   } else {
5201     lea(rscratch1, src);
5202     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5203   }
5204 }
5205 
5206 
5207 //////////////////////////////////////////////////////////////////////////////////
5208 #if INCLUDE_ALL_GCS
5209 
5210 void MacroAssembler::g1_write_barrier_pre(Register obj,
5211                                           Register pre_val,
5212                                           Register thread,
5213                                           Register tmp,
5214                                           bool tosca_live,
5215                                           bool expand_call) {
5216 
5217   // If expand_call is true then we expand the call_VM_leaf macro
5218   // directly to skip generating the check by
5219   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5220 
5221 #ifdef _LP64
5222   assert(thread == r15_thread, "must be");
5223 #endif // _LP64
5224 
5225   Label done;
5226   Label runtime;
5227 
5228   assert(pre_val != noreg, "check this code");
5229 
5230   if (obj != noreg) {
5231     assert_different_registers(obj, pre_val, tmp);
5232     assert(pre_val != rax, "check this code");
5233   }
5234 
5235   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5236                                        SATBMarkQueue::byte_offset_of_active()));
5237   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5238                                        SATBMarkQueue::byte_offset_of_index()));
5239   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5240                                        SATBMarkQueue::byte_offset_of_buf()));
5241 
5242 
5243   // Is marking active?
5244   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5245     cmpl(in_progress, 0);
5246   } else {
5247     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5248     cmpb(in_progress, 0);
5249   }
5250   jcc(Assembler::equal, done);
5251 
5252   // Do we need to load the previous value?
5253   if (obj != noreg) {
5254     load_heap_oop(pre_val, Address(obj, 0));
5255   }
5256 
5257   // Is the previous value null?
5258   cmpptr(pre_val, (int32_t) NULL_WORD);
5259   jcc(Assembler::equal, done);
5260 
5261   // Can we store original value in the thread's buffer?
5262   // Is index == 0?
5263   // (The index field is typed as size_t.)
5264 
5265   movptr(tmp, index);                   // tmp := *index_adr
5266   cmpptr(tmp, 0);                       // tmp == 0?
5267   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5268 
5269   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5270   movptr(index, tmp);                   // *index_adr := tmp
5271   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5272 
5273   // Record the previous value
5274   movptr(Address(tmp, 0), pre_val);
5275   jmp(done);
5276 
5277   bind(runtime);
5278   // save the live input values
5279   if(tosca_live) push(rax);
5280 
5281   if (obj != noreg && obj != rax)
5282     push(obj);
5283 
5284   if (pre_val != rax)
5285     push(pre_val);
5286 
5287   // Calling the runtime using the regular call_VM_leaf mechanism generates
5288   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5289   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5290   //
5291   // If we care generating the pre-barrier without a frame (e.g. in the
5292   // intrinsified Reference.get() routine) then ebp might be pointing to
5293   // the caller frame and so this check will most likely fail at runtime.
5294   //
5295   // Expanding the call directly bypasses the generation of the check.
5296   // So when we do not have have a full interpreter frame on the stack
5297   // expand_call should be passed true.
5298 
5299   NOT_LP64( push(thread); )
5300 
5301   if (expand_call) {
5302     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5303     pass_arg1(this, thread);
5304     pass_arg0(this, pre_val);
5305     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5306   } else {
5307     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5308   }
5309 
5310   NOT_LP64( pop(thread); )
5311 
5312   // save the live input values
5313   if (pre_val != rax)
5314     pop(pre_val);
5315 
5316   if (obj != noreg && obj != rax)
5317     pop(obj);
5318 
5319   if(tosca_live) pop(rax);
5320 
5321   bind(done);
5322 }
5323 
5324 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5325                                            Register new_val,
5326                                            Register thread,
5327                                            Register tmp,
5328                                            Register tmp2) {
5329 #ifdef _LP64
5330   assert(thread == r15_thread, "must be");
5331 #endif // _LP64
5332 
5333   if (UseShenandoahGC) {
5334     // No need for this in Shenandoah.
5335     return;
5336   }
5337 
5338   assert(UseG1GC, "expect G1 GC");
5339 
5340   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5341                                        DirtyCardQueue::byte_offset_of_index()));
5342   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5343                                        DirtyCardQueue::byte_offset_of_buf()));
5344 
5345   CardTableModRefBS* ct =
5346     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5347   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5348 
5349   Label done;
5350   Label runtime;
5351 
5352   // Does store cross heap regions?
5353 
5354   movptr(tmp, store_addr);
5355   xorptr(tmp, new_val);
5356   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5357   jcc(Assembler::equal, done);
5358 
5359   // crosses regions, storing NULL?
5360 
5361   cmpptr(new_val, (int32_t) NULL_WORD);
5362   jcc(Assembler::equal, done);
5363 
5364   // storing region crossing non-NULL, is card already dirty?
5365 
5366   const Register card_addr = tmp;
5367   const Register cardtable = tmp2;
5368 
5369   movptr(card_addr, store_addr);
5370   shrptr(card_addr, CardTableModRefBS::card_shift);
5371   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5372   // a valid address and therefore is not properly handled by the relocation code.
5373   movptr(cardtable, (intptr_t)ct->byte_map_base);
5374   addptr(card_addr, cardtable);
5375 
5376   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5377   jcc(Assembler::equal, done);
5378 
5379   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5380   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5381   jcc(Assembler::equal, done);
5382 
5383 
5384   // storing a region crossing, non-NULL oop, card is clean.
5385   // dirty card and log.
5386 
5387   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5388 
5389   cmpl(queue_index, 0);
5390   jcc(Assembler::equal, runtime);
5391   subl(queue_index, wordSize);
5392   movptr(tmp2, buffer);
5393 #ifdef _LP64
5394   movslq(rscratch1, queue_index);
5395   addq(tmp2, rscratch1);
5396   movq(Address(tmp2, 0), card_addr);
5397 #else
5398   addl(tmp2, queue_index);
5399   movl(Address(tmp2, 0), card_addr);
5400 #endif
5401   jmp(done);
5402 
5403   bind(runtime);
5404   // save the live input values
5405   push(store_addr);
5406   push(new_val);
5407 #ifdef _LP64
5408   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5409 #else
5410   push(thread);
5411   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5412   pop(thread);
5413 #endif
5414   pop(new_val);
5415   pop(store_addr);
5416 
5417   bind(done);
5418 }
5419 
5420 #endif // INCLUDE_ALL_GCS
5421 //////////////////////////////////////////////////////////////////////////////////
5422 
5423 
5424 void MacroAssembler::store_check(Register obj, Address dst) {
5425   store_check(obj);
5426 }
5427 
5428 void MacroAssembler::store_check(Register obj) {
5429   // Does a store check for the oop in register obj. The content of
5430   // register obj is destroyed afterwards.
5431   BarrierSet* bs = Universe::heap()->barrier_set();
5432   assert(bs->kind() == BarrierSet::CardTableForRS ||
5433          bs->kind() == BarrierSet::CardTableExtension,
5434          "Wrong barrier set kind");
5435 
5436   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5437   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5438 
5439   shrptr(obj, CardTableModRefBS::card_shift);
5440 
5441   Address card_addr;
5442 
5443   // The calculation for byte_map_base is as follows:
5444   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5445   // So this essentially converts an address to a displacement and it will
5446   // never need to be relocated. On 64bit however the value may be too
5447   // large for a 32bit displacement.
5448   intptr_t disp = (intptr_t) ct->byte_map_base;
5449   if (is_simm32(disp)) {
5450     card_addr = Address(noreg, obj, Address::times_1, disp);
5451   } else {
5452     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5453     // displacement and done in a single instruction given favorable mapping and a
5454     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5455     // entry and that entry is not properly handled by the relocation code.
5456     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5457     Address index(noreg, obj, Address::times_1);
5458     card_addr = as_Address(ArrayAddress(cardtable, index));
5459   }
5460 
5461   int dirty = CardTableModRefBS::dirty_card_val();
5462   if (UseCondCardMark) {
5463     Label L_already_dirty;
5464     if (UseConcMarkSweepGC) {
5465       membar(Assembler::StoreLoad);
5466     }
5467     cmpb(card_addr, dirty);
5468     jcc(Assembler::equal, L_already_dirty);
5469     movb(card_addr, dirty);
5470     bind(L_already_dirty);
5471   } else {
5472     movb(card_addr, dirty);
5473   }
5474 }
5475 
5476 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5477   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5478 }
5479 
5480 // Force generation of a 4 byte immediate value even if it fits into 8bit
5481 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5482   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5483 }
5484 
5485 void MacroAssembler::subptr(Register dst, Register src) {
5486   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5487 }
5488 
5489 // C++ bool manipulation
5490 void MacroAssembler::testbool(Register dst) {
5491   if(sizeof(bool) == 1)
5492     testb(dst, 0xff);
5493   else if(sizeof(bool) == 2) {
5494     // testw implementation needed for two byte bools
5495     ShouldNotReachHere();
5496   } else if(sizeof(bool) == 4)
5497     testl(dst, dst);
5498   else
5499     // unsupported
5500     ShouldNotReachHere();
5501 }
5502 
5503 void MacroAssembler::testptr(Register dst, Register src) {
5504   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5505 }
5506 
5507 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5508 void MacroAssembler::tlab_allocate(Register obj,
5509                                    Register var_size_in_bytes,
5510                                    int con_size_in_bytes,
5511                                    Register t1,
5512                                    Register t2,
5513                                    Label& slow_case) {
5514   assert_different_registers(obj, t1, t2);
5515   assert_different_registers(obj, var_size_in_bytes, t1);
5516   Register end = t2;
5517   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5518 
5519   verify_tlab();
5520 
5521   NOT_LP64(get_thread(thread));
5522 
5523   uint oop_extra_words = Universe::heap()->oop_extra_words();
5524 
5525   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5526   if (var_size_in_bytes == noreg) {
5527     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5528   } else {
5529     if (oop_extra_words > 0) {
5530       addq(var_size_in_bytes, oop_extra_words * HeapWordSize);
5531     }
5532     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5533   }
5534   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5535   jcc(Assembler::above, slow_case);
5536 
5537   // update the tlab top pointer
5538   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5539 
5540   Universe::heap()->compile_prepare_oop(this, obj);
5541 
5542   // recover var_size_in_bytes if necessary
5543   if (var_size_in_bytes == end) {
5544     subptr(var_size_in_bytes, obj);
5545   }
5546   verify_tlab();
5547 }
5548 
5549 // Preserves rbx, and rdx.
5550 Register MacroAssembler::tlab_refill(Label& retry,
5551                                      Label& try_eden,
5552                                      Label& slow_case) {
5553   Register top = rax;
5554   Register t1  = rcx; // object size
5555   Register t2  = rsi;
5556   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5557   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5558   Label do_refill, discard_tlab;
5559 
5560   if (!Universe::heap()->supports_inline_contig_alloc()) {
5561     // No allocation in the shared eden.
5562     jmp(slow_case);
5563   }
5564 
5565   NOT_LP64(get_thread(thread_reg));
5566 
5567   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5568   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5569 
5570   // calculate amount of free space
5571   subptr(t1, top);
5572   shrptr(t1, LogHeapWordSize);
5573 
5574   // Retain tlab and allocate object in shared space if
5575   // the amount free in the tlab is too large to discard.
5576   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5577   jcc(Assembler::lessEqual, discard_tlab);
5578 
5579   // Retain
5580   // %%% yuck as movptr...
5581   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5582   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5583   if (TLABStats) {
5584     // increment number of slow_allocations
5585     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5586   }
5587   jmp(try_eden);
5588 
5589   bind(discard_tlab);
5590   if (TLABStats) {
5591     // increment number of refills
5592     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5593     // accumulate wastage -- t1 is amount free in tlab
5594     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5595   }
5596 
5597   // if tlab is currently allocated (top or end != null) then
5598   // fill [top, end + alignment_reserve) with array object
5599   testptr(top, top);
5600   jcc(Assembler::zero, do_refill);
5601 
5602   // set up the mark word
5603   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5604   // set the length to the remaining space
5605   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5606   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5607   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5608   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5609   // set klass to intArrayKlass
5610   // dubious reloc why not an oop reloc?
5611   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5612   // store klass last.  concurrent gcs assumes klass length is valid if
5613   // klass field is not null.
5614   store_klass(top, t1);
5615 
5616   movptr(t1, top);
5617   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5618   incr_allocated_bytes(thread_reg, t1, 0);
5619 
5620   // refill the tlab with an eden allocation
5621   bind(do_refill);
5622   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5623   shlptr(t1, LogHeapWordSize);
5624   // allocate new tlab, address returned in top
5625   eden_allocate(top, t1, 0, t2, slow_case);
5626 
5627   // Check that t1 was preserved in eden_allocate.
5628 #ifdef ASSERT
5629   if (UseTLAB) {
5630     Label ok;
5631     Register tsize = rsi;
5632     assert_different_registers(tsize, thread_reg, t1);
5633     push(tsize);
5634     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5635     shlptr(tsize, LogHeapWordSize);
5636     cmpptr(t1, tsize);
5637     jcc(Assembler::equal, ok);
5638     STOP("assert(t1 != tlab size)");
5639     should_not_reach_here();
5640 
5641     bind(ok);
5642     pop(tsize);
5643   }
5644 #endif
5645   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5646   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5647   addptr(top, t1);
5648   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5649   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5650 
5651   if (ZeroTLAB) {
5652     // This is a fast TLAB refill, therefore the GC is not notified of it.
5653     // So compiled code must fill the new TLAB with zeroes.
5654     movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5655     zero_memory(top, t1, 0, t2);
5656   }
5657 
5658   verify_tlab();
5659   jmp(retry);
5660 
5661   return thread_reg; // for use by caller
5662 }
5663 
5664 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5665 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5666   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5667   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5668   Label done;
5669 
5670   testptr(length_in_bytes, length_in_bytes);
5671   jcc(Assembler::zero, done);
5672 
5673   // initialize topmost word, divide index by 2, check if odd and test if zero
5674   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5675 #ifdef ASSERT
5676   {
5677     Label L;
5678     testptr(length_in_bytes, BytesPerWord - 1);
5679     jcc(Assembler::zero, L);
5680     stop("length must be a multiple of BytesPerWord");
5681     bind(L);
5682   }
5683 #endif
5684   Register index = length_in_bytes;
5685   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5686   if (UseIncDec) {
5687     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5688   } else {
5689     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5690     shrptr(index, 1);
5691   }
5692 #ifndef _LP64
5693   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5694   {
5695     Label even;
5696     // note: if index was a multiple of 8, then it cannot
5697     //       be 0 now otherwise it must have been 0 before
5698     //       => if it is even, we don't need to check for 0 again
5699     jcc(Assembler::carryClear, even);
5700     // clear topmost word (no jump would be needed if conditional assignment worked here)
5701     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5702     // index could be 0 now, must check again
5703     jcc(Assembler::zero, done);
5704     bind(even);
5705   }
5706 #endif // !_LP64
5707   // initialize remaining object fields: index is a multiple of 2 now
5708   {
5709     Label loop;
5710     bind(loop);
5711     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5712     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5713     decrement(index);
5714     jcc(Assembler::notZero, loop);
5715   }
5716 
5717   bind(done);
5718 }
5719 
5720 void MacroAssembler::incr_allocated_bytes(Register thread,
5721                                           Register var_size_in_bytes,
5722                                           int con_size_in_bytes,
5723                                           Register t1) {
5724   if (!thread->is_valid()) {
5725 #ifdef _LP64
5726     thread = r15_thread;
5727 #else
5728     assert(t1->is_valid(), "need temp reg");
5729     thread = t1;
5730     get_thread(thread);
5731 #endif
5732   }
5733 
5734 #ifdef _LP64
5735   if (var_size_in_bytes->is_valid()) {
5736     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5737   } else {
5738     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5739   }
5740 #else
5741   if (var_size_in_bytes->is_valid()) {
5742     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5743   } else {
5744     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5745   }
5746   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5747 #endif
5748 }
5749 
5750 // Look up the method for a megamorphic invokeinterface call.
5751 // The target method is determined by <intf_klass, itable_index>.
5752 // The receiver klass is in recv_klass.
5753 // On success, the result will be in method_result, and execution falls through.
5754 // On failure, execution transfers to the given label.
5755 void MacroAssembler::lookup_interface_method(Register recv_klass,
5756                                              Register intf_klass,
5757                                              RegisterOrConstant itable_index,
5758                                              Register method_result,
5759                                              Register scan_temp,
5760                                              Label& L_no_such_interface) {
5761   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5762   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5763          "caller must use same register for non-constant itable index as for method");
5764 
5765   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5766   int vtable_base = in_bytes(Klass::vtable_start_offset());
5767   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5768   int scan_step   = itableOffsetEntry::size() * wordSize;
5769   int vte_size    = vtableEntry::size_in_bytes();
5770   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5771   assert(vte_size == wordSize, "else adjust times_vte_scale");
5772 
5773   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5774 
5775   // %%% Could store the aligned, prescaled offset in the klassoop.
5776   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5777 
5778   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5779   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5780   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5781 
5782   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5783   //   if (scan->interface() == intf) {
5784   //     result = (klass + scan->offset() + itable_index);
5785   //   }
5786   // }
5787   Label search, found_method;
5788 
5789   for (int peel = 1; peel >= 0; peel--) {
5790     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5791     cmpptr(intf_klass, method_result);
5792 
5793     if (peel) {
5794       jccb(Assembler::equal, found_method);
5795     } else {
5796       jccb(Assembler::notEqual, search);
5797       // (invert the test to fall through to found_method...)
5798     }
5799 
5800     if (!peel)  break;
5801 
5802     bind(search);
5803 
5804     // Check that the previous entry is non-null.  A null entry means that
5805     // the receiver class doesn't implement the interface, and wasn't the
5806     // same as when the caller was compiled.
5807     testptr(method_result, method_result);
5808     jcc(Assembler::zero, L_no_such_interface);
5809     addptr(scan_temp, scan_step);
5810   }
5811 
5812   bind(found_method);
5813 
5814   // Got a hit.
5815   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5816   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5817 }
5818 
5819 
5820 // virtual method calling
5821 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5822                                            RegisterOrConstant vtable_index,
5823                                            Register method_result) {
5824   const int base = in_bytes(Klass::vtable_start_offset());
5825   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5826   Address vtable_entry_addr(recv_klass,
5827                             vtable_index, Address::times_ptr,
5828                             base + vtableEntry::method_offset_in_bytes());
5829   movptr(method_result, vtable_entry_addr);
5830 }
5831 
5832 
5833 void MacroAssembler::check_klass_subtype(Register sub_klass,
5834                            Register super_klass,
5835                            Register temp_reg,
5836                            Label& L_success) {
5837   Label L_failure;
5838   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5839   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5840   bind(L_failure);
5841 }
5842 
5843 
5844 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5845                                                    Register super_klass,
5846                                                    Register temp_reg,
5847                                                    Label* L_success,
5848                                                    Label* L_failure,
5849                                                    Label* L_slow_path,
5850                                         RegisterOrConstant super_check_offset) {
5851   assert_different_registers(sub_klass, super_klass, temp_reg);
5852   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5853   if (super_check_offset.is_register()) {
5854     assert_different_registers(sub_klass, super_klass,
5855                                super_check_offset.as_register());
5856   } else if (must_load_sco) {
5857     assert(temp_reg != noreg, "supply either a temp or a register offset");
5858   }
5859 
5860   Label L_fallthrough;
5861   int label_nulls = 0;
5862   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5863   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5864   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5865   assert(label_nulls <= 1, "at most one NULL in the batch");
5866 
5867   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5868   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5869   Address super_check_offset_addr(super_klass, sco_offset);
5870 
5871   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5872   // range of a jccb.  If this routine grows larger, reconsider at
5873   // least some of these.
5874 #define local_jcc(assembler_cond, label)                                \
5875   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5876   else                             jcc( assembler_cond, label) /*omit semi*/
5877 
5878   // Hacked jmp, which may only be used just before L_fallthrough.
5879 #define final_jmp(label)                                                \
5880   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5881   else                            jmp(label)                /*omit semi*/
5882 
5883   // If the pointers are equal, we are done (e.g., String[] elements).
5884   // This self-check enables sharing of secondary supertype arrays among
5885   // non-primary types such as array-of-interface.  Otherwise, each such
5886   // type would need its own customized SSA.
5887   // We move this check to the front of the fast path because many
5888   // type checks are in fact trivially successful in this manner,
5889   // so we get a nicely predicted branch right at the start of the check.
5890   cmpptr(sub_klass, super_klass);
5891   local_jcc(Assembler::equal, *L_success);
5892 
5893   // Check the supertype display:
5894   if (must_load_sco) {
5895     // Positive movl does right thing on LP64.
5896     movl(temp_reg, super_check_offset_addr);
5897     super_check_offset = RegisterOrConstant(temp_reg);
5898   }
5899   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5900   cmpptr(super_klass, super_check_addr); // load displayed supertype
5901 
5902   // This check has worked decisively for primary supers.
5903   // Secondary supers are sought in the super_cache ('super_cache_addr').
5904   // (Secondary supers are interfaces and very deeply nested subtypes.)
5905   // This works in the same check above because of a tricky aliasing
5906   // between the super_cache and the primary super display elements.
5907   // (The 'super_check_addr' can address either, as the case requires.)
5908   // Note that the cache is updated below if it does not help us find
5909   // what we need immediately.
5910   // So if it was a primary super, we can just fail immediately.
5911   // Otherwise, it's the slow path for us (no success at this point).
5912 
5913   if (super_check_offset.is_register()) {
5914     local_jcc(Assembler::equal, *L_success);
5915     cmpl(super_check_offset.as_register(), sc_offset);
5916     if (L_failure == &L_fallthrough) {
5917       local_jcc(Assembler::equal, *L_slow_path);
5918     } else {
5919       local_jcc(Assembler::notEqual, *L_failure);
5920       final_jmp(*L_slow_path);
5921     }
5922   } else if (super_check_offset.as_constant() == sc_offset) {
5923     // Need a slow path; fast failure is impossible.
5924     if (L_slow_path == &L_fallthrough) {
5925       local_jcc(Assembler::equal, *L_success);
5926     } else {
5927       local_jcc(Assembler::notEqual, *L_slow_path);
5928       final_jmp(*L_success);
5929     }
5930   } else {
5931     // No slow path; it's a fast decision.
5932     if (L_failure == &L_fallthrough) {
5933       local_jcc(Assembler::equal, *L_success);
5934     } else {
5935       local_jcc(Assembler::notEqual, *L_failure);
5936       final_jmp(*L_success);
5937     }
5938   }
5939 
5940   bind(L_fallthrough);
5941 
5942 #undef local_jcc
5943 #undef final_jmp
5944 }
5945 
5946 
5947 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5948                                                    Register super_klass,
5949                                                    Register temp_reg,
5950                                                    Register temp2_reg,
5951                                                    Label* L_success,
5952                                                    Label* L_failure,
5953                                                    bool set_cond_codes) {
5954   assert_different_registers(sub_klass, super_klass, temp_reg);
5955   if (temp2_reg != noreg)
5956     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5957 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5958 
5959   Label L_fallthrough;
5960   int label_nulls = 0;
5961   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5962   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5963   assert(label_nulls <= 1, "at most one NULL in the batch");
5964 
5965   // a couple of useful fields in sub_klass:
5966   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5967   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5968   Address secondary_supers_addr(sub_klass, ss_offset);
5969   Address super_cache_addr(     sub_klass, sc_offset);
5970 
5971   // Do a linear scan of the secondary super-klass chain.
5972   // This code is rarely used, so simplicity is a virtue here.
5973   // The repne_scan instruction uses fixed registers, which we must spill.
5974   // Don't worry too much about pre-existing connections with the input regs.
5975 
5976   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5977   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5978 
5979   // Get super_klass value into rax (even if it was in rdi or rcx).
5980   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5981   if (super_klass != rax || UseCompressedOops) {
5982     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5983     mov(rax, super_klass);
5984   }
5985   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5986   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5987 
5988 #ifndef PRODUCT
5989   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5990   ExternalAddress pst_counter_addr((address) pst_counter);
5991   NOT_LP64(  incrementl(pst_counter_addr) );
5992   LP64_ONLY( lea(rcx, pst_counter_addr) );
5993   LP64_ONLY( incrementl(Address(rcx, 0)) );
5994 #endif //PRODUCT
5995 
5996   // We will consult the secondary-super array.
5997   movptr(rdi, secondary_supers_addr);
5998   // Load the array length.  (Positive movl does right thing on LP64.)
5999   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6000   // Skip to start of data.
6001   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6002 
6003   // Scan RCX words at [RDI] for an occurrence of RAX.
6004   // Set NZ/Z based on last compare.
6005   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6006   // not change flags (only scas instruction which is repeated sets flags).
6007   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6008 
6009     testptr(rax,rax); // Set Z = 0
6010     repne_scan();
6011 
6012   // Unspill the temp. registers:
6013   if (pushed_rdi)  pop(rdi);
6014   if (pushed_rcx)  pop(rcx);
6015   if (pushed_rax)  pop(rax);
6016 
6017   if (set_cond_codes) {
6018     // Special hack for the AD files:  rdi is guaranteed non-zero.
6019     assert(!pushed_rdi, "rdi must be left non-NULL");
6020     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6021   }
6022 
6023   if (L_failure == &L_fallthrough)
6024         jccb(Assembler::notEqual, *L_failure);
6025   else  jcc(Assembler::notEqual, *L_failure);
6026 
6027   // Success.  Cache the super we found and proceed in triumph.
6028   movptr(super_cache_addr, super_klass);
6029 
6030   if (L_success != &L_fallthrough) {
6031     jmp(*L_success);
6032   }
6033 
6034 #undef IS_A_TEMP
6035 
6036   bind(L_fallthrough);
6037 }
6038 
6039 
6040 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6041   if (VM_Version::supports_cmov()) {
6042     cmovl(cc, dst, src);
6043   } else {
6044     Label L;
6045     jccb(negate_condition(cc), L);
6046     movl(dst, src);
6047     bind(L);
6048   }
6049 }
6050 
6051 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6052   if (VM_Version::supports_cmov()) {
6053     cmovl(cc, dst, src);
6054   } else {
6055     Label L;
6056     jccb(negate_condition(cc), L);
6057     movl(dst, src);
6058     bind(L);
6059   }
6060 }
6061 
6062 void MacroAssembler::verify_oop(Register reg, const char* s) {
6063   if (!VerifyOops) return;
6064 
6065   // Pass register number to verify_oop_subroutine
6066   const char* b = NULL;
6067   {
6068     ResourceMark rm;
6069     stringStream ss;
6070     ss.print("verify_oop: %s: %s", reg->name(), s);
6071     b = code_string(ss.as_string());
6072   }
6073   BLOCK_COMMENT("verify_oop {");
6074 #ifdef _LP64
6075   push(rscratch1);                    // save r10, trashed by movptr()
6076 #endif
6077   push(rax);                          // save rax,
6078   push(reg);                          // pass register argument
6079   ExternalAddress buffer((address) b);
6080   // avoid using pushptr, as it modifies scratch registers
6081   // and our contract is not to modify anything
6082   movptr(rax, buffer.addr());
6083   push(rax);
6084   // call indirectly to solve generation ordering problem
6085   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6086   call(rax);
6087   // Caller pops the arguments (oop, message) and restores rax, r10
6088   BLOCK_COMMENT("} verify_oop");
6089 }
6090 
6091 void MacroAssembler::in_heap_check(Register raddr, Label& done) {
6092   ShenandoahHeap *h = (ShenandoahHeap *)Universe::heap();
6093 
6094   HeapWord* first_region_bottom = h->first_region_bottom();
6095   HeapWord* last_region_end = first_region_bottom + (ShenandoahHeapRegion::RegionSizeBytes / HeapWordSize) * h->max_regions();
6096 
6097   cmpptr(raddr, (intptr_t) first_region_bottom);
6098   jcc(Assembler::less, done);
6099   cmpptr(raddr, (intptr_t) first_region_bottom);
6100   jcc(Assembler::greaterEqual, done);
6101 
6102 }
6103 
6104 void MacroAssembler::shenandoah_cset_check(Register raddr, Register tmp1, Register tmp2, Label& done) {
6105   // Test that oop is not in to-space.
6106   movptr(tmp1, raddr);
6107   shrptr(tmp1, ShenandoahHeapRegion::RegionSizeShift);
6108   movptr(tmp2, (intptr_t) ShenandoahHeap::in_cset_fast_test_addr());
6109   movbool(tmp2, Address(tmp2, tmp1, Address::times_1));
6110   testbool(tmp2);
6111   jcc(Assembler::zero, done);
6112 
6113   // Check for cancelled GC.
6114   movptr(tmp2, (intptr_t) ShenandoahHeap::cancelled_concgc_addr());
6115   movbool(tmp2, Address(tmp2, 0));
6116   testbool(tmp2);
6117   jcc(Assembler::notZero, done);
6118 
6119 }
6120 
6121 void MacroAssembler::_shenandoah_store_addr_check(Address addr, const char* msg, const char* file, int line) {
6122   _shenandoah_store_addr_check(addr.base(), msg, file, line);
6123 }
6124 
6125 void MacroAssembler::_shenandoah_store_addr_check(Register dst, const char* msg, const char* file, int line) {
6126   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6127   if (dst == rsp) return; // Stack-based target
6128 
6129   Register raddr = r9;
6130   Register tmp1 = r10;
6131   Register tmp2 = r11;
6132 
6133   Label done;
6134 
6135   pushf();
6136   push(raddr);
6137   push(tmp1);
6138   push(tmp2);
6139 
6140   movptr(raddr, dst);
6141 
6142   // Check null.
6143   testptr(raddr, raddr);
6144   jcc(Assembler::zero, done);
6145 
6146   in_heap_check(raddr, done);
6147   shenandoah_cset_check(raddr, tmp1, tmp2, done);
6148 
6149   // Fail.
6150   pop(tmp2);
6151   pop(tmp1);
6152   pop(raddr);
6153   popf();
6154   const char* b = NULL;
6155   {
6156     ResourceMark rm;
6157     stringStream ss;
6158     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
6159     b = code_string(ss.as_string());
6160   }
6161   stop(b);
6162 
6163   bind(done);
6164 
6165   pop(tmp2);
6166   pop(tmp1);
6167   pop(raddr);
6168   popf();
6169 }
6170 
6171 void MacroAssembler::_shenandoah_store_check(Register dst, Register value, const char* msg, const char* file, int line) {
6172   if (! UseShenandoahGC || ! ShenandoahStoreCheck) return;
6173   if (dst == rsp) return; // Stack-based target
6174 
6175   Register raddr = r8;
6176   Register rval =  r9;
6177   Register tmp1 = r10;
6178   Register tmp2 = r11;
6179 
6180   // Push tmp regs and flags.
6181   pushf();
6182   push(raddr);
6183   push(rval);
6184   push(tmp1);
6185   push(tmp2);
6186 
6187   movptr(raddr, dst);
6188   movptr(rval, value);
6189 
6190   Label done;
6191 
6192   // If not in-heap target, skip check.
6193   in_heap_check(raddr, done);
6194 
6195   // Test that target oop is not in to-space.
6196   shenandoah_cset_check(raddr, tmp1, tmp2, done);
6197 
6198   // Do value-check only when concurrent mark is in progress.
6199   movptr(tmp1, (intptr_t) ShenandoahHeap::concurrent_mark_in_progress_addr());
6200   movbool(tmp1, Address(tmp1, 0));
6201   testbool(tmp1);
6202   jcc(Assembler::zero, done);
6203 
6204   // Null-check value.
6205   testptr(rval, rval);
6206   jcc(Assembler::zero, done);
6207 
6208   // Test that value oop is not in to-space.
6209   shenandoah_cset_check(rval, tmp1, tmp2, done);
6210 
6211   // Failure.
6212   // Pop tmp regs and flags.
6213   pop(tmp2);
6214   pop(tmp1);
6215   pop(rval);
6216   pop(raddr);
6217   popf();
6218   const char* b = NULL;
6219   {
6220     ResourceMark rm;
6221     stringStream ss;
6222     ss.print("shenandoah_store_check: %s in file: %s line: %i", msg, file, line);
6223     b = code_string(ss.as_string());
6224   }
6225   stop(b);
6226 
6227   bind(done);
6228 
6229   // Pop tmp regs and flags.
6230   pop(tmp2);
6231   pop(tmp1);
6232   pop(rval);
6233   pop(raddr);
6234   popf();
6235 }
6236 
6237 void MacroAssembler::_shenandoah_store_check(Address addr, Register value, const char* msg, const char* file, int line) {
6238   _shenandoah_store_check(addr.base(), value, msg, file, line);
6239 }
6240 
6241 void MacroAssembler::_shenandoah_lock_check(Register dst, const char* msg, const char* file, int line) {
6242 #ifdef ASSERT
6243   if (! UseShenandoahGC && ! ShenandoahStoreCheck) return;
6244 
6245   push(r8);
6246   movptr(r8, Address(dst, BasicObjectLock::obj_offset_in_bytes()));
6247   _shenandoah_store_addr_check(r8, msg, file, line);
6248   pop(r8);
6249 #endif
6250 }
6251 
6252 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6253                                                       Register tmp,
6254                                                       int offset) {
6255   intptr_t value = *delayed_value_addr;
6256   if (value != 0)
6257     return RegisterOrConstant(value + offset);
6258 
6259   // load indirectly to solve generation ordering problem
6260   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6261 
6262 #ifdef ASSERT
6263   { Label L;
6264     testptr(tmp, tmp);
6265     if (WizardMode) {
6266       const char* buf = NULL;
6267       {
6268         ResourceMark rm;
6269         stringStream ss;
6270         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6271         buf = code_string(ss.as_string());
6272       }
6273       jcc(Assembler::notZero, L);
6274       STOP(buf);
6275     } else {
6276       jccb(Assembler::notZero, L);
6277       hlt();
6278     }
6279     bind(L);
6280   }
6281 #endif
6282 
6283   if (offset != 0)
6284     addptr(tmp, offset);
6285 
6286   return RegisterOrConstant(tmp);
6287 }
6288 
6289 
6290 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6291                                          int extra_slot_offset) {
6292   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6293   int stackElementSize = Interpreter::stackElementSize;
6294   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6295 #ifdef ASSERT
6296   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6297   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6298 #endif
6299   Register             scale_reg    = noreg;
6300   Address::ScaleFactor scale_factor = Address::no_scale;
6301   if (arg_slot.is_constant()) {
6302     offset += arg_slot.as_constant() * stackElementSize;
6303   } else {
6304     scale_reg    = arg_slot.as_register();
6305     scale_factor = Address::times(stackElementSize);
6306   }
6307   offset += wordSize;           // return PC is on stack
6308   return Address(rsp, scale_reg, scale_factor, offset);
6309 }
6310 
6311 
6312 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6313   if (!VerifyOops) return;
6314 
6315   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6316   // Pass register number to verify_oop_subroutine
6317   const char* b = NULL;
6318   {
6319     ResourceMark rm;
6320     stringStream ss;
6321     ss.print("verify_oop_addr: %s", s);
6322     b = code_string(ss.as_string());
6323   }
6324 #ifdef _LP64
6325   push(rscratch1);                    // save r10, trashed by movptr()
6326 #endif
6327   push(rax);                          // save rax,
6328   // addr may contain rsp so we will have to adjust it based on the push
6329   // we just did (and on 64 bit we do two pushes)
6330   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6331   // stores rax into addr which is backwards of what was intended.
6332   if (addr.uses(rsp)) {
6333     lea(rax, addr);
6334     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6335   } else {
6336     pushptr(addr);
6337   }
6338 
6339   ExternalAddress buffer((address) b);
6340   // pass msg argument
6341   // avoid using pushptr, as it modifies scratch registers
6342   // and our contract is not to modify anything
6343   movptr(rax, buffer.addr());
6344   push(rax);
6345 
6346   // call indirectly to solve generation ordering problem
6347   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6348   call(rax);
6349   // Caller pops the arguments (addr, message) and restores rax, r10.
6350 }
6351 
6352 void MacroAssembler::verify_tlab() {
6353 #ifdef ASSERT
6354   if (UseTLAB && VerifyOops) {
6355     Label next, ok;
6356     Register t1 = rsi;
6357     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6358 
6359     push(t1);
6360     NOT_LP64(push(thread_reg));
6361     NOT_LP64(get_thread(thread_reg));
6362 
6363     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6364     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6365     jcc(Assembler::aboveEqual, next);
6366     STOP("assert(top >= start)");
6367     should_not_reach_here();
6368 
6369     bind(next);
6370     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6371     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6372     jcc(Assembler::aboveEqual, ok);
6373     STOP("assert(top <= end)");
6374     should_not_reach_here();
6375 
6376     bind(ok);
6377     NOT_LP64(pop(thread_reg));
6378     pop(t1);
6379   }
6380 #endif
6381 }
6382 
6383 class ControlWord {
6384  public:
6385   int32_t _value;
6386 
6387   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6388   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6389   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6390   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6391   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6392   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6393   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6394   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6395 
6396   void print() const {
6397     // rounding control
6398     const char* rc;
6399     switch (rounding_control()) {
6400       case 0: rc = "round near"; break;
6401       case 1: rc = "round down"; break;
6402       case 2: rc = "round up  "; break;
6403       case 3: rc = "chop      "; break;
6404     };
6405     // precision control
6406     const char* pc;
6407     switch (precision_control()) {
6408       case 0: pc = "24 bits "; break;
6409       case 1: pc = "reserved"; break;
6410       case 2: pc = "53 bits "; break;
6411       case 3: pc = "64 bits "; break;
6412     };
6413     // flags
6414     char f[9];
6415     f[0] = ' ';
6416     f[1] = ' ';
6417     f[2] = (precision   ()) ? 'P' : 'p';
6418     f[3] = (underflow   ()) ? 'U' : 'u';
6419     f[4] = (overflow    ()) ? 'O' : 'o';
6420     f[5] = (zero_divide ()) ? 'Z' : 'z';
6421     f[6] = (denormalized()) ? 'D' : 'd';
6422     f[7] = (invalid     ()) ? 'I' : 'i';
6423     f[8] = '\x0';
6424     // output
6425     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6426   }
6427 
6428 };
6429 
6430 class StatusWord {
6431  public:
6432   int32_t _value;
6433 
6434   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6435   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6436   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6437   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6438   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6439   int  top() const                     { return  (_value >> 11) & 7      ; }
6440   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6441   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6442   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6443   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6444   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6445   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6446   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6447   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6448 
6449   void print() const {
6450     // condition codes
6451     char c[5];
6452     c[0] = (C3()) ? '3' : '-';
6453     c[1] = (C2()) ? '2' : '-';
6454     c[2] = (C1()) ? '1' : '-';
6455     c[3] = (C0()) ? '0' : '-';
6456     c[4] = '\x0';
6457     // flags
6458     char f[9];
6459     f[0] = (error_status()) ? 'E' : '-';
6460     f[1] = (stack_fault ()) ? 'S' : '-';
6461     f[2] = (precision   ()) ? 'P' : '-';
6462     f[3] = (underflow   ()) ? 'U' : '-';
6463     f[4] = (overflow    ()) ? 'O' : '-';
6464     f[5] = (zero_divide ()) ? 'Z' : '-';
6465     f[6] = (denormalized()) ? 'D' : '-';
6466     f[7] = (invalid     ()) ? 'I' : '-';
6467     f[8] = '\x0';
6468     // output
6469     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6470   }
6471 
6472 };
6473 
6474 class TagWord {
6475  public:
6476   int32_t _value;
6477 
6478   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6479 
6480   void print() const {
6481     printf("%04x", _value & 0xFFFF);
6482   }
6483 
6484 };
6485 
6486 class FPU_Register {
6487  public:
6488   int32_t _m0;
6489   int32_t _m1;
6490   int16_t _ex;
6491 
6492   bool is_indefinite() const           {
6493     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6494   }
6495 
6496   void print() const {
6497     char  sign = (_ex < 0) ? '-' : '+';
6498     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6499     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6500   };
6501 
6502 };
6503 
6504 class FPU_State {
6505  public:
6506   enum {
6507     register_size       = 10,
6508     number_of_registers =  8,
6509     register_mask       =  7
6510   };
6511 
6512   ControlWord  _control_word;
6513   StatusWord   _status_word;
6514   TagWord      _tag_word;
6515   int32_t      _error_offset;
6516   int32_t      _error_selector;
6517   int32_t      _data_offset;
6518   int32_t      _data_selector;
6519   int8_t       _register[register_size * number_of_registers];
6520 
6521   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6522   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6523 
6524   const char* tag_as_string(int tag) const {
6525     switch (tag) {
6526       case 0: return "valid";
6527       case 1: return "zero";
6528       case 2: return "special";
6529       case 3: return "empty";
6530     }
6531     ShouldNotReachHere();
6532     return NULL;
6533   }
6534 
6535   void print() const {
6536     // print computation registers
6537     { int t = _status_word.top();
6538       for (int i = 0; i < number_of_registers; i++) {
6539         int j = (i - t) & register_mask;
6540         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6541         st(j)->print();
6542         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6543       }
6544     }
6545     printf("\n");
6546     // print control registers
6547     printf("ctrl = "); _control_word.print(); printf("\n");
6548     printf("stat = "); _status_word .print(); printf("\n");
6549     printf("tags = "); _tag_word    .print(); printf("\n");
6550   }
6551 
6552 };
6553 
6554 class Flag_Register {
6555  public:
6556   int32_t _value;
6557 
6558   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6559   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6560   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6561   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6562   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6563   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6564   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6565 
6566   void print() const {
6567     // flags
6568     char f[8];
6569     f[0] = (overflow       ()) ? 'O' : '-';
6570     f[1] = (direction      ()) ? 'D' : '-';
6571     f[2] = (sign           ()) ? 'S' : '-';
6572     f[3] = (zero           ()) ? 'Z' : '-';
6573     f[4] = (auxiliary_carry()) ? 'A' : '-';
6574     f[5] = (parity         ()) ? 'P' : '-';
6575     f[6] = (carry          ()) ? 'C' : '-';
6576     f[7] = '\x0';
6577     // output
6578     printf("%08x  flags = %s", _value, f);
6579   }
6580 
6581 };
6582 
6583 class IU_Register {
6584  public:
6585   int32_t _value;
6586 
6587   void print() const {
6588     printf("%08x  %11d", _value, _value);
6589   }
6590 
6591 };
6592 
6593 class IU_State {
6594  public:
6595   Flag_Register _eflags;
6596   IU_Register   _rdi;
6597   IU_Register   _rsi;
6598   IU_Register   _rbp;
6599   IU_Register   _rsp;
6600   IU_Register   _rbx;
6601   IU_Register   _rdx;
6602   IU_Register   _rcx;
6603   IU_Register   _rax;
6604 
6605   void print() const {
6606     // computation registers
6607     printf("rax,  = "); _rax.print(); printf("\n");
6608     printf("rbx,  = "); _rbx.print(); printf("\n");
6609     printf("rcx  = "); _rcx.print(); printf("\n");
6610     printf("rdx  = "); _rdx.print(); printf("\n");
6611     printf("rdi  = "); _rdi.print(); printf("\n");
6612     printf("rsi  = "); _rsi.print(); printf("\n");
6613     printf("rbp,  = "); _rbp.print(); printf("\n");
6614     printf("rsp  = "); _rsp.print(); printf("\n");
6615     printf("\n");
6616     // control registers
6617     printf("flgs = "); _eflags.print(); printf("\n");
6618   }
6619 };
6620 
6621 
6622 class CPU_State {
6623  public:
6624   FPU_State _fpu_state;
6625   IU_State  _iu_state;
6626 
6627   void print() const {
6628     printf("--------------------------------------------------\n");
6629     _iu_state .print();
6630     printf("\n");
6631     _fpu_state.print();
6632     printf("--------------------------------------------------\n");
6633   }
6634 
6635 };
6636 
6637 
6638 static void _print_CPU_state(CPU_State* state) {
6639   state->print();
6640 };
6641 
6642 
6643 void MacroAssembler::print_CPU_state() {
6644   push_CPU_state();
6645   push(rsp);                // pass CPU state
6646   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6647   addptr(rsp, wordSize);       // discard argument
6648   pop_CPU_state();
6649 }
6650 
6651 
6652 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6653   static int counter = 0;
6654   FPU_State* fs = &state->_fpu_state;
6655   counter++;
6656   // For leaf calls, only verify that the top few elements remain empty.
6657   // We only need 1 empty at the top for C2 code.
6658   if( stack_depth < 0 ) {
6659     if( fs->tag_for_st(7) != 3 ) {
6660       printf("FPR7 not empty\n");
6661       state->print();
6662       assert(false, "error");
6663       return false;
6664     }
6665     return true;                // All other stack states do not matter
6666   }
6667 
6668   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6669          "bad FPU control word");
6670 
6671   // compute stack depth
6672   int i = 0;
6673   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6674   int d = i;
6675   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6676   // verify findings
6677   if (i != FPU_State::number_of_registers) {
6678     // stack not contiguous
6679     printf("%s: stack not contiguous at ST%d\n", s, i);
6680     state->print();
6681     assert(false, "error");
6682     return false;
6683   }
6684   // check if computed stack depth corresponds to expected stack depth
6685   if (stack_depth < 0) {
6686     // expected stack depth is -stack_depth or less
6687     if (d > -stack_depth) {
6688       // too many elements on the stack
6689       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6690       state->print();
6691       assert(false, "error");
6692       return false;
6693     }
6694   } else {
6695     // expected stack depth is stack_depth
6696     if (d != stack_depth) {
6697       // wrong stack depth
6698       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6699       state->print();
6700       assert(false, "error");
6701       return false;
6702     }
6703   }
6704   // everything is cool
6705   return true;
6706 }
6707 
6708 
6709 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6710   if (!VerifyFPU) return;
6711   push_CPU_state();
6712   push(rsp);                // pass CPU state
6713   ExternalAddress msg((address) s);
6714   // pass message string s
6715   pushptr(msg.addr());
6716   push(stack_depth);        // pass stack depth
6717   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6718   addptr(rsp, 3 * wordSize);   // discard arguments
6719   // check for error
6720   { Label L;
6721     testl(rax, rax);
6722     jcc(Assembler::notZero, L);
6723     int3();                  // break if error condition
6724     bind(L);
6725   }
6726   pop_CPU_state();
6727 }
6728 
6729 void MacroAssembler::restore_cpu_control_state_after_jni() {
6730   // Either restore the MXCSR register after returning from the JNI Call
6731   // or verify that it wasn't changed (with -Xcheck:jni flag).
6732   if (VM_Version::supports_sse()) {
6733     if (RestoreMXCSROnJNICalls) {
6734       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6735     } else if (CheckJNICalls) {
6736       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6737     }
6738   }
6739   if (VM_Version::supports_avx()) {
6740     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6741     vzeroupper();
6742   }
6743 
6744 #ifndef _LP64
6745   // Either restore the x87 floating pointer control word after returning
6746   // from the JNI call or verify that it wasn't changed.
6747   if (CheckJNICalls) {
6748     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6749   }
6750 #endif // _LP64
6751 }
6752 
6753 void MacroAssembler::load_mirror(Register mirror, Register method) {
6754   // get mirror
6755   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6756   movptr(mirror, Address(method, Method::const_offset()));
6757   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6758   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6759   movptr(mirror, Address(mirror, mirror_offset));
6760 }
6761 
6762 void MacroAssembler::load_klass(Register dst, Register src) {
6763   if (ShenandoahVerifyReadsToFromSpace) {
6764     oopDesc::bs()->interpreter_read_barrier(this, src);
6765   }
6766 #ifdef _LP64
6767   if (UseCompressedClassPointers) {
6768     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6769     decode_klass_not_null(dst);
6770   } else
6771 #endif
6772     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6773 }
6774 
6775 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6776   load_klass(dst, src);
6777   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6778 }
6779 
6780 void MacroAssembler::store_klass(Register dst, Register src) {
6781 #ifdef _LP64
6782   if (UseCompressedClassPointers) {
6783     encode_klass_not_null(src);
6784     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6785   } else
6786 #endif
6787     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6788 }
6789 
6790 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6791 #ifdef _LP64
6792   // FIXME: Must change all places where we try to load the klass.
6793   if (UseCompressedOops) {
6794     movl(dst, src);
6795     decode_heap_oop(dst);
6796   } else
6797 #endif
6798     movptr(dst, src);
6799 }
6800 
6801 // Doesn't do verfication, generates fixed size code
6802 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6803 #ifdef _LP64
6804   if (UseCompressedOops) {
6805     movl(dst, src);
6806     decode_heap_oop_not_null(dst);
6807   } else
6808 #endif
6809     movptr(dst, src);
6810 }
6811 
6812 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6813 #ifdef _LP64
6814   if (UseCompressedOops) {
6815     assert(!dst.uses(src), "not enough registers");
6816     encode_heap_oop(src);
6817     movl(dst, src);
6818   } else
6819 #endif
6820     movptr(dst, src);
6821 }
6822 
6823 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6824   assert_different_registers(src1, tmp);
6825 #ifdef _LP64
6826   if (UseCompressedOops) {
6827     bool did_push = false;
6828     if (tmp == noreg) {
6829       tmp = rax;
6830       push(tmp);
6831       did_push = true;
6832       assert(!src2.uses(rsp), "can't push");
6833     }
6834     load_heap_oop(tmp, src2);
6835     cmpptr(src1, tmp);
6836     if (did_push)  pop(tmp);
6837   } else
6838 #endif
6839     cmpptr(src1, src2);
6840 }
6841 
6842 // Used for storing NULLs.
6843 void MacroAssembler::store_heap_oop_null(Address dst) {
6844 #ifdef _LP64
6845   if (UseCompressedOops) {
6846     movl(dst, (int32_t)NULL_WORD);
6847   } else {
6848     movslq(dst, (int32_t)NULL_WORD);
6849   }
6850 #else
6851   movl(dst, (int32_t)NULL_WORD);
6852 #endif
6853 }
6854 
6855 #ifdef _LP64
6856 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6857   if (UseCompressedClassPointers) {
6858     // Store to klass gap in destination
6859     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6860   }
6861 }
6862 
6863 #ifdef ASSERT
6864 void MacroAssembler::verify_heapbase(const char* msg) {
6865   assert (UseCompressedOops, "should be compressed");
6866   assert (Universe::heap() != NULL, "java heap should be initialized");
6867   if (CheckCompressedOops) {
6868     Label ok;
6869     push(rscratch1); // cmpptr trashes rscratch1
6870     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6871     jcc(Assembler::equal, ok);
6872     STOP(msg);
6873     bind(ok);
6874     pop(rscratch1);
6875   }
6876 }
6877 #endif
6878 
6879 // Algorithm must match oop.inline.hpp encode_heap_oop.
6880 void MacroAssembler::encode_heap_oop(Register r) {
6881 #ifdef ASSERT
6882   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6883 #endif
6884   verify_oop(r, "broken oop in encode_heap_oop");
6885   if (Universe::narrow_oop_base() == NULL) {
6886     if (Universe::narrow_oop_shift() != 0) {
6887       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6888       shrq(r, LogMinObjAlignmentInBytes);
6889     }
6890     return;
6891   }
6892   testq(r, r);
6893   cmovq(Assembler::equal, r, r12_heapbase);
6894   subq(r, r12_heapbase);
6895   shrq(r, LogMinObjAlignmentInBytes);
6896 }
6897 
6898 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6899 #ifdef ASSERT
6900   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6901   if (CheckCompressedOops) {
6902     Label ok;
6903     testq(r, r);
6904     jcc(Assembler::notEqual, ok);
6905     STOP("null oop passed to encode_heap_oop_not_null");
6906     bind(ok);
6907   }
6908 #endif
6909   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6910   if (Universe::narrow_oop_base() != NULL) {
6911     subq(r, r12_heapbase);
6912   }
6913   if (Universe::narrow_oop_shift() != 0) {
6914     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6915     shrq(r, LogMinObjAlignmentInBytes);
6916   }
6917 }
6918 
6919 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6920 #ifdef ASSERT
6921   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6922   if (CheckCompressedOops) {
6923     Label ok;
6924     testq(src, src);
6925     jcc(Assembler::notEqual, ok);
6926     STOP("null oop passed to encode_heap_oop_not_null2");
6927     bind(ok);
6928   }
6929 #endif
6930   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6931   if (dst != src) {
6932     movq(dst, src);
6933   }
6934   if (Universe::narrow_oop_base() != NULL) {
6935     subq(dst, r12_heapbase);
6936   }
6937   if (Universe::narrow_oop_shift() != 0) {
6938     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6939     shrq(dst, LogMinObjAlignmentInBytes);
6940   }
6941 }
6942 
6943 void  MacroAssembler::decode_heap_oop(Register r) {
6944 #ifdef ASSERT
6945   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6946 #endif
6947   if (Universe::narrow_oop_base() == NULL) {
6948     if (Universe::narrow_oop_shift() != 0) {
6949       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6950       shlq(r, LogMinObjAlignmentInBytes);
6951     }
6952   } else {
6953     Label done;
6954     shlq(r, LogMinObjAlignmentInBytes);
6955     jccb(Assembler::equal, done);
6956     addq(r, r12_heapbase);
6957     bind(done);
6958   }
6959   verify_oop(r, "broken oop in decode_heap_oop");
6960 }
6961 
6962 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6963   // Note: it will change flags
6964   assert (UseCompressedOops, "should only be used for compressed headers");
6965   assert (Universe::heap() != NULL, "java heap should be initialized");
6966   // Cannot assert, unverified entry point counts instructions (see .ad file)
6967   // vtableStubs also counts instructions in pd_code_size_limit.
6968   // Also do not verify_oop as this is called by verify_oop.
6969   if (Universe::narrow_oop_shift() != 0) {
6970     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6971     shlq(r, LogMinObjAlignmentInBytes);
6972     if (Universe::narrow_oop_base() != NULL) {
6973       addq(r, r12_heapbase);
6974     }
6975   } else {
6976     assert (Universe::narrow_oop_base() == NULL, "sanity");
6977   }
6978 }
6979 
6980 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6981   // Note: it will change flags
6982   assert (UseCompressedOops, "should only be used for compressed headers");
6983   assert (Universe::heap() != NULL, "java heap should be initialized");
6984   // Cannot assert, unverified entry point counts instructions (see .ad file)
6985   // vtableStubs also counts instructions in pd_code_size_limit.
6986   // Also do not verify_oop as this is called by verify_oop.
6987   if (Universe::narrow_oop_shift() != 0) {
6988     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6989     if (LogMinObjAlignmentInBytes == Address::times_8) {
6990       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6991     } else {
6992       if (dst != src) {
6993         movq(dst, src);
6994       }
6995       shlq(dst, LogMinObjAlignmentInBytes);
6996       if (Universe::narrow_oop_base() != NULL) {
6997         addq(dst, r12_heapbase);
6998       }
6999     }
7000   } else {
7001     assert (Universe::narrow_oop_base() == NULL, "sanity");
7002     if (dst != src) {
7003       movq(dst, src);
7004     }
7005   }
7006 }
7007 
7008 void MacroAssembler::encode_klass_not_null(Register r) {
7009   if (Universe::narrow_klass_base() != NULL) {
7010     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7011     assert(r != r12_heapbase, "Encoding a klass in r12");
7012     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7013     subq(r, r12_heapbase);
7014   }
7015   if (Universe::narrow_klass_shift() != 0) {
7016     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7017     shrq(r, LogKlassAlignmentInBytes);
7018   }
7019   if (Universe::narrow_klass_base() != NULL) {
7020     reinit_heapbase();
7021   }
7022 }
7023 
7024 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
7025   if (dst == src) {
7026     encode_klass_not_null(src);
7027   } else {
7028     if (Universe::narrow_klass_base() != NULL) {
7029       mov64(dst, (int64_t)Universe::narrow_klass_base());
7030       negq(dst);
7031       addq(dst, src);
7032     } else {
7033       movptr(dst, src);
7034     }
7035     if (Universe::narrow_klass_shift() != 0) {
7036       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7037       shrq(dst, LogKlassAlignmentInBytes);
7038     }
7039   }
7040 }
7041 
7042 // Function instr_size_for_decode_klass_not_null() counts the instructions
7043 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
7044 // when (Universe::heap() != NULL).  Hence, if the instructions they
7045 // generate change, then this method needs to be updated.
7046 int MacroAssembler::instr_size_for_decode_klass_not_null() {
7047   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
7048   if (Universe::narrow_klass_base() != NULL) {
7049     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
7050     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
7051   } else {
7052     // longest load decode klass function, mov64, leaq
7053     return 16;
7054   }
7055 }
7056 
7057 // !!! If the instructions that get generated here change then function
7058 // instr_size_for_decode_klass_not_null() needs to get updated.
7059 void  MacroAssembler::decode_klass_not_null(Register r) {
7060   // Note: it will change flags
7061   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7062   assert(r != r12_heapbase, "Decoding a klass in r12");
7063   // Cannot assert, unverified entry point counts instructions (see .ad file)
7064   // vtableStubs also counts instructions in pd_code_size_limit.
7065   // Also do not verify_oop as this is called by verify_oop.
7066   if (Universe::narrow_klass_shift() != 0) {
7067     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7068     shlq(r, LogKlassAlignmentInBytes);
7069   }
7070   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7071   if (Universe::narrow_klass_base() != NULL) {
7072     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7073     addq(r, r12_heapbase);
7074     reinit_heapbase();
7075   }
7076 }
7077 
7078 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7079   // Note: it will change flags
7080   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7081   if (dst == src) {
7082     decode_klass_not_null(dst);
7083   } else {
7084     // Cannot assert, unverified entry point counts instructions (see .ad file)
7085     // vtableStubs also counts instructions in pd_code_size_limit.
7086     // Also do not verify_oop as this is called by verify_oop.
7087     mov64(dst, (int64_t)Universe::narrow_klass_base());
7088     if (Universe::narrow_klass_shift() != 0) {
7089       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7090       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7091       leaq(dst, Address(dst, src, Address::times_8, 0));
7092     } else {
7093       addq(dst, src);
7094     }
7095   }
7096 }
7097 
7098 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7099   assert (UseCompressedOops, "should only be used for compressed headers");
7100   assert (Universe::heap() != NULL, "java heap should be initialized");
7101   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7102   int oop_index = oop_recorder()->find_index(obj);
7103   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7104   mov_narrow_oop(dst, oop_index, rspec);
7105 }
7106 
7107 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7108   assert (UseCompressedOops, "should only be used for compressed headers");
7109   assert (Universe::heap() != NULL, "java heap should be initialized");
7110   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7111   int oop_index = oop_recorder()->find_index(obj);
7112   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7113   mov_narrow_oop(dst, oop_index, rspec);
7114 }
7115 
7116 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7117   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7118   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7119   int klass_index = oop_recorder()->find_index(k);
7120   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7121   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7122 }
7123 
7124 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7125   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7126   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7127   int klass_index = oop_recorder()->find_index(k);
7128   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7129   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7130 }
7131 
7132 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7133   assert (UseCompressedOops, "should only be used for compressed headers");
7134   assert (Universe::heap() != NULL, "java heap should be initialized");
7135   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7136   int oop_index = oop_recorder()->find_index(obj);
7137   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7138   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7139 }
7140 
7141 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7142   assert (UseCompressedOops, "should only be used for compressed headers");
7143   assert (Universe::heap() != NULL, "java heap should be initialized");
7144   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7145   int oop_index = oop_recorder()->find_index(obj);
7146   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7147   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7148 }
7149 
7150 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7151   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7152   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7153   int klass_index = oop_recorder()->find_index(k);
7154   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7155   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7156 }
7157 
7158 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7159   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7160   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7161   int klass_index = oop_recorder()->find_index(k);
7162   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7163   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7164 }
7165 
7166 void MacroAssembler::reinit_heapbase() {
7167   if (UseCompressedOops || UseCompressedClassPointers) {
7168     if (Universe::heap() != NULL) {
7169       if (Universe::narrow_oop_base() == NULL) {
7170         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7171       } else {
7172         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7173       }
7174     } else {
7175       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7176     }
7177   }
7178 }
7179 
7180 #endif // _LP64
7181 
7182 
7183 // C2 compiled method's prolog code.
7184 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7185 
7186   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7187   // NativeJump::patch_verified_entry will be able to patch out the entry
7188   // code safely. The push to verify stack depth is ok at 5 bytes,
7189   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7190   // stack bang then we must use the 6 byte frame allocation even if
7191   // we have no frame. :-(
7192   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7193 
7194   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7195   // Remove word for return addr
7196   framesize -= wordSize;
7197   stack_bang_size -= wordSize;
7198 
7199   // Calls to C2R adapters often do not accept exceptional returns.
7200   // We require that their callers must bang for them.  But be careful, because
7201   // some VM calls (such as call site linkage) can use several kilobytes of
7202   // stack.  But the stack safety zone should account for that.
7203   // See bugs 4446381, 4468289, 4497237.
7204   if (stack_bang_size > 0) {
7205     generate_stack_overflow_check(stack_bang_size);
7206 
7207     // We always push rbp, so that on return to interpreter rbp, will be
7208     // restored correctly and we can correct the stack.
7209     push(rbp);
7210     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7211     if (PreserveFramePointer) {
7212       mov(rbp, rsp);
7213     }
7214     // Remove word for ebp
7215     framesize -= wordSize;
7216 
7217     // Create frame
7218     if (framesize) {
7219       subptr(rsp, framesize);
7220     }
7221   } else {
7222     // Create frame (force generation of a 4 byte immediate value)
7223     subptr_imm32(rsp, framesize);
7224 
7225     // Save RBP register now.
7226     framesize -= wordSize;
7227     movptr(Address(rsp, framesize), rbp);
7228     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7229     if (PreserveFramePointer) {
7230       movptr(rbp, rsp);
7231       if (framesize > 0) {
7232         addptr(rbp, framesize);
7233       }
7234     }
7235   }
7236 
7237   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7238     framesize -= wordSize;
7239     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7240   }
7241 
7242 #ifndef _LP64
7243   // If method sets FPU control word do it now
7244   if (fp_mode_24b) {
7245     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7246   }
7247   if (UseSSE >= 2 && VerifyFPU) {
7248     verify_FPU(0, "FPU stack must be clean on entry");
7249   }
7250 #endif
7251 
7252 #ifdef ASSERT
7253   if (VerifyStackAtCalls) {
7254     Label L;
7255     push(rax);
7256     mov(rax, rsp);
7257     andptr(rax, StackAlignmentInBytes-1);
7258     cmpptr(rax, StackAlignmentInBytes-wordSize);
7259     pop(rax);
7260     jcc(Assembler::equal, L);
7261     STOP("Stack is not properly aligned!");
7262     bind(L);
7263   }
7264 #endif
7265 
7266 }
7267 
7268 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7269   // cnt - number of qwords (8-byte words).
7270   // base - start address, qword aligned.
7271   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7272   assert(base==rdi, "base register must be edi for rep stos");
7273   assert(tmp==rax,   "tmp register must be eax for rep stos");
7274   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7275   assert(InitArrayShortSize % BytesPerLong == 0,
7276     "InitArrayShortSize should be the multiple of BytesPerLong");
7277 
7278   Label DONE;
7279 
7280   xorptr(tmp, tmp);
7281 
7282   if (!is_large) {
7283     Label LOOP, LONG;
7284     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7285     jccb(Assembler::greater, LONG);
7286 
7287     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7288 
7289     decrement(cnt);
7290     jccb(Assembler::negative, DONE); // Zero length
7291 
7292     // Use individual pointer-sized stores for small counts:
7293     BIND(LOOP);
7294     movptr(Address(base, cnt, Address::times_ptr), tmp);
7295     decrement(cnt);
7296     jccb(Assembler::greaterEqual, LOOP);
7297     jmpb(DONE);
7298 
7299     BIND(LONG);
7300   }
7301 
7302   // Use longer rep-prefixed ops for non-small counts:
7303   if (UseFastStosb) {
7304     shlptr(cnt, 3); // convert to number of bytes
7305     rep_stosb();
7306   } else {
7307     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7308     rep_stos();
7309   }
7310 
7311   BIND(DONE);
7312 }
7313 
7314 #ifdef COMPILER2
7315 
7316 // IndexOf for constant substrings with size >= 8 chars
7317 // which don't need to be loaded through stack.
7318 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7319                                       Register cnt1, Register cnt2,
7320                                       int int_cnt2,  Register result,
7321                                       XMMRegister vec, Register tmp,
7322                                       int ae) {
7323   ShortBranchVerifier sbv(this);
7324   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7325   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7326 
7327   // This method uses the pcmpestri instruction with bound registers
7328   //   inputs:
7329   //     xmm - substring
7330   //     rax - substring length (elements count)
7331   //     mem - scanned string
7332   //     rdx - string length (elements count)
7333   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7334   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7335   //   outputs:
7336   //     rcx - matched index in string
7337   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7338   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7339   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7340   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7341   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7342 
7343   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7344         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7345         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7346 
7347   // Note, inline_string_indexOf() generates checks:
7348   // if (substr.count > string.count) return -1;
7349   // if (substr.count == 0) return 0;
7350   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7351 
7352   // Load substring.
7353   if (ae == StrIntrinsicNode::UL) {
7354     pmovzxbw(vec, Address(str2, 0));
7355   } else {
7356     movdqu(vec, Address(str2, 0));
7357   }
7358   movl(cnt2, int_cnt2);
7359   movptr(result, str1); // string addr
7360 
7361   if (int_cnt2 > stride) {
7362     jmpb(SCAN_TO_SUBSTR);
7363 
7364     // Reload substr for rescan, this code
7365     // is executed only for large substrings (> 8 chars)
7366     bind(RELOAD_SUBSTR);
7367     if (ae == StrIntrinsicNode::UL) {
7368       pmovzxbw(vec, Address(str2, 0));
7369     } else {
7370       movdqu(vec, Address(str2, 0));
7371     }
7372     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7373 
7374     bind(RELOAD_STR);
7375     // We came here after the beginning of the substring was
7376     // matched but the rest of it was not so we need to search
7377     // again. Start from the next element after the previous match.
7378 
7379     // cnt2 is number of substring reminding elements and
7380     // cnt1 is number of string reminding elements when cmp failed.
7381     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7382     subl(cnt1, cnt2);
7383     addl(cnt1, int_cnt2);
7384     movl(cnt2, int_cnt2); // Now restore cnt2
7385 
7386     decrementl(cnt1);     // Shift to next element
7387     cmpl(cnt1, cnt2);
7388     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7389 
7390     addptr(result, (1<<scale1));
7391 
7392   } // (int_cnt2 > 8)
7393 
7394   // Scan string for start of substr in 16-byte vectors
7395   bind(SCAN_TO_SUBSTR);
7396   pcmpestri(vec, Address(result, 0), mode);
7397   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7398   subl(cnt1, stride);
7399   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7400   cmpl(cnt1, cnt2);
7401   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7402   addptr(result, 16);
7403   jmpb(SCAN_TO_SUBSTR);
7404 
7405   // Found a potential substr
7406   bind(FOUND_CANDIDATE);
7407   // Matched whole vector if first element matched (tmp(rcx) == 0).
7408   if (int_cnt2 == stride) {
7409     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7410   } else { // int_cnt2 > 8
7411     jccb(Assembler::overflow, FOUND_SUBSTR);
7412   }
7413   // After pcmpestri tmp(rcx) contains matched element index
7414   // Compute start addr of substr
7415   lea(result, Address(result, tmp, scale1));
7416 
7417   // Make sure string is still long enough
7418   subl(cnt1, tmp);
7419   cmpl(cnt1, cnt2);
7420   if (int_cnt2 == stride) {
7421     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7422   } else { // int_cnt2 > 8
7423     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7424   }
7425   // Left less then substring.
7426 
7427   bind(RET_NOT_FOUND);
7428   movl(result, -1);
7429   jmp(EXIT);
7430 
7431   if (int_cnt2 > stride) {
7432     // This code is optimized for the case when whole substring
7433     // is matched if its head is matched.
7434     bind(MATCH_SUBSTR_HEAD);
7435     pcmpestri(vec, Address(result, 0), mode);
7436     // Reload only string if does not match
7437     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7438 
7439     Label CONT_SCAN_SUBSTR;
7440     // Compare the rest of substring (> 8 chars).
7441     bind(FOUND_SUBSTR);
7442     // First 8 chars are already matched.
7443     negptr(cnt2);
7444     addptr(cnt2, stride);
7445 
7446     bind(SCAN_SUBSTR);
7447     subl(cnt1, stride);
7448     cmpl(cnt2, -stride); // Do not read beyond substring
7449     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7450     // Back-up strings to avoid reading beyond substring:
7451     // cnt1 = cnt1 - cnt2 + 8
7452     addl(cnt1, cnt2); // cnt2 is negative
7453     addl(cnt1, stride);
7454     movl(cnt2, stride); negptr(cnt2);
7455     bind(CONT_SCAN_SUBSTR);
7456     if (int_cnt2 < (int)G) {
7457       int tail_off1 = int_cnt2<<scale1;
7458       int tail_off2 = int_cnt2<<scale2;
7459       if (ae == StrIntrinsicNode::UL) {
7460         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7461       } else {
7462         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7463       }
7464       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7465     } else {
7466       // calculate index in register to avoid integer overflow (int_cnt2*2)
7467       movl(tmp, int_cnt2);
7468       addptr(tmp, cnt2);
7469       if (ae == StrIntrinsicNode::UL) {
7470         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7471       } else {
7472         movdqu(vec, Address(str2, tmp, scale2, 0));
7473       }
7474       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7475     }
7476     // Need to reload strings pointers if not matched whole vector
7477     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7478     addptr(cnt2, stride);
7479     jcc(Assembler::negative, SCAN_SUBSTR);
7480     // Fall through if found full substring
7481 
7482   } // (int_cnt2 > 8)
7483 
7484   bind(RET_FOUND);
7485   // Found result if we matched full small substring.
7486   // Compute substr offset
7487   subptr(result, str1);
7488   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7489     shrl(result, 1); // index
7490   }
7491   bind(EXIT);
7492 
7493 } // string_indexofC8
7494 
7495 // Small strings are loaded through stack if they cross page boundary.
7496 void MacroAssembler::string_indexof(Register str1, Register str2,
7497                                     Register cnt1, Register cnt2,
7498                                     int int_cnt2,  Register result,
7499                                     XMMRegister vec, Register tmp,
7500                                     int ae) {
7501   ShortBranchVerifier sbv(this);
7502   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7503   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7504 
7505   //
7506   // int_cnt2 is length of small (< 8 chars) constant substring
7507   // or (-1) for non constant substring in which case its length
7508   // is in cnt2 register.
7509   //
7510   // Note, inline_string_indexOf() generates checks:
7511   // if (substr.count > string.count) return -1;
7512   // if (substr.count == 0) return 0;
7513   //
7514   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7515   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7516   // This method uses the pcmpestri instruction with bound registers
7517   //   inputs:
7518   //     xmm - substring
7519   //     rax - substring length (elements count)
7520   //     mem - scanned string
7521   //     rdx - string length (elements count)
7522   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7523   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7524   //   outputs:
7525   //     rcx - matched index in string
7526   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7527   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7528   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7529   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7530 
7531   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7532         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7533         FOUND_CANDIDATE;
7534 
7535   { //========================================================
7536     // We don't know where these strings are located
7537     // and we can't read beyond them. Load them through stack.
7538     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7539 
7540     movptr(tmp, rsp); // save old SP
7541 
7542     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7543       if (int_cnt2 == (1>>scale2)) { // One byte
7544         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7545         load_unsigned_byte(result, Address(str2, 0));
7546         movdl(vec, result); // move 32 bits
7547       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7548         // Not enough header space in 32-bit VM: 12+3 = 15.
7549         movl(result, Address(str2, -1));
7550         shrl(result, 8);
7551         movdl(vec, result); // move 32 bits
7552       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7553         load_unsigned_short(result, Address(str2, 0));
7554         movdl(vec, result); // move 32 bits
7555       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7556         movdl(vec, Address(str2, 0)); // move 32 bits
7557       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7558         movq(vec, Address(str2, 0));  // move 64 bits
7559       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7560         // Array header size is 12 bytes in 32-bit VM
7561         // + 6 bytes for 3 chars == 18 bytes,
7562         // enough space to load vec and shift.
7563         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7564         if (ae == StrIntrinsicNode::UL) {
7565           int tail_off = int_cnt2-8;
7566           pmovzxbw(vec, Address(str2, tail_off));
7567           psrldq(vec, -2*tail_off);
7568         }
7569         else {
7570           int tail_off = int_cnt2*(1<<scale2);
7571           movdqu(vec, Address(str2, tail_off-16));
7572           psrldq(vec, 16-tail_off);
7573         }
7574       }
7575     } else { // not constant substring
7576       cmpl(cnt2, stride);
7577       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7578 
7579       // We can read beyond string if srt+16 does not cross page boundary
7580       // since heaps are aligned and mapped by pages.
7581       assert(os::vm_page_size() < (int)G, "default page should be small");
7582       movl(result, str2); // We need only low 32 bits
7583       andl(result, (os::vm_page_size()-1));
7584       cmpl(result, (os::vm_page_size()-16));
7585       jccb(Assembler::belowEqual, CHECK_STR);
7586 
7587       // Move small strings to stack to allow load 16 bytes into vec.
7588       subptr(rsp, 16);
7589       int stk_offset = wordSize-(1<<scale2);
7590       push(cnt2);
7591 
7592       bind(COPY_SUBSTR);
7593       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7594         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7595         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7596       } else if (ae == StrIntrinsicNode::UU) {
7597         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7598         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7599       }
7600       decrement(cnt2);
7601       jccb(Assembler::notZero, COPY_SUBSTR);
7602 
7603       pop(cnt2);
7604       movptr(str2, rsp);  // New substring address
7605     } // non constant
7606 
7607     bind(CHECK_STR);
7608     cmpl(cnt1, stride);
7609     jccb(Assembler::aboveEqual, BIG_STRINGS);
7610 
7611     // Check cross page boundary.
7612     movl(result, str1); // We need only low 32 bits
7613     andl(result, (os::vm_page_size()-1));
7614     cmpl(result, (os::vm_page_size()-16));
7615     jccb(Assembler::belowEqual, BIG_STRINGS);
7616 
7617     subptr(rsp, 16);
7618     int stk_offset = -(1<<scale1);
7619     if (int_cnt2 < 0) { // not constant
7620       push(cnt2);
7621       stk_offset += wordSize;
7622     }
7623     movl(cnt2, cnt1);
7624 
7625     bind(COPY_STR);
7626     if (ae == StrIntrinsicNode::LL) {
7627       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7628       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7629     } else {
7630       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7631       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7632     }
7633     decrement(cnt2);
7634     jccb(Assembler::notZero, COPY_STR);
7635 
7636     if (int_cnt2 < 0) { // not constant
7637       pop(cnt2);
7638     }
7639     movptr(str1, rsp);  // New string address
7640 
7641     bind(BIG_STRINGS);
7642     // Load substring.
7643     if (int_cnt2 < 0) { // -1
7644       if (ae == StrIntrinsicNode::UL) {
7645         pmovzxbw(vec, Address(str2, 0));
7646       } else {
7647         movdqu(vec, Address(str2, 0));
7648       }
7649       push(cnt2);       // substr count
7650       push(str2);       // substr addr
7651       push(str1);       // string addr
7652     } else {
7653       // Small (< 8 chars) constant substrings are loaded already.
7654       movl(cnt2, int_cnt2);
7655     }
7656     push(tmp);  // original SP
7657 
7658   } // Finished loading
7659 
7660   //========================================================
7661   // Start search
7662   //
7663 
7664   movptr(result, str1); // string addr
7665 
7666   if (int_cnt2  < 0) {  // Only for non constant substring
7667     jmpb(SCAN_TO_SUBSTR);
7668 
7669     // SP saved at sp+0
7670     // String saved at sp+1*wordSize
7671     // Substr saved at sp+2*wordSize
7672     // Substr count saved at sp+3*wordSize
7673 
7674     // Reload substr for rescan, this code
7675     // is executed only for large substrings (> 8 chars)
7676     bind(RELOAD_SUBSTR);
7677     movptr(str2, Address(rsp, 2*wordSize));
7678     movl(cnt2, Address(rsp, 3*wordSize));
7679     if (ae == StrIntrinsicNode::UL) {
7680       pmovzxbw(vec, Address(str2, 0));
7681     } else {
7682       movdqu(vec, Address(str2, 0));
7683     }
7684     // We came here after the beginning of the substring was
7685     // matched but the rest of it was not so we need to search
7686     // again. Start from the next element after the previous match.
7687     subptr(str1, result); // Restore counter
7688     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7689       shrl(str1, 1);
7690     }
7691     addl(cnt1, str1);
7692     decrementl(cnt1);   // Shift to next element
7693     cmpl(cnt1, cnt2);
7694     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7695 
7696     addptr(result, (1<<scale1));
7697   } // non constant
7698 
7699   // Scan string for start of substr in 16-byte vectors
7700   bind(SCAN_TO_SUBSTR);
7701   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7702   pcmpestri(vec, Address(result, 0), mode);
7703   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7704   subl(cnt1, stride);
7705   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7706   cmpl(cnt1, cnt2);
7707   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7708   addptr(result, 16);
7709 
7710   bind(ADJUST_STR);
7711   cmpl(cnt1, stride); // Do not read beyond string
7712   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7713   // Back-up string to avoid reading beyond string.
7714   lea(result, Address(result, cnt1, scale1, -16));
7715   movl(cnt1, stride);
7716   jmpb(SCAN_TO_SUBSTR);
7717 
7718   // Found a potential substr
7719   bind(FOUND_CANDIDATE);
7720   // After pcmpestri tmp(rcx) contains matched element index
7721 
7722   // Make sure string is still long enough
7723   subl(cnt1, tmp);
7724   cmpl(cnt1, cnt2);
7725   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7726   // Left less then substring.
7727 
7728   bind(RET_NOT_FOUND);
7729   movl(result, -1);
7730   jmpb(CLEANUP);
7731 
7732   bind(FOUND_SUBSTR);
7733   // Compute start addr of substr
7734   lea(result, Address(result, tmp, scale1));
7735   if (int_cnt2 > 0) { // Constant substring
7736     // Repeat search for small substring (< 8 chars)
7737     // from new point without reloading substring.
7738     // Have to check that we don't read beyond string.
7739     cmpl(tmp, stride-int_cnt2);
7740     jccb(Assembler::greater, ADJUST_STR);
7741     // Fall through if matched whole substring.
7742   } else { // non constant
7743     assert(int_cnt2 == -1, "should be != 0");
7744 
7745     addl(tmp, cnt2);
7746     // Found result if we matched whole substring.
7747     cmpl(tmp, stride);
7748     jccb(Assembler::lessEqual, RET_FOUND);
7749 
7750     // Repeat search for small substring (<= 8 chars)
7751     // from new point 'str1' without reloading substring.
7752     cmpl(cnt2, stride);
7753     // Have to check that we don't read beyond string.
7754     jccb(Assembler::lessEqual, ADJUST_STR);
7755 
7756     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7757     // Compare the rest of substring (> 8 chars).
7758     movptr(str1, result);
7759 
7760     cmpl(tmp, cnt2);
7761     // First 8 chars are already matched.
7762     jccb(Assembler::equal, CHECK_NEXT);
7763 
7764     bind(SCAN_SUBSTR);
7765     pcmpestri(vec, Address(str1, 0), mode);
7766     // Need to reload strings pointers if not matched whole vector
7767     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7768 
7769     bind(CHECK_NEXT);
7770     subl(cnt2, stride);
7771     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7772     addptr(str1, 16);
7773     if (ae == StrIntrinsicNode::UL) {
7774       addptr(str2, 8);
7775     } else {
7776       addptr(str2, 16);
7777     }
7778     subl(cnt1, stride);
7779     cmpl(cnt2, stride); // Do not read beyond substring
7780     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7781     // Back-up strings to avoid reading beyond substring.
7782 
7783     if (ae == StrIntrinsicNode::UL) {
7784       lea(str2, Address(str2, cnt2, scale2, -8));
7785       lea(str1, Address(str1, cnt2, scale1, -16));
7786     } else {
7787       lea(str2, Address(str2, cnt2, scale2, -16));
7788       lea(str1, Address(str1, cnt2, scale1, -16));
7789     }
7790     subl(cnt1, cnt2);
7791     movl(cnt2, stride);
7792     addl(cnt1, stride);
7793     bind(CONT_SCAN_SUBSTR);
7794     if (ae == StrIntrinsicNode::UL) {
7795       pmovzxbw(vec, Address(str2, 0));
7796     } else {
7797       movdqu(vec, Address(str2, 0));
7798     }
7799     jmp(SCAN_SUBSTR);
7800 
7801     bind(RET_FOUND_LONG);
7802     movptr(str1, Address(rsp, wordSize));
7803   } // non constant
7804 
7805   bind(RET_FOUND);
7806   // Compute substr offset
7807   subptr(result, str1);
7808   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7809     shrl(result, 1); // index
7810   }
7811   bind(CLEANUP);
7812   pop(rsp); // restore SP
7813 
7814 } // string_indexof
7815 
7816 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7817                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7818   ShortBranchVerifier sbv(this);
7819   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7820 
7821   int stride = 8;
7822 
7823   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7824         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7825         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7826         FOUND_SEQ_CHAR, DONE_LABEL;
7827 
7828   movptr(result, str1);
7829   if (UseAVX >= 2) {
7830     cmpl(cnt1, stride);
7831     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7832     cmpl(cnt1, 2*stride);
7833     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7834     movdl(vec1, ch);
7835     vpbroadcastw(vec1, vec1);
7836     vpxor(vec2, vec2);
7837     movl(tmp, cnt1);
7838     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7839     andl(cnt1,0x0000000F);  //tail count (in chars)
7840 
7841     bind(SCAN_TO_16_CHAR_LOOP);
7842     vmovdqu(vec3, Address(result, 0));
7843     vpcmpeqw(vec3, vec3, vec1, 1);
7844     vptest(vec2, vec3);
7845     jcc(Assembler::carryClear, FOUND_CHAR);
7846     addptr(result, 32);
7847     subl(tmp, 2*stride);
7848     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7849     jmp(SCAN_TO_8_CHAR);
7850     bind(SCAN_TO_8_CHAR_INIT);
7851     movdl(vec1, ch);
7852     pshuflw(vec1, vec1, 0x00);
7853     pshufd(vec1, vec1, 0);
7854     pxor(vec2, vec2);
7855   }
7856   bind(SCAN_TO_8_CHAR);
7857   cmpl(cnt1, stride);
7858   if (UseAVX >= 2) {
7859     jcc(Assembler::less, SCAN_TO_CHAR);
7860   } else {
7861     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7862     movdl(vec1, ch);
7863     pshuflw(vec1, vec1, 0x00);
7864     pshufd(vec1, vec1, 0);
7865     pxor(vec2, vec2);
7866   }
7867   movl(tmp, cnt1);
7868   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7869   andl(cnt1,0x00000007);  //tail count (in chars)
7870 
7871   bind(SCAN_TO_8_CHAR_LOOP);
7872   movdqu(vec3, Address(result, 0));
7873   pcmpeqw(vec3, vec1);
7874   ptest(vec2, vec3);
7875   jcc(Assembler::carryClear, FOUND_CHAR);
7876   addptr(result, 16);
7877   subl(tmp, stride);
7878   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7879   bind(SCAN_TO_CHAR);
7880   testl(cnt1, cnt1);
7881   jcc(Assembler::zero, RET_NOT_FOUND);
7882   bind(SCAN_TO_CHAR_LOOP);
7883   load_unsigned_short(tmp, Address(result, 0));
7884   cmpl(ch, tmp);
7885   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7886   addptr(result, 2);
7887   subl(cnt1, 1);
7888   jccb(Assembler::zero, RET_NOT_FOUND);
7889   jmp(SCAN_TO_CHAR_LOOP);
7890 
7891   bind(RET_NOT_FOUND);
7892   movl(result, -1);
7893   jmpb(DONE_LABEL);
7894 
7895   bind(FOUND_CHAR);
7896   if (UseAVX >= 2) {
7897     vpmovmskb(tmp, vec3);
7898   } else {
7899     pmovmskb(tmp, vec3);
7900   }
7901   bsfl(ch, tmp);
7902   addl(result, ch);
7903 
7904   bind(FOUND_SEQ_CHAR);
7905   subptr(result, str1);
7906   shrl(result, 1);
7907 
7908   bind(DONE_LABEL);
7909 } // string_indexof_char
7910 
7911 // helper function for string_compare
7912 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7913                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7914                                         Address::ScaleFactor scale2, Register index, int ae) {
7915   if (ae == StrIntrinsicNode::LL) {
7916     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7917     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7918   } else if (ae == StrIntrinsicNode::UU) {
7919     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7920     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7921   } else {
7922     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7923     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7924   }
7925 }
7926 
7927 // Compare strings, used for char[] and byte[].
7928 void MacroAssembler::string_compare(Register str1, Register str2,
7929                                     Register cnt1, Register cnt2, Register result,
7930                                     XMMRegister vec1, int ae) {
7931   ShortBranchVerifier sbv(this);
7932   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7933   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7934   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7935   int stride2x2 = 0x40;
7936   Address::ScaleFactor scale = Address::no_scale;
7937   Address::ScaleFactor scale1 = Address::no_scale;
7938   Address::ScaleFactor scale2 = Address::no_scale;
7939 
7940   if (ae != StrIntrinsicNode::LL) {
7941     stride2x2 = 0x20;
7942   }
7943 
7944   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7945     shrl(cnt2, 1);
7946   }
7947   // Compute the minimum of the string lengths and the
7948   // difference of the string lengths (stack).
7949   // Do the conditional move stuff
7950   movl(result, cnt1);
7951   subl(cnt1, cnt2);
7952   push(cnt1);
7953   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7954 
7955   // Is the minimum length zero?
7956   testl(cnt2, cnt2);
7957   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7958   if (ae == StrIntrinsicNode::LL) {
7959     // Load first bytes
7960     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7961     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7962   } else if (ae == StrIntrinsicNode::UU) {
7963     // Load first characters
7964     load_unsigned_short(result, Address(str1, 0));
7965     load_unsigned_short(cnt1, Address(str2, 0));
7966   } else {
7967     load_unsigned_byte(result, Address(str1, 0));
7968     load_unsigned_short(cnt1, Address(str2, 0));
7969   }
7970   subl(result, cnt1);
7971   jcc(Assembler::notZero,  POP_LABEL);
7972 
7973   if (ae == StrIntrinsicNode::UU) {
7974     // Divide length by 2 to get number of chars
7975     shrl(cnt2, 1);
7976   }
7977   cmpl(cnt2, 1);
7978   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7979 
7980   // Check if the strings start at the same location and setup scale and stride
7981   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7982     cmpptr(str1, str2);
7983     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7984     if (ae == StrIntrinsicNode::LL) {
7985       scale = Address::times_1;
7986       stride = 16;
7987     } else {
7988       scale = Address::times_2;
7989       stride = 8;
7990     }
7991   } else {
7992     scale1 = Address::times_1;
7993     scale2 = Address::times_2;
7994     // scale not used
7995     stride = 8;
7996   }
7997 
7998   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7999     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
8000     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
8001     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
8002     Label COMPARE_TAIL_LONG;
8003     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
8004 
8005     int pcmpmask = 0x19;
8006     if (ae == StrIntrinsicNode::LL) {
8007       pcmpmask &= ~0x01;
8008     }
8009 
8010     // Setup to compare 16-chars (32-bytes) vectors,
8011     // start from first character again because it has aligned address.
8012     if (ae == StrIntrinsicNode::LL) {
8013       stride2 = 32;
8014     } else {
8015       stride2 = 16;
8016     }
8017     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8018       adr_stride = stride << scale;
8019     } else {
8020       adr_stride1 = 8;  //stride << scale1;
8021       adr_stride2 = 16; //stride << scale2;
8022     }
8023 
8024     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8025     // rax and rdx are used by pcmpestri as elements counters
8026     movl(result, cnt2);
8027     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
8028     jcc(Assembler::zero, COMPARE_TAIL_LONG);
8029 
8030     // fast path : compare first 2 8-char vectors.
8031     bind(COMPARE_16_CHARS);
8032     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8033       movdqu(vec1, Address(str1, 0));
8034     } else {
8035       pmovzxbw(vec1, Address(str1, 0));
8036     }
8037     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8038     jccb(Assembler::below, COMPARE_INDEX_CHAR);
8039 
8040     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8041       movdqu(vec1, Address(str1, adr_stride));
8042       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
8043     } else {
8044       pmovzxbw(vec1, Address(str1, adr_stride1));
8045       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
8046     }
8047     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
8048     addl(cnt1, stride);
8049 
8050     // Compare the characters at index in cnt1
8051     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8052     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8053     subl(result, cnt2);
8054     jmp(POP_LABEL);
8055 
8056     // Setup the registers to start vector comparison loop
8057     bind(COMPARE_WIDE_VECTORS);
8058     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8059       lea(str1, Address(str1, result, scale));
8060       lea(str2, Address(str2, result, scale));
8061     } else {
8062       lea(str1, Address(str1, result, scale1));
8063       lea(str2, Address(str2, result, scale2));
8064     }
8065     subl(result, stride2);
8066     subl(cnt2, stride2);
8067     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8068     negptr(result);
8069 
8070     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8071     bind(COMPARE_WIDE_VECTORS_LOOP);
8072 
8073 #ifdef _LP64
8074     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8075       cmpl(cnt2, stride2x2);
8076       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8077       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8078       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8079 
8080       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8081       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8082         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8083         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8084       } else {
8085         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8086         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8087       }
8088       kortestql(k7, k7);
8089       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8090       addptr(result, stride2x2);  // update since we already compared at this addr
8091       subl(cnt2, stride2x2);      // and sub the size too
8092       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8093 
8094       vpxor(vec1, vec1);
8095       jmpb(COMPARE_WIDE_TAIL);
8096     }//if (VM_Version::supports_avx512vlbw())
8097 #endif // _LP64
8098 
8099 
8100     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8101     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8102       vmovdqu(vec1, Address(str1, result, scale));
8103       vpxor(vec1, Address(str2, result, scale));
8104     } else {
8105       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8106       vpxor(vec1, Address(str2, result, scale2));
8107     }
8108     vptest(vec1, vec1);
8109     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8110     addptr(result, stride2);
8111     subl(cnt2, stride2);
8112     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8113     // clean upper bits of YMM registers
8114     vpxor(vec1, vec1);
8115 
8116     // compare wide vectors tail
8117     bind(COMPARE_WIDE_TAIL);
8118     testptr(result, result);
8119     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8120 
8121     movl(result, stride2);
8122     movl(cnt2, result);
8123     negptr(result);
8124     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8125 
8126     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8127     bind(VECTOR_NOT_EQUAL);
8128     // clean upper bits of YMM registers
8129     vpxor(vec1, vec1);
8130     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8131       lea(str1, Address(str1, result, scale));
8132       lea(str2, Address(str2, result, scale));
8133     } else {
8134       lea(str1, Address(str1, result, scale1));
8135       lea(str2, Address(str2, result, scale2));
8136     }
8137     jmp(COMPARE_16_CHARS);
8138 
8139     // Compare tail chars, length between 1 to 15 chars
8140     bind(COMPARE_TAIL_LONG);
8141     movl(cnt2, result);
8142     cmpl(cnt2, stride);
8143     jcc(Assembler::less, COMPARE_SMALL_STR);
8144 
8145     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8146       movdqu(vec1, Address(str1, 0));
8147     } else {
8148       pmovzxbw(vec1, Address(str1, 0));
8149     }
8150     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8151     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8152     subptr(cnt2, stride);
8153     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8154     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8155       lea(str1, Address(str1, result, scale));
8156       lea(str2, Address(str2, result, scale));
8157     } else {
8158       lea(str1, Address(str1, result, scale1));
8159       lea(str2, Address(str2, result, scale2));
8160     }
8161     negptr(cnt2);
8162     jmpb(WHILE_HEAD_LABEL);
8163 
8164     bind(COMPARE_SMALL_STR);
8165   } else if (UseSSE42Intrinsics) {
8166     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8167     int pcmpmask = 0x19;
8168     // Setup to compare 8-char (16-byte) vectors,
8169     // start from first character again because it has aligned address.
8170     movl(result, cnt2);
8171     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8172     if (ae == StrIntrinsicNode::LL) {
8173       pcmpmask &= ~0x01;
8174     }
8175     jcc(Assembler::zero, COMPARE_TAIL);
8176     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8177       lea(str1, Address(str1, result, scale));
8178       lea(str2, Address(str2, result, scale));
8179     } else {
8180       lea(str1, Address(str1, result, scale1));
8181       lea(str2, Address(str2, result, scale2));
8182     }
8183     negptr(result);
8184 
8185     // pcmpestri
8186     //   inputs:
8187     //     vec1- substring
8188     //     rax - negative string length (elements count)
8189     //     mem - scanned string
8190     //     rdx - string length (elements count)
8191     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8192     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8193     //   outputs:
8194     //     rcx - first mismatched element index
8195     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8196 
8197     bind(COMPARE_WIDE_VECTORS);
8198     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8199       movdqu(vec1, Address(str1, result, scale));
8200       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8201     } else {
8202       pmovzxbw(vec1, Address(str1, result, scale1));
8203       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8204     }
8205     // After pcmpestri cnt1(rcx) contains mismatched element index
8206 
8207     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8208     addptr(result, stride);
8209     subptr(cnt2, stride);
8210     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8211 
8212     // compare wide vectors tail
8213     testptr(result, result);
8214     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8215 
8216     movl(cnt2, stride);
8217     movl(result, stride);
8218     negptr(result);
8219     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8220       movdqu(vec1, Address(str1, result, scale));
8221       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8222     } else {
8223       pmovzxbw(vec1, Address(str1, result, scale1));
8224       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8225     }
8226     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8227 
8228     // Mismatched characters in the vectors
8229     bind(VECTOR_NOT_EQUAL);
8230     addptr(cnt1, result);
8231     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8232     subl(result, cnt2);
8233     jmpb(POP_LABEL);
8234 
8235     bind(COMPARE_TAIL); // limit is zero
8236     movl(cnt2, result);
8237     // Fallthru to tail compare
8238   }
8239   // Shift str2 and str1 to the end of the arrays, negate min
8240   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8241     lea(str1, Address(str1, cnt2, scale));
8242     lea(str2, Address(str2, cnt2, scale));
8243   } else {
8244     lea(str1, Address(str1, cnt2, scale1));
8245     lea(str2, Address(str2, cnt2, scale2));
8246   }
8247   decrementl(cnt2);  // first character was compared already
8248   negptr(cnt2);
8249 
8250   // Compare the rest of the elements
8251   bind(WHILE_HEAD_LABEL);
8252   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8253   subl(result, cnt1);
8254   jccb(Assembler::notZero, POP_LABEL);
8255   increment(cnt2);
8256   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8257 
8258   // Strings are equal up to min length.  Return the length difference.
8259   bind(LENGTH_DIFF_LABEL);
8260   pop(result);
8261   if (ae == StrIntrinsicNode::UU) {
8262     // Divide diff by 2 to get number of chars
8263     sarl(result, 1);
8264   }
8265   jmpb(DONE_LABEL);
8266 
8267 #ifdef _LP64
8268   if (VM_Version::supports_avx512vlbw()) {
8269 
8270     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8271 
8272     kmovql(cnt1, k7);
8273     notq(cnt1);
8274     bsfq(cnt2, cnt1);
8275     if (ae != StrIntrinsicNode::LL) {
8276       // Divide diff by 2 to get number of chars
8277       sarl(cnt2, 1);
8278     }
8279     addq(result, cnt2);
8280     if (ae == StrIntrinsicNode::LL) {
8281       load_unsigned_byte(cnt1, Address(str2, result));
8282       load_unsigned_byte(result, Address(str1, result));
8283     } else if (ae == StrIntrinsicNode::UU) {
8284       load_unsigned_short(cnt1, Address(str2, result, scale));
8285       load_unsigned_short(result, Address(str1, result, scale));
8286     } else {
8287       load_unsigned_short(cnt1, Address(str2, result, scale2));
8288       load_unsigned_byte(result, Address(str1, result, scale1));
8289     }
8290     subl(result, cnt1);
8291     jmpb(POP_LABEL);
8292   }//if (VM_Version::supports_avx512vlbw())
8293 #endif // _LP64
8294 
8295   // Discard the stored length difference
8296   bind(POP_LABEL);
8297   pop(cnt1);
8298 
8299   // That's it
8300   bind(DONE_LABEL);
8301   if(ae == StrIntrinsicNode::UL) {
8302     negl(result);
8303   }
8304 
8305 }
8306 
8307 // Search for Non-ASCII character (Negative byte value) in a byte array,
8308 // return true if it has any and false otherwise.
8309 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8310 //   @HotSpotIntrinsicCandidate
8311 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8312 //     for (int i = off; i < off + len; i++) {
8313 //       if (ba[i] < 0) {
8314 //         return true;
8315 //       }
8316 //     }
8317 //     return false;
8318 //   }
8319 void MacroAssembler::has_negatives(Register ary1, Register len,
8320   Register result, Register tmp1,
8321   XMMRegister vec1, XMMRegister vec2) {
8322   // rsi: byte array
8323   // rcx: len
8324   // rax: result
8325   ShortBranchVerifier sbv(this);
8326   assert_different_registers(ary1, len, result, tmp1);
8327   assert_different_registers(vec1, vec2);
8328   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8329 
8330   // len == 0
8331   testl(len, len);
8332   jcc(Assembler::zero, FALSE_LABEL);
8333 
8334   if ((UseAVX > 2) && // AVX512
8335     VM_Version::supports_avx512vlbw() &&
8336     VM_Version::supports_bmi2()) {
8337 
8338     set_vector_masking();  // opening of the stub context for programming mask registers
8339 
8340     Label test_64_loop, test_tail;
8341     Register tmp3_aliased = len;
8342 
8343     movl(tmp1, len);
8344     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8345 
8346     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8347     andl(len, ~(64 - 1));    // vector count (in chars)
8348     jccb(Assembler::zero, test_tail);
8349 
8350     lea(ary1, Address(ary1, len, Address::times_1));
8351     negptr(len);
8352 
8353     bind(test_64_loop);
8354     // Check whether our 64 elements of size byte contain negatives
8355     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8356     kortestql(k2, k2);
8357     jcc(Assembler::notZero, TRUE_LABEL);
8358 
8359     addptr(len, 64);
8360     jccb(Assembler::notZero, test_64_loop);
8361 
8362 
8363     bind(test_tail);
8364     // bail out when there is nothing to be done
8365     testl(tmp1, -1);
8366     jcc(Assembler::zero, FALSE_LABEL);
8367 
8368     // Save k1
8369     kmovql(k3, k1);
8370 
8371     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8372 #ifdef _LP64
8373     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8374     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8375     notq(tmp3_aliased);
8376     kmovql(k1, tmp3_aliased);
8377 #else
8378     Label k_init;
8379     jmp(k_init);
8380 
8381     // We could not read 64-bits from a general purpose register thus we move
8382     // data required to compose 64 1's to the instruction stream
8383     // We emit 64 byte wide series of elements from 0..63 which later on would
8384     // be used as a compare targets with tail count contained in tmp1 register.
8385     // Result would be a k1 register having tmp1 consecutive number or 1
8386     // counting from least significant bit.
8387     address tmp = pc();
8388     emit_int64(0x0706050403020100);
8389     emit_int64(0x0F0E0D0C0B0A0908);
8390     emit_int64(0x1716151413121110);
8391     emit_int64(0x1F1E1D1C1B1A1918);
8392     emit_int64(0x2726252423222120);
8393     emit_int64(0x2F2E2D2C2B2A2928);
8394     emit_int64(0x3736353433323130);
8395     emit_int64(0x3F3E3D3C3B3A3938);
8396 
8397     bind(k_init);
8398     lea(len, InternalAddress(tmp));
8399     // create mask to test for negative byte inside a vector
8400     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8401     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8402 
8403 #endif
8404     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8405     ktestq(k2, k1);
8406     // Restore k1
8407     kmovql(k1, k3);
8408     jcc(Assembler::notZero, TRUE_LABEL);
8409 
8410     jmp(FALSE_LABEL);
8411 
8412     clear_vector_masking();   // closing of the stub context for programming mask registers
8413   }
8414   else {
8415     movl(result, len); // copy
8416 
8417     if (UseAVX == 2 && UseSSE >= 2) {
8418       // With AVX2, use 32-byte vector compare
8419       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8420 
8421       // Compare 32-byte vectors
8422       andl(result, 0x0000001f);  //   tail count (in bytes)
8423       andl(len, 0xffffffe0);   // vector count (in bytes)
8424       jccb(Assembler::zero, COMPARE_TAIL);
8425 
8426       lea(ary1, Address(ary1, len, Address::times_1));
8427       negptr(len);
8428 
8429       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8430       movdl(vec2, tmp1);
8431       vpbroadcastd(vec2, vec2);
8432 
8433       bind(COMPARE_WIDE_VECTORS);
8434       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8435       vptest(vec1, vec2);
8436       jccb(Assembler::notZero, TRUE_LABEL);
8437       addptr(len, 32);
8438       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8439 
8440       testl(result, result);
8441       jccb(Assembler::zero, FALSE_LABEL);
8442 
8443       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8444       vptest(vec1, vec2);
8445       jccb(Assembler::notZero, TRUE_LABEL);
8446       jmpb(FALSE_LABEL);
8447 
8448       bind(COMPARE_TAIL); // len is zero
8449       movl(len, result);
8450       // Fallthru to tail compare
8451     }
8452     else if (UseSSE42Intrinsics) {
8453       // With SSE4.2, use double quad vector compare
8454       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8455 
8456       // Compare 16-byte vectors
8457       andl(result, 0x0000000f);  //   tail count (in bytes)
8458       andl(len, 0xfffffff0);   // vector count (in bytes)
8459       jccb(Assembler::zero, COMPARE_TAIL);
8460 
8461       lea(ary1, Address(ary1, len, Address::times_1));
8462       negptr(len);
8463 
8464       movl(tmp1, 0x80808080);
8465       movdl(vec2, tmp1);
8466       pshufd(vec2, vec2, 0);
8467 
8468       bind(COMPARE_WIDE_VECTORS);
8469       movdqu(vec1, Address(ary1, len, Address::times_1));
8470       ptest(vec1, vec2);
8471       jccb(Assembler::notZero, TRUE_LABEL);
8472       addptr(len, 16);
8473       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8474 
8475       testl(result, result);
8476       jccb(Assembler::zero, FALSE_LABEL);
8477 
8478       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8479       ptest(vec1, vec2);
8480       jccb(Assembler::notZero, TRUE_LABEL);
8481       jmpb(FALSE_LABEL);
8482 
8483       bind(COMPARE_TAIL); // len is zero
8484       movl(len, result);
8485       // Fallthru to tail compare
8486     }
8487   }
8488   // Compare 4-byte vectors
8489   andl(len, 0xfffffffc); // vector count (in bytes)
8490   jccb(Assembler::zero, COMPARE_CHAR);
8491 
8492   lea(ary1, Address(ary1, len, Address::times_1));
8493   negptr(len);
8494 
8495   bind(COMPARE_VECTORS);
8496   movl(tmp1, Address(ary1, len, Address::times_1));
8497   andl(tmp1, 0x80808080);
8498   jccb(Assembler::notZero, TRUE_LABEL);
8499   addptr(len, 4);
8500   jcc(Assembler::notZero, COMPARE_VECTORS);
8501 
8502   // Compare trailing char (final 2 bytes), if any
8503   bind(COMPARE_CHAR);
8504   testl(result, 0x2);   // tail  char
8505   jccb(Assembler::zero, COMPARE_BYTE);
8506   load_unsigned_short(tmp1, Address(ary1, 0));
8507   andl(tmp1, 0x00008080);
8508   jccb(Assembler::notZero, TRUE_LABEL);
8509   subptr(result, 2);
8510   lea(ary1, Address(ary1, 2));
8511 
8512   bind(COMPARE_BYTE);
8513   testl(result, 0x1);   // tail  byte
8514   jccb(Assembler::zero, FALSE_LABEL);
8515   load_unsigned_byte(tmp1, Address(ary1, 0));
8516   andl(tmp1, 0x00000080);
8517   jccb(Assembler::notEqual, TRUE_LABEL);
8518   jmpb(FALSE_LABEL);
8519 
8520   bind(TRUE_LABEL);
8521   movl(result, 1);   // return true
8522   jmpb(DONE);
8523 
8524   bind(FALSE_LABEL);
8525   xorl(result, result); // return false
8526 
8527   // That's it
8528   bind(DONE);
8529   if (UseAVX >= 2 && UseSSE >= 2) {
8530     // clean upper bits of YMM registers
8531     vpxor(vec1, vec1);
8532     vpxor(vec2, vec2);
8533   }
8534 }
8535 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8536 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8537                                    Register limit, Register result, Register chr,
8538                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8539   ShortBranchVerifier sbv(this);
8540   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8541 
8542   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8543   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8544 
8545   if (is_array_equ) {
8546     // Check the input args
8547     cmpptr(ary1, ary2);
8548     jcc(Assembler::equal, TRUE_LABEL);
8549 
8550     // Need additional checks for arrays_equals.
8551     testptr(ary1, ary1);
8552     jcc(Assembler::zero, FALSE_LABEL);
8553     testptr(ary2, ary2);
8554     jcc(Assembler::zero, FALSE_LABEL);
8555 
8556     // Check the lengths
8557     movl(limit, Address(ary1, length_offset));
8558     cmpl(limit, Address(ary2, length_offset));
8559     jcc(Assembler::notEqual, FALSE_LABEL);
8560   }
8561 
8562   // count == 0
8563   testl(limit, limit);
8564   jcc(Assembler::zero, TRUE_LABEL);
8565 
8566   if (is_array_equ) {
8567     // Load array address
8568     lea(ary1, Address(ary1, base_offset));
8569     lea(ary2, Address(ary2, base_offset));
8570   }
8571 
8572   if (is_array_equ && is_char) {
8573     // arrays_equals when used for char[].
8574     shll(limit, 1);      // byte count != 0
8575   }
8576   movl(result, limit); // copy
8577 
8578   if (UseAVX >= 2) {
8579     // With AVX2, use 32-byte vector compare
8580     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8581 
8582     // Compare 32-byte vectors
8583     andl(result, 0x0000001f);  //   tail count (in bytes)
8584     andl(limit, 0xffffffe0);   // vector count (in bytes)
8585     jcc(Assembler::zero, COMPARE_TAIL);
8586 
8587     lea(ary1, Address(ary1, limit, Address::times_1));
8588     lea(ary2, Address(ary2, limit, Address::times_1));
8589     negptr(limit);
8590 
8591     bind(COMPARE_WIDE_VECTORS);
8592 
8593 #ifdef _LP64
8594     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8595       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8596 
8597       cmpl(limit, -64);
8598       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8599 
8600       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8601 
8602       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8603       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8604       kortestql(k7, k7);
8605       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8606       addptr(limit, 64);  // update since we already compared at this addr
8607       cmpl(limit, -64);
8608       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8609 
8610       // At this point we may still need to compare -limit+result bytes.
8611       // We could execute the next two instruction and just continue via non-wide path:
8612       //  cmpl(limit, 0);
8613       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8614       // But since we stopped at the points ary{1,2}+limit which are
8615       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8616       // (|limit| <= 32 and result < 32),
8617       // we may just compare the last 64 bytes.
8618       //
8619       addptr(result, -64);   // it is safe, bc we just came from this area
8620       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8621       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8622       kortestql(k7, k7);
8623       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8624 
8625       jmp(TRUE_LABEL);
8626 
8627       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8628 
8629     }//if (VM_Version::supports_avx512vlbw())
8630 #endif //_LP64
8631 
8632     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8633     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8634     vpxor(vec1, vec2);
8635 
8636     vptest(vec1, vec1);
8637     jcc(Assembler::notZero, FALSE_LABEL);
8638     addptr(limit, 32);
8639     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8640 
8641     testl(result, result);
8642     jcc(Assembler::zero, TRUE_LABEL);
8643 
8644     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8645     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8646     vpxor(vec1, vec2);
8647 
8648     vptest(vec1, vec1);
8649     jccb(Assembler::notZero, FALSE_LABEL);
8650     jmpb(TRUE_LABEL);
8651 
8652     bind(COMPARE_TAIL); // limit is zero
8653     movl(limit, result);
8654     // Fallthru to tail compare
8655   } else if (UseSSE42Intrinsics) {
8656     // With SSE4.2, use double quad vector compare
8657     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8658 
8659     // Compare 16-byte vectors
8660     andl(result, 0x0000000f);  //   tail count (in bytes)
8661     andl(limit, 0xfffffff0);   // vector count (in bytes)
8662     jcc(Assembler::zero, COMPARE_TAIL);
8663 
8664     lea(ary1, Address(ary1, limit, Address::times_1));
8665     lea(ary2, Address(ary2, limit, Address::times_1));
8666     negptr(limit);
8667 
8668     bind(COMPARE_WIDE_VECTORS);
8669     movdqu(vec1, Address(ary1, limit, Address::times_1));
8670     movdqu(vec2, Address(ary2, limit, Address::times_1));
8671     pxor(vec1, vec2);
8672 
8673     ptest(vec1, vec1);
8674     jcc(Assembler::notZero, FALSE_LABEL);
8675     addptr(limit, 16);
8676     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8677 
8678     testl(result, result);
8679     jcc(Assembler::zero, TRUE_LABEL);
8680 
8681     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8682     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8683     pxor(vec1, vec2);
8684 
8685     ptest(vec1, vec1);
8686     jccb(Assembler::notZero, FALSE_LABEL);
8687     jmpb(TRUE_LABEL);
8688 
8689     bind(COMPARE_TAIL); // limit is zero
8690     movl(limit, result);
8691     // Fallthru to tail compare
8692   }
8693 
8694   // Compare 4-byte vectors
8695   andl(limit, 0xfffffffc); // vector count (in bytes)
8696   jccb(Assembler::zero, COMPARE_CHAR);
8697 
8698   lea(ary1, Address(ary1, limit, Address::times_1));
8699   lea(ary2, Address(ary2, limit, Address::times_1));
8700   negptr(limit);
8701 
8702   bind(COMPARE_VECTORS);
8703   movl(chr, Address(ary1, limit, Address::times_1));
8704   cmpl(chr, Address(ary2, limit, Address::times_1));
8705   jccb(Assembler::notEqual, FALSE_LABEL);
8706   addptr(limit, 4);
8707   jcc(Assembler::notZero, COMPARE_VECTORS);
8708 
8709   // Compare trailing char (final 2 bytes), if any
8710   bind(COMPARE_CHAR);
8711   testl(result, 0x2);   // tail  char
8712   jccb(Assembler::zero, COMPARE_BYTE);
8713   load_unsigned_short(chr, Address(ary1, 0));
8714   load_unsigned_short(limit, Address(ary2, 0));
8715   cmpl(chr, limit);
8716   jccb(Assembler::notEqual, FALSE_LABEL);
8717 
8718   if (is_array_equ && is_char) {
8719     bind(COMPARE_BYTE);
8720   } else {
8721     lea(ary1, Address(ary1, 2));
8722     lea(ary2, Address(ary2, 2));
8723 
8724     bind(COMPARE_BYTE);
8725     testl(result, 0x1);   // tail  byte
8726     jccb(Assembler::zero, TRUE_LABEL);
8727     load_unsigned_byte(chr, Address(ary1, 0));
8728     load_unsigned_byte(limit, Address(ary2, 0));
8729     cmpl(chr, limit);
8730     jccb(Assembler::notEqual, FALSE_LABEL);
8731   }
8732   bind(TRUE_LABEL);
8733   movl(result, 1);   // return true
8734   jmpb(DONE);
8735 
8736   bind(FALSE_LABEL);
8737   xorl(result, result); // return false
8738 
8739   // That's it
8740   bind(DONE);
8741   if (UseAVX >= 2) {
8742     // clean upper bits of YMM registers
8743     vpxor(vec1, vec1);
8744     vpxor(vec2, vec2);
8745   }
8746 }
8747 
8748 #endif
8749 
8750 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8751                                    Register to, Register value, Register count,
8752                                    Register rtmp, XMMRegister xtmp) {
8753   ShortBranchVerifier sbv(this);
8754   assert_different_registers(to, value, count, rtmp);
8755   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8756   Label L_fill_2_bytes, L_fill_4_bytes;
8757 
8758   int shift = -1;
8759   switch (t) {
8760     case T_BYTE:
8761       shift = 2;
8762       break;
8763     case T_SHORT:
8764       shift = 1;
8765       break;
8766     case T_INT:
8767       shift = 0;
8768       break;
8769     default: ShouldNotReachHere();
8770   }
8771 
8772   if (t == T_BYTE) {
8773     andl(value, 0xff);
8774     movl(rtmp, value);
8775     shll(rtmp, 8);
8776     orl(value, rtmp);
8777   }
8778   if (t == T_SHORT) {
8779     andl(value, 0xffff);
8780   }
8781   if (t == T_BYTE || t == T_SHORT) {
8782     movl(rtmp, value);
8783     shll(rtmp, 16);
8784     orl(value, rtmp);
8785   }
8786 
8787   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8788   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8789   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8790     // align source address at 4 bytes address boundary
8791     if (t == T_BYTE) {
8792       // One byte misalignment happens only for byte arrays
8793       testptr(to, 1);
8794       jccb(Assembler::zero, L_skip_align1);
8795       movb(Address(to, 0), value);
8796       increment(to);
8797       decrement(count);
8798       BIND(L_skip_align1);
8799     }
8800     // Two bytes misalignment happens only for byte and short (char) arrays
8801     testptr(to, 2);
8802     jccb(Assembler::zero, L_skip_align2);
8803     movw(Address(to, 0), value);
8804     addptr(to, 2);
8805     subl(count, 1<<(shift-1));
8806     BIND(L_skip_align2);
8807   }
8808   if (UseSSE < 2) {
8809     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8810     // Fill 32-byte chunks
8811     subl(count, 8 << shift);
8812     jcc(Assembler::less, L_check_fill_8_bytes);
8813     align(16);
8814 
8815     BIND(L_fill_32_bytes_loop);
8816 
8817     for (int i = 0; i < 32; i += 4) {
8818       movl(Address(to, i), value);
8819     }
8820 
8821     addptr(to, 32);
8822     subl(count, 8 << shift);
8823     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8824     BIND(L_check_fill_8_bytes);
8825     addl(count, 8 << shift);
8826     jccb(Assembler::zero, L_exit);
8827     jmpb(L_fill_8_bytes);
8828 
8829     //
8830     // length is too short, just fill qwords
8831     //
8832     BIND(L_fill_8_bytes_loop);
8833     movl(Address(to, 0), value);
8834     movl(Address(to, 4), value);
8835     addptr(to, 8);
8836     BIND(L_fill_8_bytes);
8837     subl(count, 1 << (shift + 1));
8838     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8839     // fall through to fill 4 bytes
8840   } else {
8841     Label L_fill_32_bytes;
8842     if (!UseUnalignedLoadStores) {
8843       // align to 8 bytes, we know we are 4 byte aligned to start
8844       testptr(to, 4);
8845       jccb(Assembler::zero, L_fill_32_bytes);
8846       movl(Address(to, 0), value);
8847       addptr(to, 4);
8848       subl(count, 1<<shift);
8849     }
8850     BIND(L_fill_32_bytes);
8851     {
8852       assert( UseSSE >= 2, "supported cpu only" );
8853       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8854       if (UseAVX > 2) {
8855         movl(rtmp, 0xffff);
8856         kmovwl(k1, rtmp);
8857       }
8858       movdl(xtmp, value);
8859       if (UseAVX > 2 && UseUnalignedLoadStores) {
8860         // Fill 64-byte chunks
8861         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8862         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8863 
8864         subl(count, 16 << shift);
8865         jcc(Assembler::less, L_check_fill_32_bytes);
8866         align(16);
8867 
8868         BIND(L_fill_64_bytes_loop);
8869         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8870         addptr(to, 64);
8871         subl(count, 16 << shift);
8872         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8873 
8874         BIND(L_check_fill_32_bytes);
8875         addl(count, 8 << shift);
8876         jccb(Assembler::less, L_check_fill_8_bytes);
8877         vmovdqu(Address(to, 0), xtmp);
8878         addptr(to, 32);
8879         subl(count, 8 << shift);
8880 
8881         BIND(L_check_fill_8_bytes);
8882       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8883         // Fill 64-byte chunks
8884         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8885         vpbroadcastd(xtmp, xtmp);
8886 
8887         subl(count, 16 << shift);
8888         jcc(Assembler::less, L_check_fill_32_bytes);
8889         align(16);
8890 
8891         BIND(L_fill_64_bytes_loop);
8892         vmovdqu(Address(to, 0), xtmp);
8893         vmovdqu(Address(to, 32), xtmp);
8894         addptr(to, 64);
8895         subl(count, 16 << shift);
8896         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8897 
8898         BIND(L_check_fill_32_bytes);
8899         addl(count, 8 << shift);
8900         jccb(Assembler::less, L_check_fill_8_bytes);
8901         vmovdqu(Address(to, 0), xtmp);
8902         addptr(to, 32);
8903         subl(count, 8 << shift);
8904 
8905         BIND(L_check_fill_8_bytes);
8906         // clean upper bits of YMM registers
8907         movdl(xtmp, value);
8908         pshufd(xtmp, xtmp, 0);
8909       } else {
8910         // Fill 32-byte chunks
8911         pshufd(xtmp, xtmp, 0);
8912 
8913         subl(count, 8 << shift);
8914         jcc(Assembler::less, L_check_fill_8_bytes);
8915         align(16);
8916 
8917         BIND(L_fill_32_bytes_loop);
8918 
8919         if (UseUnalignedLoadStores) {
8920           movdqu(Address(to, 0), xtmp);
8921           movdqu(Address(to, 16), xtmp);
8922         } else {
8923           movq(Address(to, 0), xtmp);
8924           movq(Address(to, 8), xtmp);
8925           movq(Address(to, 16), xtmp);
8926           movq(Address(to, 24), xtmp);
8927         }
8928 
8929         addptr(to, 32);
8930         subl(count, 8 << shift);
8931         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8932 
8933         BIND(L_check_fill_8_bytes);
8934       }
8935       addl(count, 8 << shift);
8936       jccb(Assembler::zero, L_exit);
8937       jmpb(L_fill_8_bytes);
8938 
8939       //
8940       // length is too short, just fill qwords
8941       //
8942       BIND(L_fill_8_bytes_loop);
8943       movq(Address(to, 0), xtmp);
8944       addptr(to, 8);
8945       BIND(L_fill_8_bytes);
8946       subl(count, 1 << (shift + 1));
8947       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8948     }
8949   }
8950   // fill trailing 4 bytes
8951   BIND(L_fill_4_bytes);
8952   testl(count, 1<<shift);
8953   jccb(Assembler::zero, L_fill_2_bytes);
8954   movl(Address(to, 0), value);
8955   if (t == T_BYTE || t == T_SHORT) {
8956     addptr(to, 4);
8957     BIND(L_fill_2_bytes);
8958     // fill trailing 2 bytes
8959     testl(count, 1<<(shift-1));
8960     jccb(Assembler::zero, L_fill_byte);
8961     movw(Address(to, 0), value);
8962     if (t == T_BYTE) {
8963       addptr(to, 2);
8964       BIND(L_fill_byte);
8965       // fill trailing byte
8966       testl(count, 1);
8967       jccb(Assembler::zero, L_exit);
8968       movb(Address(to, 0), value);
8969     } else {
8970       BIND(L_fill_byte);
8971     }
8972   } else {
8973     BIND(L_fill_2_bytes);
8974   }
8975   BIND(L_exit);
8976 }
8977 
8978 // encode char[] to byte[] in ISO_8859_1
8979    //@HotSpotIntrinsicCandidate
8980    //private static int implEncodeISOArray(byte[] sa, int sp,
8981    //byte[] da, int dp, int len) {
8982    //  int i = 0;
8983    //  for (; i < len; i++) {
8984    //    char c = StringUTF16.getChar(sa, sp++);
8985    //    if (c > '\u00FF')
8986    //      break;
8987    //    da[dp++] = (byte)c;
8988    //  }
8989    //  return i;
8990    //}
8991 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8992   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8993   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8994   Register tmp5, Register result) {
8995 
8996   // rsi: src
8997   // rdi: dst
8998   // rdx: len
8999   // rcx: tmp5
9000   // rax: result
9001   ShortBranchVerifier sbv(this);
9002   assert_different_registers(src, dst, len, tmp5, result);
9003   Label L_done, L_copy_1_char, L_copy_1_char_exit;
9004 
9005   // set result
9006   xorl(result, result);
9007   // check for zero length
9008   testl(len, len);
9009   jcc(Assembler::zero, L_done);
9010 
9011   movl(result, len);
9012 
9013   // Setup pointers
9014   lea(src, Address(src, len, Address::times_2)); // char[]
9015   lea(dst, Address(dst, len, Address::times_1)); // byte[]
9016   negptr(len);
9017 
9018   if (UseSSE42Intrinsics || UseAVX >= 2) {
9019     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
9020     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
9021 
9022     if (UseAVX >= 2) {
9023       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
9024       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9025       movdl(tmp1Reg, tmp5);
9026       vpbroadcastd(tmp1Reg, tmp1Reg);
9027       jmp(L_chars_32_check);
9028 
9029       bind(L_copy_32_chars);
9030       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
9031       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
9032       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9033       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9034       jccb(Assembler::notZero, L_copy_32_chars_exit);
9035       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
9036       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
9037       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
9038 
9039       bind(L_chars_32_check);
9040       addptr(len, 32);
9041       jcc(Assembler::lessEqual, L_copy_32_chars);
9042 
9043       bind(L_copy_32_chars_exit);
9044       subptr(len, 16);
9045       jccb(Assembler::greater, L_copy_16_chars_exit);
9046 
9047     } else if (UseSSE42Intrinsics) {
9048       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
9049       movdl(tmp1Reg, tmp5);
9050       pshufd(tmp1Reg, tmp1Reg, 0);
9051       jmpb(L_chars_16_check);
9052     }
9053 
9054     bind(L_copy_16_chars);
9055     if (UseAVX >= 2) {
9056       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9057       vptest(tmp2Reg, tmp1Reg);
9058       jcc(Assembler::notZero, L_copy_16_chars_exit);
9059       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9060       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9061     } else {
9062       if (UseAVX > 0) {
9063         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9064         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9065         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9066       } else {
9067         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9068         por(tmp2Reg, tmp3Reg);
9069         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9070         por(tmp2Reg, tmp4Reg);
9071       }
9072       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9073       jccb(Assembler::notZero, L_copy_16_chars_exit);
9074       packuswb(tmp3Reg, tmp4Reg);
9075     }
9076     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9077 
9078     bind(L_chars_16_check);
9079     addptr(len, 16);
9080     jcc(Assembler::lessEqual, L_copy_16_chars);
9081 
9082     bind(L_copy_16_chars_exit);
9083     if (UseAVX >= 2) {
9084       // clean upper bits of YMM registers
9085       vpxor(tmp2Reg, tmp2Reg);
9086       vpxor(tmp3Reg, tmp3Reg);
9087       vpxor(tmp4Reg, tmp4Reg);
9088       movdl(tmp1Reg, tmp5);
9089       pshufd(tmp1Reg, tmp1Reg, 0);
9090     }
9091     subptr(len, 8);
9092     jccb(Assembler::greater, L_copy_8_chars_exit);
9093 
9094     bind(L_copy_8_chars);
9095     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9096     ptest(tmp3Reg, tmp1Reg);
9097     jccb(Assembler::notZero, L_copy_8_chars_exit);
9098     packuswb(tmp3Reg, tmp1Reg);
9099     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9100     addptr(len, 8);
9101     jccb(Assembler::lessEqual, L_copy_8_chars);
9102 
9103     bind(L_copy_8_chars_exit);
9104     subptr(len, 8);
9105     jccb(Assembler::zero, L_done);
9106   }
9107 
9108   bind(L_copy_1_char);
9109   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9110   testl(tmp5, 0xff00);      // check if Unicode char
9111   jccb(Assembler::notZero, L_copy_1_char_exit);
9112   movb(Address(dst, len, Address::times_1, 0), tmp5);
9113   addptr(len, 1);
9114   jccb(Assembler::less, L_copy_1_char);
9115 
9116   bind(L_copy_1_char_exit);
9117   addptr(result, len); // len is negative count of not processed elements
9118 
9119   bind(L_done);
9120 }
9121 
9122 #ifdef _LP64
9123 /**
9124  * Helper for multiply_to_len().
9125  */
9126 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9127   addq(dest_lo, src1);
9128   adcq(dest_hi, 0);
9129   addq(dest_lo, src2);
9130   adcq(dest_hi, 0);
9131 }
9132 
9133 /**
9134  * Multiply 64 bit by 64 bit first loop.
9135  */
9136 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9137                                            Register y, Register y_idx, Register z,
9138                                            Register carry, Register product,
9139                                            Register idx, Register kdx) {
9140   //
9141   //  jlong carry, x[], y[], z[];
9142   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9143   //    huge_128 product = y[idx] * x[xstart] + carry;
9144   //    z[kdx] = (jlong)product;
9145   //    carry  = (jlong)(product >>> 64);
9146   //  }
9147   //  z[xstart] = carry;
9148   //
9149 
9150   Label L_first_loop, L_first_loop_exit;
9151   Label L_one_x, L_one_y, L_multiply;
9152 
9153   decrementl(xstart);
9154   jcc(Assembler::negative, L_one_x);
9155 
9156   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9157   rorq(x_xstart, 32); // convert big-endian to little-endian
9158 
9159   bind(L_first_loop);
9160   decrementl(idx);
9161   jcc(Assembler::negative, L_first_loop_exit);
9162   decrementl(idx);
9163   jcc(Assembler::negative, L_one_y);
9164   movq(y_idx, Address(y, idx, Address::times_4,  0));
9165   rorq(y_idx, 32); // convert big-endian to little-endian
9166   bind(L_multiply);
9167   movq(product, x_xstart);
9168   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9169   addq(product, carry);
9170   adcq(rdx, 0);
9171   subl(kdx, 2);
9172   movl(Address(z, kdx, Address::times_4,  4), product);
9173   shrq(product, 32);
9174   movl(Address(z, kdx, Address::times_4,  0), product);
9175   movq(carry, rdx);
9176   jmp(L_first_loop);
9177 
9178   bind(L_one_y);
9179   movl(y_idx, Address(y,  0));
9180   jmp(L_multiply);
9181 
9182   bind(L_one_x);
9183   movl(x_xstart, Address(x,  0));
9184   jmp(L_first_loop);
9185 
9186   bind(L_first_loop_exit);
9187 }
9188 
9189 /**
9190  * Multiply 64 bit by 64 bit and add 128 bit.
9191  */
9192 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9193                                             Register yz_idx, Register idx,
9194                                             Register carry, Register product, int offset) {
9195   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9196   //     z[kdx] = (jlong)product;
9197 
9198   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9199   rorq(yz_idx, 32); // convert big-endian to little-endian
9200   movq(product, x_xstart);
9201   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9202   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9203   rorq(yz_idx, 32); // convert big-endian to little-endian
9204 
9205   add2_with_carry(rdx, product, carry, yz_idx);
9206 
9207   movl(Address(z, idx, Address::times_4,  offset+4), product);
9208   shrq(product, 32);
9209   movl(Address(z, idx, Address::times_4,  offset), product);
9210 
9211 }
9212 
9213 /**
9214  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9215  */
9216 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9217                                              Register yz_idx, Register idx, Register jdx,
9218                                              Register carry, Register product,
9219                                              Register carry2) {
9220   //   jlong carry, x[], y[], z[];
9221   //   int kdx = ystart+1;
9222   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9223   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9224   //     z[kdx+idx+1] = (jlong)product;
9225   //     jlong carry2  = (jlong)(product >>> 64);
9226   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9227   //     z[kdx+idx] = (jlong)product;
9228   //     carry  = (jlong)(product >>> 64);
9229   //   }
9230   //   idx += 2;
9231   //   if (idx > 0) {
9232   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9233   //     z[kdx+idx] = (jlong)product;
9234   //     carry  = (jlong)(product >>> 64);
9235   //   }
9236   //
9237 
9238   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9239 
9240   movl(jdx, idx);
9241   andl(jdx, 0xFFFFFFFC);
9242   shrl(jdx, 2);
9243 
9244   bind(L_third_loop);
9245   subl(jdx, 1);
9246   jcc(Assembler::negative, L_third_loop_exit);
9247   subl(idx, 4);
9248 
9249   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9250   movq(carry2, rdx);
9251 
9252   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9253   movq(carry, rdx);
9254   jmp(L_third_loop);
9255 
9256   bind (L_third_loop_exit);
9257 
9258   andl (idx, 0x3);
9259   jcc(Assembler::zero, L_post_third_loop_done);
9260 
9261   Label L_check_1;
9262   subl(idx, 2);
9263   jcc(Assembler::negative, L_check_1);
9264 
9265   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9266   movq(carry, rdx);
9267 
9268   bind (L_check_1);
9269   addl (idx, 0x2);
9270   andl (idx, 0x1);
9271   subl(idx, 1);
9272   jcc(Assembler::negative, L_post_third_loop_done);
9273 
9274   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9275   movq(product, x_xstart);
9276   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9277   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9278 
9279   add2_with_carry(rdx, product, yz_idx, carry);
9280 
9281   movl(Address(z, idx, Address::times_4,  0), product);
9282   shrq(product, 32);
9283 
9284   shlq(rdx, 32);
9285   orq(product, rdx);
9286   movq(carry, product);
9287 
9288   bind(L_post_third_loop_done);
9289 }
9290 
9291 /**
9292  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9293  *
9294  */
9295 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9296                                                   Register carry, Register carry2,
9297                                                   Register idx, Register jdx,
9298                                                   Register yz_idx1, Register yz_idx2,
9299                                                   Register tmp, Register tmp3, Register tmp4) {
9300   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9301 
9302   //   jlong carry, x[], y[], z[];
9303   //   int kdx = ystart+1;
9304   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9305   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9306   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9307   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9308   //     carry  = (jlong)(tmp4 >>> 64);
9309   //     z[kdx+idx+1] = (jlong)tmp3;
9310   //     z[kdx+idx] = (jlong)tmp4;
9311   //   }
9312   //   idx += 2;
9313   //   if (idx > 0) {
9314   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9315   //     z[kdx+idx] = (jlong)yz_idx1;
9316   //     carry  = (jlong)(yz_idx1 >>> 64);
9317   //   }
9318   //
9319 
9320   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9321 
9322   movl(jdx, idx);
9323   andl(jdx, 0xFFFFFFFC);
9324   shrl(jdx, 2);
9325 
9326   bind(L_third_loop);
9327   subl(jdx, 1);
9328   jcc(Assembler::negative, L_third_loop_exit);
9329   subl(idx, 4);
9330 
9331   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9332   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9333   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9334   rorxq(yz_idx2, yz_idx2, 32);
9335 
9336   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9337   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9338 
9339   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9340   rorxq(yz_idx1, yz_idx1, 32);
9341   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9342   rorxq(yz_idx2, yz_idx2, 32);
9343 
9344   if (VM_Version::supports_adx()) {
9345     adcxq(tmp3, carry);
9346     adoxq(tmp3, yz_idx1);
9347 
9348     adcxq(tmp4, tmp);
9349     adoxq(tmp4, yz_idx2);
9350 
9351     movl(carry, 0); // does not affect flags
9352     adcxq(carry2, carry);
9353     adoxq(carry2, carry);
9354   } else {
9355     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9356     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9357   }
9358   movq(carry, carry2);
9359 
9360   movl(Address(z, idx, Address::times_4, 12), tmp3);
9361   shrq(tmp3, 32);
9362   movl(Address(z, idx, Address::times_4,  8), tmp3);
9363 
9364   movl(Address(z, idx, Address::times_4,  4), tmp4);
9365   shrq(tmp4, 32);
9366   movl(Address(z, idx, Address::times_4,  0), tmp4);
9367 
9368   jmp(L_third_loop);
9369 
9370   bind (L_third_loop_exit);
9371 
9372   andl (idx, 0x3);
9373   jcc(Assembler::zero, L_post_third_loop_done);
9374 
9375   Label L_check_1;
9376   subl(idx, 2);
9377   jcc(Assembler::negative, L_check_1);
9378 
9379   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9380   rorxq(yz_idx1, yz_idx1, 32);
9381   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9382   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9383   rorxq(yz_idx2, yz_idx2, 32);
9384 
9385   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9386 
9387   movl(Address(z, idx, Address::times_4,  4), tmp3);
9388   shrq(tmp3, 32);
9389   movl(Address(z, idx, Address::times_4,  0), tmp3);
9390   movq(carry, tmp4);
9391 
9392   bind (L_check_1);
9393   addl (idx, 0x2);
9394   andl (idx, 0x1);
9395   subl(idx, 1);
9396   jcc(Assembler::negative, L_post_third_loop_done);
9397   movl(tmp4, Address(y, idx, Address::times_4,  0));
9398   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9399   movl(tmp4, Address(z, idx, Address::times_4,  0));
9400 
9401   add2_with_carry(carry2, tmp3, tmp4, carry);
9402 
9403   movl(Address(z, idx, Address::times_4,  0), tmp3);
9404   shrq(tmp3, 32);
9405 
9406   shlq(carry2, 32);
9407   orq(tmp3, carry2);
9408   movq(carry, tmp3);
9409 
9410   bind(L_post_third_loop_done);
9411 }
9412 
9413 /**
9414  * Code for BigInteger::multiplyToLen() instrinsic.
9415  *
9416  * rdi: x
9417  * rax: xlen
9418  * rsi: y
9419  * rcx: ylen
9420  * r8:  z
9421  * r11: zlen
9422  * r12: tmp1
9423  * r13: tmp2
9424  * r14: tmp3
9425  * r15: tmp4
9426  * rbx: tmp5
9427  *
9428  */
9429 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9430                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9431   ShortBranchVerifier sbv(this);
9432   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9433 
9434   push(tmp1);
9435   push(tmp2);
9436   push(tmp3);
9437   push(tmp4);
9438   push(tmp5);
9439 
9440   push(xlen);
9441   push(zlen);
9442 
9443   const Register idx = tmp1;
9444   const Register kdx = tmp2;
9445   const Register xstart = tmp3;
9446 
9447   const Register y_idx = tmp4;
9448   const Register carry = tmp5;
9449   const Register product  = xlen;
9450   const Register x_xstart = zlen;  // reuse register
9451 
9452   // First Loop.
9453   //
9454   //  final static long LONG_MASK = 0xffffffffL;
9455   //  int xstart = xlen - 1;
9456   //  int ystart = ylen - 1;
9457   //  long carry = 0;
9458   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9459   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9460   //    z[kdx] = (int)product;
9461   //    carry = product >>> 32;
9462   //  }
9463   //  z[xstart] = (int)carry;
9464   //
9465 
9466   movl(idx, ylen);      // idx = ylen;
9467   movl(kdx, zlen);      // kdx = xlen+ylen;
9468   xorq(carry, carry);   // carry = 0;
9469 
9470   Label L_done;
9471 
9472   movl(xstart, xlen);
9473   decrementl(xstart);
9474   jcc(Assembler::negative, L_done);
9475 
9476   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9477 
9478   Label L_second_loop;
9479   testl(kdx, kdx);
9480   jcc(Assembler::zero, L_second_loop);
9481 
9482   Label L_carry;
9483   subl(kdx, 1);
9484   jcc(Assembler::zero, L_carry);
9485 
9486   movl(Address(z, kdx, Address::times_4,  0), carry);
9487   shrq(carry, 32);
9488   subl(kdx, 1);
9489 
9490   bind(L_carry);
9491   movl(Address(z, kdx, Address::times_4,  0), carry);
9492 
9493   // Second and third (nested) loops.
9494   //
9495   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9496   //   carry = 0;
9497   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9498   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9499   //                    (z[k] & LONG_MASK) + carry;
9500   //     z[k] = (int)product;
9501   //     carry = product >>> 32;
9502   //   }
9503   //   z[i] = (int)carry;
9504   // }
9505   //
9506   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9507 
9508   const Register jdx = tmp1;
9509 
9510   bind(L_second_loop);
9511   xorl(carry, carry);    // carry = 0;
9512   movl(jdx, ylen);       // j = ystart+1
9513 
9514   subl(xstart, 1);       // i = xstart-1;
9515   jcc(Assembler::negative, L_done);
9516 
9517   push (z);
9518 
9519   Label L_last_x;
9520   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9521   subl(xstart, 1);       // i = xstart-1;
9522   jcc(Assembler::negative, L_last_x);
9523 
9524   if (UseBMI2Instructions) {
9525     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9526     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9527   } else {
9528     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9529     rorq(x_xstart, 32);  // convert big-endian to little-endian
9530   }
9531 
9532   Label L_third_loop_prologue;
9533   bind(L_third_loop_prologue);
9534 
9535   push (x);
9536   push (xstart);
9537   push (ylen);
9538 
9539 
9540   if (UseBMI2Instructions) {
9541     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9542   } else { // !UseBMI2Instructions
9543     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9544   }
9545 
9546   pop(ylen);
9547   pop(xlen);
9548   pop(x);
9549   pop(z);
9550 
9551   movl(tmp3, xlen);
9552   addl(tmp3, 1);
9553   movl(Address(z, tmp3, Address::times_4,  0), carry);
9554   subl(tmp3, 1);
9555   jccb(Assembler::negative, L_done);
9556 
9557   shrq(carry, 32);
9558   movl(Address(z, tmp3, Address::times_4,  0), carry);
9559   jmp(L_second_loop);
9560 
9561   // Next infrequent code is moved outside loops.
9562   bind(L_last_x);
9563   if (UseBMI2Instructions) {
9564     movl(rdx, Address(x,  0));
9565   } else {
9566     movl(x_xstart, Address(x,  0));
9567   }
9568   jmp(L_third_loop_prologue);
9569 
9570   bind(L_done);
9571 
9572   pop(zlen);
9573   pop(xlen);
9574 
9575   pop(tmp5);
9576   pop(tmp4);
9577   pop(tmp3);
9578   pop(tmp2);
9579   pop(tmp1);
9580 }
9581 
9582 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9583   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9584   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9585   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9586   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9587   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9588   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9589   Label SAME_TILL_END, DONE;
9590   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9591 
9592   //scale is in rcx in both Win64 and Unix
9593   ShortBranchVerifier sbv(this);
9594 
9595   shlq(length);
9596   xorq(result, result);
9597 
9598   if ((UseAVX > 2) &&
9599       VM_Version::supports_avx512vlbw()) {
9600     set_vector_masking();  // opening of the stub context for programming mask registers
9601     cmpq(length, 64);
9602     jcc(Assembler::less, VECTOR32_TAIL);
9603     movq(tmp1, length);
9604     andq(tmp1, 0x3F);      // tail count
9605     andq(length, ~(0x3F)); //vector count
9606 
9607     bind(VECTOR64_LOOP);
9608     // AVX512 code to compare 64 byte vectors.
9609     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9610     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9611     kortestql(k7, k7);
9612     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9613     addq(result, 64);
9614     subq(length, 64);
9615     jccb(Assembler::notZero, VECTOR64_LOOP);
9616 
9617     //bind(VECTOR64_TAIL);
9618     testq(tmp1, tmp1);
9619     jcc(Assembler::zero, SAME_TILL_END);
9620 
9621     bind(VECTOR64_TAIL);
9622     // AVX512 code to compare upto 63 byte vectors.
9623     // Save k1
9624     kmovql(k3, k1);
9625     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9626     shlxq(tmp2, tmp2, tmp1);
9627     notq(tmp2);
9628     kmovql(k1, tmp2);
9629 
9630     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9631     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9632 
9633     ktestql(k7, k1);
9634     // Restore k1
9635     kmovql(k1, k3);
9636     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9637 
9638     bind(VECTOR64_NOT_EQUAL);
9639     kmovql(tmp1, k7);
9640     notq(tmp1);
9641     tzcntq(tmp1, tmp1);
9642     addq(result, tmp1);
9643     shrq(result);
9644     jmp(DONE);
9645     bind(VECTOR32_TAIL);
9646     clear_vector_masking();   // closing of the stub context for programming mask registers
9647   }
9648 
9649   cmpq(length, 8);
9650   jcc(Assembler::equal, VECTOR8_LOOP);
9651   jcc(Assembler::less, VECTOR4_TAIL);
9652 
9653   if (UseAVX >= 2) {
9654 
9655     cmpq(length, 16);
9656     jcc(Assembler::equal, VECTOR16_LOOP);
9657     jcc(Assembler::less, VECTOR8_LOOP);
9658 
9659     cmpq(length, 32);
9660     jccb(Assembler::less, VECTOR16_TAIL);
9661 
9662     subq(length, 32);
9663     bind(VECTOR32_LOOP);
9664     vmovdqu(rymm0, Address(obja, result));
9665     vmovdqu(rymm1, Address(objb, result));
9666     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9667     vptest(rymm2, rymm2);
9668     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9669     addq(result, 32);
9670     subq(length, 32);
9671     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9672     addq(length, 32);
9673     jcc(Assembler::equal, SAME_TILL_END);
9674     //falling through if less than 32 bytes left //close the branch here.
9675 
9676     bind(VECTOR16_TAIL);
9677     cmpq(length, 16);
9678     jccb(Assembler::less, VECTOR8_TAIL);
9679     bind(VECTOR16_LOOP);
9680     movdqu(rymm0, Address(obja, result));
9681     movdqu(rymm1, Address(objb, result));
9682     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9683     ptest(rymm2, rymm2);
9684     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9685     addq(result, 16);
9686     subq(length, 16);
9687     jcc(Assembler::equal, SAME_TILL_END);
9688     //falling through if less than 16 bytes left
9689   } else {//regular intrinsics
9690 
9691     cmpq(length, 16);
9692     jccb(Assembler::less, VECTOR8_TAIL);
9693 
9694     subq(length, 16);
9695     bind(VECTOR16_LOOP);
9696     movdqu(rymm0, Address(obja, result));
9697     movdqu(rymm1, Address(objb, result));
9698     pxor(rymm0, rymm1);
9699     ptest(rymm0, rymm0);
9700     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9701     addq(result, 16);
9702     subq(length, 16);
9703     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9704     addq(length, 16);
9705     jcc(Assembler::equal, SAME_TILL_END);
9706     //falling through if less than 16 bytes left
9707   }
9708 
9709   bind(VECTOR8_TAIL);
9710   cmpq(length, 8);
9711   jccb(Assembler::less, VECTOR4_TAIL);
9712   bind(VECTOR8_LOOP);
9713   movq(tmp1, Address(obja, result));
9714   movq(tmp2, Address(objb, result));
9715   xorq(tmp1, tmp2);
9716   testq(tmp1, tmp1);
9717   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9718   addq(result, 8);
9719   subq(length, 8);
9720   jcc(Assembler::equal, SAME_TILL_END);
9721   //falling through if less than 8 bytes left
9722 
9723   bind(VECTOR4_TAIL);
9724   cmpq(length, 4);
9725   jccb(Assembler::less, BYTES_TAIL);
9726   bind(VECTOR4_LOOP);
9727   movl(tmp1, Address(obja, result));
9728   xorl(tmp1, Address(objb, result));
9729   testl(tmp1, tmp1);
9730   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9731   addq(result, 4);
9732   subq(length, 4);
9733   jcc(Assembler::equal, SAME_TILL_END);
9734   //falling through if less than 4 bytes left
9735 
9736   bind(BYTES_TAIL);
9737   bind(BYTES_LOOP);
9738   load_unsigned_byte(tmp1, Address(obja, result));
9739   load_unsigned_byte(tmp2, Address(objb, result));
9740   xorl(tmp1, tmp2);
9741   testl(tmp1, tmp1);
9742   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9743   decq(length);
9744   jccb(Assembler::zero, SAME_TILL_END);
9745   incq(result);
9746   load_unsigned_byte(tmp1, Address(obja, result));
9747   load_unsigned_byte(tmp2, Address(objb, result));
9748   xorl(tmp1, tmp2);
9749   testl(tmp1, tmp1);
9750   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9751   decq(length);
9752   jccb(Assembler::zero, SAME_TILL_END);
9753   incq(result);
9754   load_unsigned_byte(tmp1, Address(obja, result));
9755   load_unsigned_byte(tmp2, Address(objb, result));
9756   xorl(tmp1, tmp2);
9757   testl(tmp1, tmp1);
9758   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9759   jmpb(SAME_TILL_END);
9760 
9761   if (UseAVX >= 2) {
9762     bind(VECTOR32_NOT_EQUAL);
9763     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9764     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9765     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9766     vpmovmskb(tmp1, rymm0);
9767     bsfq(tmp1, tmp1);
9768     addq(result, tmp1);
9769     shrq(result);
9770     jmpb(DONE);
9771   }
9772 
9773   bind(VECTOR16_NOT_EQUAL);
9774   if (UseAVX >= 2) {
9775     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9776     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9777     pxor(rymm0, rymm2);
9778   } else {
9779     pcmpeqb(rymm2, rymm2);
9780     pxor(rymm0, rymm1);
9781     pcmpeqb(rymm0, rymm1);
9782     pxor(rymm0, rymm2);
9783   }
9784   pmovmskb(tmp1, rymm0);
9785   bsfq(tmp1, tmp1);
9786   addq(result, tmp1);
9787   shrq(result);
9788   jmpb(DONE);
9789 
9790   bind(VECTOR8_NOT_EQUAL);
9791   bind(VECTOR4_NOT_EQUAL);
9792   bsfq(tmp1, tmp1);
9793   shrq(tmp1, 3);
9794   addq(result, tmp1);
9795   bind(BYTES_NOT_EQUAL);
9796   shrq(result);
9797   jmpb(DONE);
9798 
9799   bind(SAME_TILL_END);
9800   mov64(result, -1);
9801 
9802   bind(DONE);
9803 }
9804 
9805 //Helper functions for square_to_len()
9806 
9807 /**
9808  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9809  * Preserves x and z and modifies rest of the registers.
9810  */
9811 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9812   // Perform square and right shift by 1
9813   // Handle odd xlen case first, then for even xlen do the following
9814   // jlong carry = 0;
9815   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9816   //     huge_128 product = x[j:j+1] * x[j:j+1];
9817   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9818   //     z[i+2:i+3] = (jlong)(product >>> 1);
9819   //     carry = (jlong)product;
9820   // }
9821 
9822   xorq(tmp5, tmp5);     // carry
9823   xorq(rdxReg, rdxReg);
9824   xorl(tmp1, tmp1);     // index for x
9825   xorl(tmp4, tmp4);     // index for z
9826 
9827   Label L_first_loop, L_first_loop_exit;
9828 
9829   testl(xlen, 1);
9830   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9831 
9832   // Square and right shift by 1 the odd element using 32 bit multiply
9833   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9834   imulq(raxReg, raxReg);
9835   shrq(raxReg, 1);
9836   adcq(tmp5, 0);
9837   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9838   incrementl(tmp1);
9839   addl(tmp4, 2);
9840 
9841   // Square and  right shift by 1 the rest using 64 bit multiply
9842   bind(L_first_loop);
9843   cmpptr(tmp1, xlen);
9844   jccb(Assembler::equal, L_first_loop_exit);
9845 
9846   // Square
9847   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9848   rorq(raxReg, 32);    // convert big-endian to little-endian
9849   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9850 
9851   // Right shift by 1 and save carry
9852   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9853   rcrq(rdxReg, 1);
9854   rcrq(raxReg, 1);
9855   adcq(tmp5, 0);
9856 
9857   // Store result in z
9858   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9859   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9860 
9861   // Update indices for x and z
9862   addl(tmp1, 2);
9863   addl(tmp4, 4);
9864   jmp(L_first_loop);
9865 
9866   bind(L_first_loop_exit);
9867 }
9868 
9869 
9870 /**
9871  * Perform the following multiply add operation using BMI2 instructions
9872  * carry:sum = sum + op1*op2 + carry
9873  * op2 should be in rdx
9874  * op2 is preserved, all other registers are modified
9875  */
9876 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9877   // assert op2 is rdx
9878   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9879   addq(sum, carry);
9880   adcq(tmp2, 0);
9881   addq(sum, op1);
9882   adcq(tmp2, 0);
9883   movq(carry, tmp2);
9884 }
9885 
9886 /**
9887  * Perform the following multiply add operation:
9888  * carry:sum = sum + op1*op2 + carry
9889  * Preserves op1, op2 and modifies rest of registers
9890  */
9891 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9892   // rdx:rax = op1 * op2
9893   movq(raxReg, op2);
9894   mulq(op1);
9895 
9896   //  rdx:rax = sum + carry + rdx:rax
9897   addq(sum, carry);
9898   adcq(rdxReg, 0);
9899   addq(sum, raxReg);
9900   adcq(rdxReg, 0);
9901 
9902   // carry:sum = rdx:sum
9903   movq(carry, rdxReg);
9904 }
9905 
9906 /**
9907  * Add 64 bit long carry into z[] with carry propogation.
9908  * Preserves z and carry register values and modifies rest of registers.
9909  *
9910  */
9911 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9912   Label L_fourth_loop, L_fourth_loop_exit;
9913 
9914   movl(tmp1, 1);
9915   subl(zlen, 2);
9916   addq(Address(z, zlen, Address::times_4, 0), carry);
9917 
9918   bind(L_fourth_loop);
9919   jccb(Assembler::carryClear, L_fourth_loop_exit);
9920   subl(zlen, 2);
9921   jccb(Assembler::negative, L_fourth_loop_exit);
9922   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9923   jmp(L_fourth_loop);
9924   bind(L_fourth_loop_exit);
9925 }
9926 
9927 /**
9928  * Shift z[] left by 1 bit.
9929  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9930  *
9931  */
9932 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9933 
9934   Label L_fifth_loop, L_fifth_loop_exit;
9935 
9936   // Fifth loop
9937   // Perform primitiveLeftShift(z, zlen, 1)
9938 
9939   const Register prev_carry = tmp1;
9940   const Register new_carry = tmp4;
9941   const Register value = tmp2;
9942   const Register zidx = tmp3;
9943 
9944   // int zidx, carry;
9945   // long value;
9946   // carry = 0;
9947   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9948   //    (carry:value)  = (z[i] << 1) | carry ;
9949   //    z[i] = value;
9950   // }
9951 
9952   movl(zidx, zlen);
9953   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9954 
9955   bind(L_fifth_loop);
9956   decl(zidx);  // Use decl to preserve carry flag
9957   decl(zidx);
9958   jccb(Assembler::negative, L_fifth_loop_exit);
9959 
9960   if (UseBMI2Instructions) {
9961      movq(value, Address(z, zidx, Address::times_4, 0));
9962      rclq(value, 1);
9963      rorxq(value, value, 32);
9964      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9965   }
9966   else {
9967     // clear new_carry
9968     xorl(new_carry, new_carry);
9969 
9970     // Shift z[i] by 1, or in previous carry and save new carry
9971     movq(value, Address(z, zidx, Address::times_4, 0));
9972     shlq(value, 1);
9973     adcl(new_carry, 0);
9974 
9975     orq(value, prev_carry);
9976     rorq(value, 0x20);
9977     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9978 
9979     // Set previous carry = new carry
9980     movl(prev_carry, new_carry);
9981   }
9982   jmp(L_fifth_loop);
9983 
9984   bind(L_fifth_loop_exit);
9985 }
9986 
9987 
9988 /**
9989  * Code for BigInteger::squareToLen() intrinsic
9990  *
9991  * rdi: x
9992  * rsi: len
9993  * r8:  z
9994  * rcx: zlen
9995  * r12: tmp1
9996  * r13: tmp2
9997  * r14: tmp3
9998  * r15: tmp4
9999  * rbx: tmp5
10000  *
10001  */
10002 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) {
10003 
10004   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;
10005   push(tmp1);
10006   push(tmp2);
10007   push(tmp3);
10008   push(tmp4);
10009   push(tmp5);
10010 
10011   // First loop
10012   // Store the squares, right shifted one bit (i.e., divided by 2).
10013   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
10014 
10015   // Add in off-diagonal sums.
10016   //
10017   // Second, third (nested) and fourth loops.
10018   // zlen +=2;
10019   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
10020   //    carry = 0;
10021   //    long op2 = x[xidx:xidx+1];
10022   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
10023   //       k -= 2;
10024   //       long op1 = x[j:j+1];
10025   //       long sum = z[k:k+1];
10026   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
10027   //       z[k:k+1] = sum;
10028   //    }
10029   //    add_one_64(z, k, carry, tmp_regs);
10030   // }
10031 
10032   const Register carry = tmp5;
10033   const Register sum = tmp3;
10034   const Register op1 = tmp4;
10035   Register op2 = tmp2;
10036 
10037   push(zlen);
10038   push(len);
10039   addl(zlen,2);
10040   bind(L_second_loop);
10041   xorq(carry, carry);
10042   subl(zlen, 4);
10043   subl(len, 2);
10044   push(zlen);
10045   push(len);
10046   cmpl(len, 0);
10047   jccb(Assembler::lessEqual, L_second_loop_exit);
10048 
10049   // Multiply an array by one 64 bit long.
10050   if (UseBMI2Instructions) {
10051     op2 = rdxReg;
10052     movq(op2, Address(x, len, Address::times_4,  0));
10053     rorxq(op2, op2, 32);
10054   }
10055   else {
10056     movq(op2, Address(x, len, Address::times_4,  0));
10057     rorq(op2, 32);
10058   }
10059 
10060   bind(L_third_loop);
10061   decrementl(len);
10062   jccb(Assembler::negative, L_third_loop_exit);
10063   decrementl(len);
10064   jccb(Assembler::negative, L_last_x);
10065 
10066   movq(op1, Address(x, len, Address::times_4,  0));
10067   rorq(op1, 32);
10068 
10069   bind(L_multiply);
10070   subl(zlen, 2);
10071   movq(sum, Address(z, zlen, Address::times_4,  0));
10072 
10073   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10074   if (UseBMI2Instructions) {
10075     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10076   }
10077   else {
10078     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10079   }
10080 
10081   movq(Address(z, zlen, Address::times_4, 0), sum);
10082 
10083   jmp(L_third_loop);
10084   bind(L_third_loop_exit);
10085 
10086   // Fourth loop
10087   // Add 64 bit long carry into z with carry propogation.
10088   // Uses offsetted zlen.
10089   add_one_64(z, zlen, carry, tmp1);
10090 
10091   pop(len);
10092   pop(zlen);
10093   jmp(L_second_loop);
10094 
10095   // Next infrequent code is moved outside loops.
10096   bind(L_last_x);
10097   movl(op1, Address(x, 0));
10098   jmp(L_multiply);
10099 
10100   bind(L_second_loop_exit);
10101   pop(len);
10102   pop(zlen);
10103   pop(len);
10104   pop(zlen);
10105 
10106   // Fifth loop
10107   // Shift z left 1 bit.
10108   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10109 
10110   // z[zlen-1] |= x[len-1] & 1;
10111   movl(tmp3, Address(x, len, Address::times_4, -4));
10112   andl(tmp3, 1);
10113   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10114 
10115   pop(tmp5);
10116   pop(tmp4);
10117   pop(tmp3);
10118   pop(tmp2);
10119   pop(tmp1);
10120 }
10121 
10122 /**
10123  * Helper function for mul_add()
10124  * Multiply the in[] by int k and add to out[] starting at offset offs using
10125  * 128 bit by 32 bit multiply and return the carry in tmp5.
10126  * Only quad int aligned length of in[] is operated on in this function.
10127  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10128  * This function preserves out, in and k registers.
10129  * len and offset point to the appropriate index in "in" & "out" correspondingly
10130  * tmp5 has the carry.
10131  * other registers are temporary and are modified.
10132  *
10133  */
10134 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10135   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10136   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10137 
10138   Label L_first_loop, L_first_loop_exit;
10139 
10140   movl(tmp1, len);
10141   shrl(tmp1, 2);
10142 
10143   bind(L_first_loop);
10144   subl(tmp1, 1);
10145   jccb(Assembler::negative, L_first_loop_exit);
10146 
10147   subl(len, 4);
10148   subl(offset, 4);
10149 
10150   Register op2 = tmp2;
10151   const Register sum = tmp3;
10152   const Register op1 = tmp4;
10153   const Register carry = tmp5;
10154 
10155   if (UseBMI2Instructions) {
10156     op2 = rdxReg;
10157   }
10158 
10159   movq(op1, Address(in, len, Address::times_4,  8));
10160   rorq(op1, 32);
10161   movq(sum, Address(out, offset, Address::times_4,  8));
10162   rorq(sum, 32);
10163   if (UseBMI2Instructions) {
10164     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10165   }
10166   else {
10167     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10168   }
10169   // Store back in big endian from little endian
10170   rorq(sum, 0x20);
10171   movq(Address(out, offset, Address::times_4,  8), sum);
10172 
10173   movq(op1, Address(in, len, Address::times_4,  0));
10174   rorq(op1, 32);
10175   movq(sum, Address(out, offset, Address::times_4,  0));
10176   rorq(sum, 32);
10177   if (UseBMI2Instructions) {
10178     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10179   }
10180   else {
10181     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10182   }
10183   // Store back in big endian from little endian
10184   rorq(sum, 0x20);
10185   movq(Address(out, offset, Address::times_4,  0), sum);
10186 
10187   jmp(L_first_loop);
10188   bind(L_first_loop_exit);
10189 }
10190 
10191 /**
10192  * Code for BigInteger::mulAdd() intrinsic
10193  *
10194  * rdi: out
10195  * rsi: in
10196  * r11: offs (out.length - offset)
10197  * rcx: len
10198  * r8:  k
10199  * r12: tmp1
10200  * r13: tmp2
10201  * r14: tmp3
10202  * r15: tmp4
10203  * rbx: tmp5
10204  * Multiply the in[] by word k and add to out[], return the carry in rax
10205  */
10206 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10207    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10208    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10209 
10210   Label L_carry, L_last_in, L_done;
10211 
10212 // carry = 0;
10213 // for (int j=len-1; j >= 0; j--) {
10214 //    long product = (in[j] & LONG_MASK) * kLong +
10215 //                   (out[offs] & LONG_MASK) + carry;
10216 //    out[offs--] = (int)product;
10217 //    carry = product >>> 32;
10218 // }
10219 //
10220   push(tmp1);
10221   push(tmp2);
10222   push(tmp3);
10223   push(tmp4);
10224   push(tmp5);
10225 
10226   Register op2 = tmp2;
10227   const Register sum = tmp3;
10228   const Register op1 = tmp4;
10229   const Register carry =  tmp5;
10230 
10231   if (UseBMI2Instructions) {
10232     op2 = rdxReg;
10233     movl(op2, k);
10234   }
10235   else {
10236     movl(op2, k);
10237   }
10238 
10239   xorq(carry, carry);
10240 
10241   //First loop
10242 
10243   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10244   //The carry is in tmp5
10245   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10246 
10247   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10248   decrementl(len);
10249   jccb(Assembler::negative, L_carry);
10250   decrementl(len);
10251   jccb(Assembler::negative, L_last_in);
10252 
10253   movq(op1, Address(in, len, Address::times_4,  0));
10254   rorq(op1, 32);
10255 
10256   subl(offs, 2);
10257   movq(sum, Address(out, offs, Address::times_4,  0));
10258   rorq(sum, 32);
10259 
10260   if (UseBMI2Instructions) {
10261     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10262   }
10263   else {
10264     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10265   }
10266 
10267   // Store back in big endian from little endian
10268   rorq(sum, 0x20);
10269   movq(Address(out, offs, Address::times_4,  0), sum);
10270 
10271   testl(len, len);
10272   jccb(Assembler::zero, L_carry);
10273 
10274   //Multiply the last in[] entry, if any
10275   bind(L_last_in);
10276   movl(op1, Address(in, 0));
10277   movl(sum, Address(out, offs, Address::times_4,  -4));
10278 
10279   movl(raxReg, k);
10280   mull(op1); //tmp4 * eax -> edx:eax
10281   addl(sum, carry);
10282   adcl(rdxReg, 0);
10283   addl(sum, raxReg);
10284   adcl(rdxReg, 0);
10285   movl(carry, rdxReg);
10286 
10287   movl(Address(out, offs, Address::times_4,  -4), sum);
10288 
10289   bind(L_carry);
10290   //return tmp5/carry as carry in rax
10291   movl(rax, carry);
10292 
10293   bind(L_done);
10294   pop(tmp5);
10295   pop(tmp4);
10296   pop(tmp3);
10297   pop(tmp2);
10298   pop(tmp1);
10299 }
10300 #endif
10301 
10302 /**
10303  * Emits code to update CRC-32 with a byte value according to constants in table
10304  *
10305  * @param [in,out]crc   Register containing the crc.
10306  * @param [in]val       Register containing the byte to fold into the CRC.
10307  * @param [in]table     Register containing the table of crc constants.
10308  *
10309  * uint32_t crc;
10310  * val = crc_table[(val ^ crc) & 0xFF];
10311  * crc = val ^ (crc >> 8);
10312  *
10313  */
10314 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10315   xorl(val, crc);
10316   andl(val, 0xFF);
10317   shrl(crc, 8); // unsigned shift
10318   xorl(crc, Address(table, val, Address::times_4, 0));
10319 }
10320 
10321 /**
10322  * Fold 128-bit data chunk
10323  */
10324 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10325   if (UseAVX > 0) {
10326     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10327     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10328     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10329     pxor(xcrc, xtmp);
10330   } else {
10331     movdqa(xtmp, xcrc);
10332     pclmulhdq(xtmp, xK);   // [123:64]
10333     pclmulldq(xcrc, xK);   // [63:0]
10334     pxor(xcrc, xtmp);
10335     movdqu(xtmp, Address(buf, offset));
10336     pxor(xcrc, xtmp);
10337   }
10338 }
10339 
10340 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10341   if (UseAVX > 0) {
10342     vpclmulhdq(xtmp, xK, xcrc);
10343     vpclmulldq(xcrc, xK, xcrc);
10344     pxor(xcrc, xbuf);
10345     pxor(xcrc, xtmp);
10346   } else {
10347     movdqa(xtmp, xcrc);
10348     pclmulhdq(xtmp, xK);
10349     pclmulldq(xcrc, xK);
10350     pxor(xcrc, xbuf);
10351     pxor(xcrc, xtmp);
10352   }
10353 }
10354 
10355 /**
10356  * 8-bit folds to compute 32-bit CRC
10357  *
10358  * uint64_t xcrc;
10359  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10360  */
10361 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10362   movdl(tmp, xcrc);
10363   andl(tmp, 0xFF);
10364   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10365   psrldq(xcrc, 1); // unsigned shift one byte
10366   pxor(xcrc, xtmp);
10367 }
10368 
10369 /**
10370  * uint32_t crc;
10371  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10372  */
10373 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10374   movl(tmp, crc);
10375   andl(tmp, 0xFF);
10376   shrl(crc, 8);
10377   xorl(crc, Address(table, tmp, Address::times_4, 0));
10378 }
10379 
10380 /**
10381  * @param crc   register containing existing CRC (32-bit)
10382  * @param buf   register pointing to input byte buffer (byte*)
10383  * @param len   register containing number of bytes
10384  * @param table register that will contain address of CRC table
10385  * @param tmp   scratch register
10386  */
10387 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10388   assert_different_registers(crc, buf, len, table, tmp, rax);
10389 
10390   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10391   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10392 
10393   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10394   // context for the registers used, where all instructions below are using 128-bit mode
10395   // On EVEX without VL and BW, these instructions will all be AVX.
10396   if (VM_Version::supports_avx512vlbw()) {
10397     movl(tmp, 0xffff);
10398     kmovwl(k1, tmp);
10399   }
10400 
10401   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10402   notl(crc); // ~crc
10403   cmpl(len, 16);
10404   jcc(Assembler::less, L_tail);
10405 
10406   // Align buffer to 16 bytes
10407   movl(tmp, buf);
10408   andl(tmp, 0xF);
10409   jccb(Assembler::zero, L_aligned);
10410   subl(tmp,  16);
10411   addl(len, tmp);
10412 
10413   align(4);
10414   BIND(L_align_loop);
10415   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10416   update_byte_crc32(crc, rax, table);
10417   increment(buf);
10418   incrementl(tmp);
10419   jccb(Assembler::less, L_align_loop);
10420 
10421   BIND(L_aligned);
10422   movl(tmp, len); // save
10423   shrl(len, 4);
10424   jcc(Assembler::zero, L_tail_restore);
10425 
10426   // Fold crc into first bytes of vector
10427   movdqa(xmm1, Address(buf, 0));
10428   movdl(rax, xmm1);
10429   xorl(crc, rax);
10430   if (VM_Version::supports_sse4_1()) {
10431     pinsrd(xmm1, crc, 0);
10432   } else {
10433     pinsrw(xmm1, crc, 0);
10434     shrl(crc, 16);
10435     pinsrw(xmm1, crc, 1);
10436   }
10437   addptr(buf, 16);
10438   subl(len, 4); // len > 0
10439   jcc(Assembler::less, L_fold_tail);
10440 
10441   movdqa(xmm2, Address(buf,  0));
10442   movdqa(xmm3, Address(buf, 16));
10443   movdqa(xmm4, Address(buf, 32));
10444   addptr(buf, 48);
10445   subl(len, 3);
10446   jcc(Assembler::lessEqual, L_fold_512b);
10447 
10448   // Fold total 512 bits of polynomial on each iteration,
10449   // 128 bits per each of 4 parallel streams.
10450   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10451 
10452   align(32);
10453   BIND(L_fold_512b_loop);
10454   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10455   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10456   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10457   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10458   addptr(buf, 64);
10459   subl(len, 4);
10460   jcc(Assembler::greater, L_fold_512b_loop);
10461 
10462   // Fold 512 bits to 128 bits.
10463   BIND(L_fold_512b);
10464   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10465   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10466   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10467   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10468 
10469   // Fold the rest of 128 bits data chunks
10470   BIND(L_fold_tail);
10471   addl(len, 3);
10472   jccb(Assembler::lessEqual, L_fold_128b);
10473   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10474 
10475   BIND(L_fold_tail_loop);
10476   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10477   addptr(buf, 16);
10478   decrementl(len);
10479   jccb(Assembler::greater, L_fold_tail_loop);
10480 
10481   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10482   BIND(L_fold_128b);
10483   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10484   if (UseAVX > 0) {
10485     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10486     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10487     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10488   } else {
10489     movdqa(xmm2, xmm0);
10490     pclmulqdq(xmm2, xmm1, 0x1);
10491     movdqa(xmm3, xmm0);
10492     pand(xmm3, xmm2);
10493     pclmulqdq(xmm0, xmm3, 0x1);
10494   }
10495   psrldq(xmm1, 8);
10496   psrldq(xmm2, 4);
10497   pxor(xmm0, xmm1);
10498   pxor(xmm0, xmm2);
10499 
10500   // 8 8-bit folds to compute 32-bit CRC.
10501   for (int j = 0; j < 4; j++) {
10502     fold_8bit_crc32(xmm0, table, xmm1, rax);
10503   }
10504   movdl(crc, xmm0); // mov 32 bits to general register
10505   for (int j = 0; j < 4; j++) {
10506     fold_8bit_crc32(crc, table, rax);
10507   }
10508 
10509   BIND(L_tail_restore);
10510   movl(len, tmp); // restore
10511   BIND(L_tail);
10512   andl(len, 0xf);
10513   jccb(Assembler::zero, L_exit);
10514 
10515   // Fold the rest of bytes
10516   align(4);
10517   BIND(L_tail_loop);
10518   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10519   update_byte_crc32(crc, rax, table);
10520   increment(buf);
10521   decrementl(len);
10522   jccb(Assembler::greater, L_tail_loop);
10523 
10524   BIND(L_exit);
10525   notl(crc); // ~c
10526 }
10527 
10528 #ifdef _LP64
10529 // S. Gueron / Information Processing Letters 112 (2012) 184
10530 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10531 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10532 // Output: the 64-bit carry-less product of B * CONST
10533 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10534                                      Register tmp1, Register tmp2, Register tmp3) {
10535   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10536   if (n > 0) {
10537     addq(tmp3, n * 256 * 8);
10538   }
10539   //    Q1 = TABLEExt[n][B & 0xFF];
10540   movl(tmp1, in);
10541   andl(tmp1, 0x000000FF);
10542   shll(tmp1, 3);
10543   addq(tmp1, tmp3);
10544   movq(tmp1, Address(tmp1, 0));
10545 
10546   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10547   movl(tmp2, in);
10548   shrl(tmp2, 8);
10549   andl(tmp2, 0x000000FF);
10550   shll(tmp2, 3);
10551   addq(tmp2, tmp3);
10552   movq(tmp2, Address(tmp2, 0));
10553 
10554   shlq(tmp2, 8);
10555   xorq(tmp1, tmp2);
10556 
10557   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10558   movl(tmp2, in);
10559   shrl(tmp2, 16);
10560   andl(tmp2, 0x000000FF);
10561   shll(tmp2, 3);
10562   addq(tmp2, tmp3);
10563   movq(tmp2, Address(tmp2, 0));
10564 
10565   shlq(tmp2, 16);
10566   xorq(tmp1, tmp2);
10567 
10568   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10569   shrl(in, 24);
10570   andl(in, 0x000000FF);
10571   shll(in, 3);
10572   addq(in, tmp3);
10573   movq(in, Address(in, 0));
10574 
10575   shlq(in, 24);
10576   xorq(in, tmp1);
10577   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10578 }
10579 
10580 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10581                                       Register in_out,
10582                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10583                                       XMMRegister w_xtmp2,
10584                                       Register tmp1,
10585                                       Register n_tmp2, Register n_tmp3) {
10586   if (is_pclmulqdq_supported) {
10587     movdl(w_xtmp1, in_out); // modified blindly
10588 
10589     movl(tmp1, const_or_pre_comp_const_index);
10590     movdl(w_xtmp2, tmp1);
10591     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10592 
10593     movdq(in_out, w_xtmp1);
10594   } else {
10595     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10596   }
10597 }
10598 
10599 // Recombination Alternative 2: No bit-reflections
10600 // T1 = (CRC_A * U1) << 1
10601 // T2 = (CRC_B * U2) << 1
10602 // C1 = T1 >> 32
10603 // C2 = T2 >> 32
10604 // T1 = T1 & 0xFFFFFFFF
10605 // T2 = T2 & 0xFFFFFFFF
10606 // T1 = CRC32(0, T1)
10607 // T2 = CRC32(0, T2)
10608 // C1 = C1 ^ T1
10609 // C2 = C2 ^ T2
10610 // CRC = C1 ^ C2 ^ CRC_C
10611 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,
10612                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10613                                      Register tmp1, Register tmp2,
10614                                      Register n_tmp3) {
10615   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10616   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10617   shlq(in_out, 1);
10618   movl(tmp1, in_out);
10619   shrq(in_out, 32);
10620   xorl(tmp2, tmp2);
10621   crc32(tmp2, tmp1, 4);
10622   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10623   shlq(in1, 1);
10624   movl(tmp1, in1);
10625   shrq(in1, 32);
10626   xorl(tmp2, tmp2);
10627   crc32(tmp2, tmp1, 4);
10628   xorl(in1, tmp2);
10629   xorl(in_out, in1);
10630   xorl(in_out, in2);
10631 }
10632 
10633 // Set N to predefined value
10634 // Subtract from a lenght of a buffer
10635 // execute in a loop:
10636 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10637 // for i = 1 to N do
10638 //  CRC_A = CRC32(CRC_A, A[i])
10639 //  CRC_B = CRC32(CRC_B, B[i])
10640 //  CRC_C = CRC32(CRC_C, C[i])
10641 // end for
10642 // Recombine
10643 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,
10644                                        Register in_out1, Register in_out2, Register in_out3,
10645                                        Register tmp1, Register tmp2, Register tmp3,
10646                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10647                                        Register tmp4, Register tmp5,
10648                                        Register n_tmp6) {
10649   Label L_processPartitions;
10650   Label L_processPartition;
10651   Label L_exit;
10652 
10653   bind(L_processPartitions);
10654   cmpl(in_out1, 3 * size);
10655   jcc(Assembler::less, L_exit);
10656     xorl(tmp1, tmp1);
10657     xorl(tmp2, tmp2);
10658     movq(tmp3, in_out2);
10659     addq(tmp3, size);
10660 
10661     bind(L_processPartition);
10662       crc32(in_out3, Address(in_out2, 0), 8);
10663       crc32(tmp1, Address(in_out2, size), 8);
10664       crc32(tmp2, Address(in_out2, size * 2), 8);
10665       addq(in_out2, 8);
10666       cmpq(in_out2, tmp3);
10667       jcc(Assembler::less, L_processPartition);
10668     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10669             w_xtmp1, w_xtmp2, w_xtmp3,
10670             tmp4, tmp5,
10671             n_tmp6);
10672     addq(in_out2, 2 * size);
10673     subl(in_out1, 3 * size);
10674     jmp(L_processPartitions);
10675 
10676   bind(L_exit);
10677 }
10678 #else
10679 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10680                                      Register tmp1, Register tmp2, Register tmp3,
10681                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10682   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10683   if (n > 0) {
10684     addl(tmp3, n * 256 * 8);
10685   }
10686   //    Q1 = TABLEExt[n][B & 0xFF];
10687   movl(tmp1, in_out);
10688   andl(tmp1, 0x000000FF);
10689   shll(tmp1, 3);
10690   addl(tmp1, tmp3);
10691   movq(xtmp1, Address(tmp1, 0));
10692 
10693   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10694   movl(tmp2, in_out);
10695   shrl(tmp2, 8);
10696   andl(tmp2, 0x000000FF);
10697   shll(tmp2, 3);
10698   addl(tmp2, tmp3);
10699   movq(xtmp2, Address(tmp2, 0));
10700 
10701   psllq(xtmp2, 8);
10702   pxor(xtmp1, xtmp2);
10703 
10704   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10705   movl(tmp2, in_out);
10706   shrl(tmp2, 16);
10707   andl(tmp2, 0x000000FF);
10708   shll(tmp2, 3);
10709   addl(tmp2, tmp3);
10710   movq(xtmp2, Address(tmp2, 0));
10711 
10712   psllq(xtmp2, 16);
10713   pxor(xtmp1, xtmp2);
10714 
10715   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10716   shrl(in_out, 24);
10717   andl(in_out, 0x000000FF);
10718   shll(in_out, 3);
10719   addl(in_out, tmp3);
10720   movq(xtmp2, Address(in_out, 0));
10721 
10722   psllq(xtmp2, 24);
10723   pxor(xtmp1, xtmp2); // Result in CXMM
10724   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10725 }
10726 
10727 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10728                                       Register in_out,
10729                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10730                                       XMMRegister w_xtmp2,
10731                                       Register tmp1,
10732                                       Register n_tmp2, Register n_tmp3) {
10733   if (is_pclmulqdq_supported) {
10734     movdl(w_xtmp1, in_out);
10735 
10736     movl(tmp1, const_or_pre_comp_const_index);
10737     movdl(w_xtmp2, tmp1);
10738     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10739     // Keep result in XMM since GPR is 32 bit in length
10740   } else {
10741     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10742   }
10743 }
10744 
10745 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,
10746                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10747                                      Register tmp1, Register tmp2,
10748                                      Register n_tmp3) {
10749   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10750   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10751 
10752   psllq(w_xtmp1, 1);
10753   movdl(tmp1, w_xtmp1);
10754   psrlq(w_xtmp1, 32);
10755   movdl(in_out, w_xtmp1);
10756 
10757   xorl(tmp2, tmp2);
10758   crc32(tmp2, tmp1, 4);
10759   xorl(in_out, tmp2);
10760 
10761   psllq(w_xtmp2, 1);
10762   movdl(tmp1, w_xtmp2);
10763   psrlq(w_xtmp2, 32);
10764   movdl(in1, w_xtmp2);
10765 
10766   xorl(tmp2, tmp2);
10767   crc32(tmp2, tmp1, 4);
10768   xorl(in1, tmp2);
10769   xorl(in_out, in1);
10770   xorl(in_out, in2);
10771 }
10772 
10773 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,
10774                                        Register in_out1, Register in_out2, Register in_out3,
10775                                        Register tmp1, Register tmp2, Register tmp3,
10776                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10777                                        Register tmp4, Register tmp5,
10778                                        Register n_tmp6) {
10779   Label L_processPartitions;
10780   Label L_processPartition;
10781   Label L_exit;
10782 
10783   bind(L_processPartitions);
10784   cmpl(in_out1, 3 * size);
10785   jcc(Assembler::less, L_exit);
10786     xorl(tmp1, tmp1);
10787     xorl(tmp2, tmp2);
10788     movl(tmp3, in_out2);
10789     addl(tmp3, size);
10790 
10791     bind(L_processPartition);
10792       crc32(in_out3, Address(in_out2, 0), 4);
10793       crc32(tmp1, Address(in_out2, size), 4);
10794       crc32(tmp2, Address(in_out2, size*2), 4);
10795       crc32(in_out3, Address(in_out2, 0+4), 4);
10796       crc32(tmp1, Address(in_out2, size+4), 4);
10797       crc32(tmp2, Address(in_out2, size*2+4), 4);
10798       addl(in_out2, 8);
10799       cmpl(in_out2, tmp3);
10800       jcc(Assembler::less, L_processPartition);
10801 
10802         push(tmp3);
10803         push(in_out1);
10804         push(in_out2);
10805         tmp4 = tmp3;
10806         tmp5 = in_out1;
10807         n_tmp6 = in_out2;
10808 
10809       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10810             w_xtmp1, w_xtmp2, w_xtmp3,
10811             tmp4, tmp5,
10812             n_tmp6);
10813 
10814         pop(in_out2);
10815         pop(in_out1);
10816         pop(tmp3);
10817 
10818     addl(in_out2, 2 * size);
10819     subl(in_out1, 3 * size);
10820     jmp(L_processPartitions);
10821 
10822   bind(L_exit);
10823 }
10824 #endif //LP64
10825 
10826 #ifdef _LP64
10827 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10828 // Input: A buffer I of L bytes.
10829 // Output: the CRC32C value of the buffer.
10830 // Notations:
10831 // Write L = 24N + r, with N = floor (L/24).
10832 // r = L mod 24 (0 <= r < 24).
10833 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10834 // N quadwords, and R consists of r bytes.
10835 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10836 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10837 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10838 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10839 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10840                                           Register tmp1, Register tmp2, Register tmp3,
10841                                           Register tmp4, Register tmp5, Register tmp6,
10842                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10843                                           bool is_pclmulqdq_supported) {
10844   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10845   Label L_wordByWord;
10846   Label L_byteByByteProlog;
10847   Label L_byteByByte;
10848   Label L_exit;
10849 
10850   if (is_pclmulqdq_supported ) {
10851     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10852     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10853 
10854     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10855     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10856 
10857     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10858     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10859     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10860   } else {
10861     const_or_pre_comp_const_index[0] = 1;
10862     const_or_pre_comp_const_index[1] = 0;
10863 
10864     const_or_pre_comp_const_index[2] = 3;
10865     const_or_pre_comp_const_index[3] = 2;
10866 
10867     const_or_pre_comp_const_index[4] = 5;
10868     const_or_pre_comp_const_index[5] = 4;
10869    }
10870   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10871                     in2, in1, in_out,
10872                     tmp1, tmp2, tmp3,
10873                     w_xtmp1, w_xtmp2, w_xtmp3,
10874                     tmp4, tmp5,
10875                     tmp6);
10876   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10877                     in2, in1, in_out,
10878                     tmp1, tmp2, tmp3,
10879                     w_xtmp1, w_xtmp2, w_xtmp3,
10880                     tmp4, tmp5,
10881                     tmp6);
10882   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10883                     in2, in1, in_out,
10884                     tmp1, tmp2, tmp3,
10885                     w_xtmp1, w_xtmp2, w_xtmp3,
10886                     tmp4, tmp5,
10887                     tmp6);
10888   movl(tmp1, in2);
10889   andl(tmp1, 0x00000007);
10890   negl(tmp1);
10891   addl(tmp1, in2);
10892   addq(tmp1, in1);
10893 
10894   BIND(L_wordByWord);
10895   cmpq(in1, tmp1);
10896   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10897     crc32(in_out, Address(in1, 0), 4);
10898     addq(in1, 4);
10899     jmp(L_wordByWord);
10900 
10901   BIND(L_byteByByteProlog);
10902   andl(in2, 0x00000007);
10903   movl(tmp2, 1);
10904 
10905   BIND(L_byteByByte);
10906   cmpl(tmp2, in2);
10907   jccb(Assembler::greater, L_exit);
10908     crc32(in_out, Address(in1, 0), 1);
10909     incq(in1);
10910     incl(tmp2);
10911     jmp(L_byteByByte);
10912 
10913   BIND(L_exit);
10914 }
10915 #else
10916 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10917                                           Register tmp1, Register  tmp2, Register tmp3,
10918                                           Register tmp4, Register  tmp5, Register tmp6,
10919                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10920                                           bool is_pclmulqdq_supported) {
10921   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10922   Label L_wordByWord;
10923   Label L_byteByByteProlog;
10924   Label L_byteByByte;
10925   Label L_exit;
10926 
10927   if (is_pclmulqdq_supported) {
10928     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10929     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10930 
10931     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10932     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10933 
10934     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10935     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10936   } else {
10937     const_or_pre_comp_const_index[0] = 1;
10938     const_or_pre_comp_const_index[1] = 0;
10939 
10940     const_or_pre_comp_const_index[2] = 3;
10941     const_or_pre_comp_const_index[3] = 2;
10942 
10943     const_or_pre_comp_const_index[4] = 5;
10944     const_or_pre_comp_const_index[5] = 4;
10945   }
10946   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10947                     in2, in1, in_out,
10948                     tmp1, tmp2, tmp3,
10949                     w_xtmp1, w_xtmp2, w_xtmp3,
10950                     tmp4, tmp5,
10951                     tmp6);
10952   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10953                     in2, in1, in_out,
10954                     tmp1, tmp2, tmp3,
10955                     w_xtmp1, w_xtmp2, w_xtmp3,
10956                     tmp4, tmp5,
10957                     tmp6);
10958   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10959                     in2, in1, in_out,
10960                     tmp1, tmp2, tmp3,
10961                     w_xtmp1, w_xtmp2, w_xtmp3,
10962                     tmp4, tmp5,
10963                     tmp6);
10964   movl(tmp1, in2);
10965   andl(tmp1, 0x00000007);
10966   negl(tmp1);
10967   addl(tmp1, in2);
10968   addl(tmp1, in1);
10969 
10970   BIND(L_wordByWord);
10971   cmpl(in1, tmp1);
10972   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10973     crc32(in_out, Address(in1,0), 4);
10974     addl(in1, 4);
10975     jmp(L_wordByWord);
10976 
10977   BIND(L_byteByByteProlog);
10978   andl(in2, 0x00000007);
10979   movl(tmp2, 1);
10980 
10981   BIND(L_byteByByte);
10982   cmpl(tmp2, in2);
10983   jccb(Assembler::greater, L_exit);
10984     movb(tmp1, Address(in1, 0));
10985     crc32(in_out, tmp1, 1);
10986     incl(in1);
10987     incl(tmp2);
10988     jmp(L_byteByByte);
10989 
10990   BIND(L_exit);
10991 }
10992 #endif // LP64
10993 #undef BIND
10994 #undef BLOCK_COMMENT
10995 
10996 // Compress char[] array to byte[].
10997 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10998 //   @HotSpotIntrinsicCandidate
10999 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
11000 //     for (int i = 0; i < len; i++) {
11001 //       int c = src[srcOff++];
11002 //       if (c >>> 8 != 0) {
11003 //         return 0;
11004 //       }
11005 //       dst[dstOff++] = (byte)c;
11006 //     }
11007 //     return len;
11008 //   }
11009 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
11010   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
11011   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
11012   Register tmp5, Register result) {
11013   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
11014 
11015   // rsi: src
11016   // rdi: dst
11017   // rdx: len
11018   // rcx: tmp5
11019   // rax: result
11020 
11021   // rsi holds start addr of source char[] to be compressed
11022   // rdi holds start addr of destination byte[]
11023   // rdx holds length
11024 
11025   assert(len != result, "");
11026 
11027   // save length for return
11028   push(len);
11029 
11030   if ((UseAVX > 2) && // AVX512
11031     VM_Version::supports_avx512vlbw() &&
11032     VM_Version::supports_bmi2()) {
11033 
11034     set_vector_masking();  // opening of the stub context for programming mask registers
11035 
11036     Label copy_32_loop, copy_loop_tail, copy_just_portion_of_candidates;
11037 
11038     // alignement
11039     Label post_alignement;
11040 
11041     // if length of the string is less than 16, handle it in an old fashioned
11042     // way
11043     testl(len, -32);
11044     jcc(Assembler::zero, below_threshold);
11045 
11046     // First check whether a character is compressable ( <= 0xFF).
11047     // Create mask to test for Unicode chars inside zmm vector
11048     movl(result, 0x00FF);
11049     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
11050 
11051     testl(len, -64);
11052     jcc(Assembler::zero, post_alignement);
11053 
11054     // Save k1
11055     kmovql(k3, k1);
11056 
11057     movl(tmp5, dst);
11058     andl(tmp5, (64 - 1));
11059     negl(tmp5);
11060     andl(tmp5, (64 - 1));
11061 
11062     // bail out when there is nothing to be done
11063     testl(tmp5, 0xFFFFFFFF);
11064     jcc(Assembler::zero, post_alignement);
11065 
11066     // ~(~0 << len), where len is the # of remaining elements to process
11067     movl(result, 0xFFFFFFFF);
11068     shlxl(result, result, tmp5);
11069     notl(result);
11070 
11071     kmovdl(k1, result);
11072 
11073     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11074     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11075     ktestd(k2, k1);
11076     jcc(Assembler::carryClear, copy_just_portion_of_candidates);
11077 
11078     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11079 
11080     addptr(src, tmp5);
11081     addptr(src, tmp5);
11082     addptr(dst, tmp5);
11083     subl(len, tmp5);
11084 
11085     bind(post_alignement);
11086     // end of alignement
11087 
11088     movl(tmp5, len);
11089     andl(tmp5, (32 - 1));   // tail count (in chars)
11090     andl(len, ~(32 - 1));    // vector count (in chars)
11091     jcc(Assembler::zero, copy_loop_tail);
11092 
11093     lea(src, Address(src, len, Address::times_2));
11094     lea(dst, Address(dst, len, Address::times_1));
11095     negptr(len);
11096 
11097     bind(copy_32_loop);
11098     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11099     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11100     kortestdl(k2, k2);
11101     jcc(Assembler::carryClear, copy_just_portion_of_candidates);
11102 
11103     // All elements in current processed chunk are valid candidates for
11104     // compression. Write a truncated byte elements to the memory.
11105     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11106     addptr(len, 32);
11107     jcc(Assembler::notZero, copy_32_loop);
11108 
11109     bind(copy_loop_tail);
11110     // bail out when there is nothing to be done
11111     testl(tmp5, 0xFFFFFFFF);
11112     jcc(Assembler::zero, return_length);
11113 
11114     // Save k1
11115     kmovql(k3, k1);
11116 
11117     movl(len, tmp5);
11118 
11119     // ~(~0 << len), where len is the # of remaining elements to process
11120     movl(result, 0xFFFFFFFF);
11121     shlxl(result, result, len);
11122     notl(result);
11123 
11124     kmovdl(k1, result);
11125 
11126     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11127     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11128     ktestd(k2, k1);
11129     jcc(Assembler::carryClear, copy_just_portion_of_candidates);
11130 
11131     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11132     // Restore k1
11133     kmovql(k1, k3);
11134 
11135     jmp(return_length);
11136 
11137     bind(copy_just_portion_of_candidates);
11138     kmovdl(tmp5, k2);
11139     tzcntl(tmp5, tmp5);
11140 
11141     // ~(~0 << tmp5), where tmp5 is a number of elements in an array from the
11142     // result to the first element larger than 0xFF
11143     movl(result, 0xFFFFFFFF);
11144     shlxl(result, result, tmp5);
11145     notl(result);
11146 
11147     kmovdl(k1, result);
11148 
11149     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11150     // Restore k1
11151     kmovql(k1, k3);
11152 
11153     jmp(return_zero);
11154 
11155     clear_vector_masking();   // closing of the stub context for programming mask registers
11156   }
11157   if (UseSSE42Intrinsics) {
11158     Label copy_32_loop, copy_16, copy_tail;
11159 
11160     bind(below_threshold);
11161 
11162     movl(result, len);
11163 
11164     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11165 
11166     // vectored compression
11167     andl(len, 0xfffffff0);    // vector count (in chars)
11168     andl(result, 0x0000000f);    // tail count (in chars)
11169     testl(len, len);
11170     jccb(Assembler::zero, copy_16);
11171 
11172     // compress 16 chars per iter
11173     movdl(tmp1Reg, tmp5);
11174     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11175     pxor(tmp4Reg, tmp4Reg);
11176 
11177     lea(src, Address(src, len, Address::times_2));
11178     lea(dst, Address(dst, len, Address::times_1));
11179     negptr(len);
11180 
11181     bind(copy_32_loop);
11182     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11183     por(tmp4Reg, tmp2Reg);
11184     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11185     por(tmp4Reg, tmp3Reg);
11186     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11187     jcc(Assembler::notZero, return_zero);
11188     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11189     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11190     addptr(len, 16);
11191     jcc(Assembler::notZero, copy_32_loop);
11192 
11193     // compress next vector of 8 chars (if any)
11194     bind(copy_16);
11195     movl(len, result);
11196     andl(len, 0xfffffff8);    // vector count (in chars)
11197     andl(result, 0x00000007);    // tail count (in chars)
11198     testl(len, len);
11199     jccb(Assembler::zero, copy_tail);
11200 
11201     movdl(tmp1Reg, tmp5);
11202     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11203     pxor(tmp3Reg, tmp3Reg);
11204 
11205     movdqu(tmp2Reg, Address(src, 0));
11206     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11207     jccb(Assembler::notZero, return_zero);
11208     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11209     movq(Address(dst, 0), tmp2Reg);
11210     addptr(src, 16);
11211     addptr(dst, 8);
11212 
11213     bind(copy_tail);
11214     movl(len, result);
11215   }
11216   // compress 1 char per iter
11217   testl(len, len);
11218   jccb(Assembler::zero, return_length);
11219   lea(src, Address(src, len, Address::times_2));
11220   lea(dst, Address(dst, len, Address::times_1));
11221   negptr(len);
11222 
11223   bind(copy_chars_loop);
11224   load_unsigned_short(result, Address(src, len, Address::times_2));
11225   testl(result, 0xff00);      // check if Unicode char
11226   jccb(Assembler::notZero, return_zero);
11227   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11228   increment(len);
11229   jcc(Assembler::notZero, copy_chars_loop);
11230 
11231   // if compression succeeded, return length
11232   bind(return_length);
11233   pop(result);
11234   jmpb(done);
11235 
11236   // if compression failed, return 0
11237   bind(return_zero);
11238   xorl(result, result);
11239   addptr(rsp, wordSize);
11240 
11241   bind(done);
11242 }
11243 
11244 // Inflate byte[] array to char[].
11245 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11246 //   @HotSpotIntrinsicCandidate
11247 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11248 //     for (int i = 0; i < len; i++) {
11249 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11250 //     }
11251 //   }
11252 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11253   XMMRegister tmp1, Register tmp2) {
11254   Label copy_chars_loop, done, below_threshold;
11255   // rsi: src
11256   // rdi: dst
11257   // rdx: len
11258   // rcx: tmp2
11259 
11260   // rsi holds start addr of source byte[] to be inflated
11261   // rdi holds start addr of destination char[]
11262   // rdx holds length
11263   assert_different_registers(src, dst, len, tmp2);
11264 
11265   if ((UseAVX > 2) && // AVX512
11266     VM_Version::supports_avx512vlbw() &&
11267     VM_Version::supports_bmi2()) {
11268 
11269     set_vector_masking();  // opening of the stub context for programming mask registers
11270 
11271     Label copy_32_loop, copy_tail;
11272     Register tmp3_aliased = len;
11273 
11274     // if length of the string is less than 16, handle it in an old fashioned
11275     // way
11276     testl(len, -16);
11277     jcc(Assembler::zero, below_threshold);
11278 
11279     // In order to use only one arithmetic operation for the main loop we use
11280     // this pre-calculation
11281     movl(tmp2, len);
11282     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11283     andl(len, -32);     // vector count
11284     jccb(Assembler::zero, copy_tail);
11285 
11286     lea(src, Address(src, len, Address::times_1));
11287     lea(dst, Address(dst, len, Address::times_2));
11288     negptr(len);
11289 
11290 
11291     // inflate 32 chars per iter
11292     bind(copy_32_loop);
11293     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11294     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11295     addptr(len, 32);
11296     jcc(Assembler::notZero, copy_32_loop);
11297 
11298     bind(copy_tail);
11299     // bail out when there is nothing to be done
11300     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11301     jcc(Assembler::zero, done);
11302 
11303     // Save k1
11304     kmovql(k2, k1);
11305 
11306     // ~(~0 << length), where length is the # of remaining elements to process
11307     movl(tmp3_aliased, -1);
11308     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11309     notl(tmp3_aliased);
11310     kmovdl(k1, tmp3_aliased);
11311     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11312     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11313 
11314     // Restore k1
11315     kmovql(k1, k2);
11316     jmp(done);
11317 
11318     clear_vector_masking();   // closing of the stub context for programming mask registers
11319   }
11320   if (UseSSE42Intrinsics) {
11321     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11322 
11323     movl(tmp2, len);
11324 
11325     if (UseAVX > 1) {
11326       andl(tmp2, (16 - 1));
11327       andl(len, -16);
11328       jccb(Assembler::zero, copy_new_tail);
11329     } else {
11330       andl(tmp2, 0x00000007);   // tail count (in chars)
11331       andl(len, 0xfffffff8);    // vector count (in chars)
11332       jccb(Assembler::zero, copy_tail);
11333     }
11334 
11335     // vectored inflation
11336     lea(src, Address(src, len, Address::times_1));
11337     lea(dst, Address(dst, len, Address::times_2));
11338     negptr(len);
11339 
11340     if (UseAVX > 1) {
11341       bind(copy_16_loop);
11342       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11343       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11344       addptr(len, 16);
11345       jcc(Assembler::notZero, copy_16_loop);
11346 
11347       bind(below_threshold);
11348       bind(copy_new_tail);
11349       if (UseAVX > 2) {
11350         movl(tmp2, len);
11351       }
11352       else {
11353         movl(len, tmp2);
11354       }
11355       andl(tmp2, 0x00000007);
11356       andl(len, 0xFFFFFFF8);
11357       jccb(Assembler::zero, copy_tail);
11358 
11359       pmovzxbw(tmp1, Address(src, 0));
11360       movdqu(Address(dst, 0), tmp1);
11361       addptr(src, 8);
11362       addptr(dst, 2 * 8);
11363 
11364       jmp(copy_tail, true);
11365     }
11366 
11367     // inflate 8 chars per iter
11368     bind(copy_8_loop);
11369     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11370     movdqu(Address(dst, len, Address::times_2), tmp1);
11371     addptr(len, 8);
11372     jcc(Assembler::notZero, copy_8_loop);
11373 
11374     bind(copy_tail);
11375     movl(len, tmp2);
11376 
11377     cmpl(len, 4);
11378     jccb(Assembler::less, copy_bytes);
11379 
11380     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11381     pmovzxbw(tmp1, tmp1);
11382     movq(Address(dst, 0), tmp1);
11383     subptr(len, 4);
11384     addptr(src, 4);
11385     addptr(dst, 8);
11386 
11387     bind(copy_bytes);
11388   }
11389   testl(len, len);
11390   jccb(Assembler::zero, done);
11391   lea(src, Address(src, len, Address::times_1));
11392   lea(dst, Address(dst, len, Address::times_2));
11393   negptr(len);
11394 
11395   // inflate 1 char per iter
11396   bind(copy_chars_loop);
11397   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11398   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11399   increment(len);
11400   jcc(Assembler::notZero, copy_chars_loop);
11401 
11402   bind(done);
11403 }
11404 
11405 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11406   switch (cond) {
11407     // Note some conditions are synonyms for others
11408     case Assembler::zero:         return Assembler::notZero;
11409     case Assembler::notZero:      return Assembler::zero;
11410     case Assembler::less:         return Assembler::greaterEqual;
11411     case Assembler::lessEqual:    return Assembler::greater;
11412     case Assembler::greater:      return Assembler::lessEqual;
11413     case Assembler::greaterEqual: return Assembler::less;
11414     case Assembler::below:        return Assembler::aboveEqual;
11415     case Assembler::belowEqual:   return Assembler::above;
11416     case Assembler::above:        return Assembler::belowEqual;
11417     case Assembler::aboveEqual:   return Assembler::below;
11418     case Assembler::overflow:     return Assembler::noOverflow;
11419     case Assembler::noOverflow:   return Assembler::overflow;
11420     case Assembler::negative:     return Assembler::positive;
11421     case Assembler::positive:     return Assembler::negative;
11422     case Assembler::parity:       return Assembler::noParity;
11423     case Assembler::noParity:     return Assembler::parity;
11424   }
11425   ShouldNotReachHere(); return Assembler::overflow;
11426 }
11427 
11428 SkipIfEqual::SkipIfEqual(
11429     MacroAssembler* masm, const bool* flag_addr, bool value) {
11430   _masm = masm;
11431   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11432   _masm->jcc(Assembler::equal, _label);
11433 }
11434 
11435 SkipIfEqual::~SkipIfEqual() {
11436   _masm->bind(_label);
11437 }
11438 
11439 // 32-bit Windows has its own fast-path implementation
11440 // of get_thread
11441 #if !defined(WIN32) || defined(_LP64)
11442 
11443 // This is simply a call to Thread::current()
11444 void MacroAssembler::get_thread(Register thread) {
11445   if (thread != rax) {
11446     push(rax);
11447   }
11448   LP64_ONLY(push(rdi);)
11449   LP64_ONLY(push(rsi);)
11450   push(rdx);
11451   push(rcx);
11452 #ifdef _LP64
11453   push(r8);
11454   push(r9);
11455   push(r10);
11456   push(r11);
11457 #endif
11458 
11459   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11460 
11461 #ifdef _LP64
11462   pop(r11);
11463   pop(r10);
11464   pop(r9);
11465   pop(r8);
11466 #endif
11467   pop(rcx);
11468   pop(rdx);
11469   LP64_ONLY(pop(rsi);)
11470   LP64_ONLY(pop(rdi);)
11471   if (thread != rax) {
11472     mov(thread, rax);
11473     pop(rax);
11474   }
11475 }
11476 
11477 #endif
11478 
11479 void MacroAssembler::save_vector_registers() {
11480   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11481   if (UseAVX > 2) {
11482     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11483   }
11484 
11485   if (UseSSE == 1)  {
11486     subptr(rsp, sizeof(jdouble)*8);
11487     for (int n = 0; n < 8; n++) {
11488       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11489     }
11490   } else if (UseSSE >= 2)  {
11491     if (UseAVX > 2) {
11492       push(rbx);
11493       movl(rbx, 0xffff);
11494       kmovwl(k1, rbx);
11495       pop(rbx);
11496     }
11497 #ifdef COMPILER2
11498     if (MaxVectorSize > 16) {
11499       if(UseAVX > 2) {
11500         // Save upper half of ZMM registers
11501         subptr(rsp, 32*num_xmm_regs);
11502         for (int n = 0; n < num_xmm_regs; n++) {
11503           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11504         }
11505       }
11506       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11507       // Save upper half of YMM registers
11508       subptr(rsp, 16*num_xmm_regs);
11509       for (int n = 0; n < num_xmm_regs; n++) {
11510         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11511       }
11512     }
11513 #endif
11514     // Save whole 128bit (16 bytes) XMM registers
11515     subptr(rsp, 16*num_xmm_regs);
11516 #ifdef _LP64
11517     if (VM_Version::supports_evex()) {
11518       for (int n = 0; n < num_xmm_regs; n++) {
11519         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11520       }
11521     } else {
11522       for (int n = 0; n < num_xmm_regs; n++) {
11523         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11524       }
11525     }
11526 #else
11527     for (int n = 0; n < num_xmm_regs; n++) {
11528       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11529     }
11530 #endif
11531   }
11532 }
11533 
11534 void MacroAssembler::restore_vector_registers() {
11535   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11536   if (UseAVX > 2) {
11537     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11538   }
11539   if (UseSSE == 1)  {
11540     for (int n = 0; n < 8; n++) {
11541       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11542     }
11543     addptr(rsp, sizeof(jdouble)*8);
11544   } else if (UseSSE >= 2)  {
11545     // Restore whole 128bit (16 bytes) XMM registers
11546 #ifdef _LP64
11547   if (VM_Version::supports_evex()) {
11548     for (int n = 0; n < num_xmm_regs; n++) {
11549       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11550     }
11551   } else {
11552     for (int n = 0; n < num_xmm_regs; n++) {
11553       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11554     }
11555   }
11556 #else
11557   for (int n = 0; n < num_xmm_regs; n++) {
11558     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11559   }
11560 #endif
11561     addptr(rsp, 16*num_xmm_regs);
11562 
11563 #ifdef COMPILER2
11564     if (MaxVectorSize > 16) {
11565       // Restore upper half of YMM registers.
11566       for (int n = 0; n < num_xmm_regs; n++) {
11567         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11568       }
11569       addptr(rsp, 16*num_xmm_regs);
11570       if(UseAVX > 2) {
11571         for (int n = 0; n < num_xmm_regs; n++) {
11572           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11573         }
11574         addptr(rsp, 32*num_xmm_regs);
11575       }
11576     }
11577 #endif
11578   }
11579 }