1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/access.hpp"
  37 #include "oops/klass.inline.hpp"
  38 #include "prims/methodHandles.hpp"
  39 #include "runtime/biasedLocking.hpp"
  40 #include "runtime/interfaceSupport.inline.hpp"
  41 #include "runtime/objectMonitor.hpp"
  42 #include "runtime/os.hpp"
  43 #include "runtime/safepoint.hpp"
  44 #include "runtime/safepointMechanism.hpp"
  45 #include "runtime/sharedRuntime.hpp"
  46 #include "runtime/stubRoutines.hpp"
  47 #include "runtime/thread.hpp"
  48 #include "utilities/macros.hpp"
  49 #include "crc32c.h"
  50 #ifdef COMPILER2
  51 #include "opto/intrinsicnode.hpp"
  52 #endif
  53 
  54 #ifdef PRODUCT
  55 #define BLOCK_COMMENT(str) /* nothing */
  56 #define STOP(error) stop(error)
  57 #else
  58 #define BLOCK_COMMENT(str) block_comment(str)
  59 #define STOP(error) block_comment(error); stop(error)
  60 #endif
  61 
  62 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  63 
  64 #ifdef ASSERT
  65 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  66 #endif
  67 
  68 static Assembler::Condition reverse[] = {
  69     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  70     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  71     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  72     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  73     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  74     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  75     Assembler::above          /* belowEqual    = 0x6 */ ,
  76     Assembler::belowEqual     /* above         = 0x7 */ ,
  77     Assembler::positive       /* negative      = 0x8 */ ,
  78     Assembler::negative       /* positive      = 0x9 */ ,
  79     Assembler::noParity       /* parity        = 0xa */ ,
  80     Assembler::parity         /* noParity      = 0xb */ ,
  81     Assembler::greaterEqual   /* less          = 0xc */ ,
  82     Assembler::less           /* greaterEqual  = 0xd */ ,
  83     Assembler::greater        /* lessEqual     = 0xe */ ,
  84     Assembler::lessEqual      /* greater       = 0xf, */
  85 
  86 };
  87 
  88 
  89 // Implementation of MacroAssembler
  90 
  91 // First all the versions that have distinct versions depending on 32/64 bit
  92 // Unless the difference is trivial (1 line or so).
  93 
  94 #ifndef _LP64
  95 
  96 // 32bit versions
  97 
  98 Address MacroAssembler::as_Address(AddressLiteral adr) {
  99   return Address(adr.target(), adr.rspec());
 100 }
 101 
 102 Address MacroAssembler::as_Address(ArrayAddress adr) {
 103   return Address::make_array(adr);
 104 }
 105 
 106 void MacroAssembler::call_VM_leaf_base(address entry_point,
 107                                        int number_of_arguments) {
 108   call(RuntimeAddress(entry_point));
 109   increment(rsp, number_of_arguments * wordSize);
 110 }
 111 
 112 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 113   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 114 }
 115 
 116 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 117   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 121   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 125   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 126 }
 127 
 128 void MacroAssembler::extend_sign(Register hi, Register lo) {
 129   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 130   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 131     cdql();
 132   } else {
 133     movl(hi, lo);
 134     sarl(hi, 31);
 135   }
 136 }
 137 
 138 void MacroAssembler::jC2(Register tmp, Label& L) {
 139   // set parity bit if FPU flag C2 is set (via rax)
 140   save_rax(tmp);
 141   fwait(); fnstsw_ax();
 142   sahf();
 143   restore_rax(tmp);
 144   // branch
 145   jcc(Assembler::parity, L);
 146 }
 147 
 148 void MacroAssembler::jnC2(Register tmp, Label& L) {
 149   // set parity bit if FPU flag C2 is set (via rax)
 150   save_rax(tmp);
 151   fwait(); fnstsw_ax();
 152   sahf();
 153   restore_rax(tmp);
 154   // branch
 155   jcc(Assembler::noParity, L);
 156 }
 157 
 158 // 32bit can do a case table jump in one instruction but we no longer allow the base
 159 // to be installed in the Address class
 160 void MacroAssembler::jump(ArrayAddress entry) {
 161   jmp(as_Address(entry));
 162 }
 163 
 164 // Note: y_lo will be destroyed
 165 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 166   // Long compare for Java (semantics as described in JVM spec.)
 167   Label high, low, done;
 168 
 169   cmpl(x_hi, y_hi);
 170   jcc(Assembler::less, low);
 171   jcc(Assembler::greater, high);
 172   // x_hi is the return register
 173   xorl(x_hi, x_hi);
 174   cmpl(x_lo, y_lo);
 175   jcc(Assembler::below, low);
 176   jcc(Assembler::equal, done);
 177 
 178   bind(high);
 179   xorl(x_hi, x_hi);
 180   increment(x_hi);
 181   jmp(done);
 182 
 183   bind(low);
 184   xorl(x_hi, x_hi);
 185   decrementl(x_hi);
 186 
 187   bind(done);
 188 }
 189 
 190 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 191     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 192 }
 193 
 194 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 195   // leal(dst, as_Address(adr));
 196   // see note in movl as to why we must use a move
 197   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 198 }
 199 
 200 void MacroAssembler::leave() {
 201   mov(rsp, rbp);
 202   pop(rbp);
 203 }
 204 
 205 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 206   // Multiplication of two Java long values stored on the stack
 207   // as illustrated below. Result is in rdx:rax.
 208   //
 209   // rsp ---> [  ??  ] \               \
 210   //            ....    | y_rsp_offset  |
 211   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 212   //          [ y_hi ]                  | (in bytes)
 213   //            ....                    |
 214   //          [ x_lo ]                 /
 215   //          [ x_hi ]
 216   //            ....
 217   //
 218   // Basic idea: lo(result) = lo(x_lo * y_lo)
 219   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 220   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 221   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 222   Label quick;
 223   // load x_hi, y_hi and check if quick
 224   // multiplication is possible
 225   movl(rbx, x_hi);
 226   movl(rcx, y_hi);
 227   movl(rax, rbx);
 228   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 229   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 230   // do full multiplication
 231   // 1st step
 232   mull(y_lo);                                    // x_hi * y_lo
 233   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 234   // 2nd step
 235   movl(rax, x_lo);
 236   mull(rcx);                                     // x_lo * y_hi
 237   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 238   // 3rd step
 239   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 240   movl(rax, x_lo);
 241   mull(y_lo);                                    // x_lo * y_lo
 242   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 243 }
 244 
 245 void MacroAssembler::lneg(Register hi, Register lo) {
 246   negl(lo);
 247   adcl(hi, 0);
 248   negl(hi);
 249 }
 250 
 251 void MacroAssembler::lshl(Register hi, Register lo) {
 252   // Java shift left long support (semantics as described in JVM spec., p.305)
 253   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 254   // shift value is in rcx !
 255   assert(hi != rcx, "must not use rcx");
 256   assert(lo != rcx, "must not use rcx");
 257   const Register s = rcx;                        // shift count
 258   const int      n = BitsPerWord;
 259   Label L;
 260   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 261   cmpl(s, n);                                    // if (s < n)
 262   jcc(Assembler::less, L);                       // else (s >= n)
 263   movl(hi, lo);                                  // x := x << n
 264   xorl(lo, lo);
 265   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 266   bind(L);                                       // s (mod n) < n
 267   shldl(hi, lo);                                 // x := x << s
 268   shll(lo);
 269 }
 270 
 271 
 272 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 273   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 274   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 275   assert(hi != rcx, "must not use rcx");
 276   assert(lo != rcx, "must not use rcx");
 277   const Register s = rcx;                        // shift count
 278   const int      n = BitsPerWord;
 279   Label L;
 280   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 281   cmpl(s, n);                                    // if (s < n)
 282   jcc(Assembler::less, L);                       // else (s >= n)
 283   movl(lo, hi);                                  // x := x >> n
 284   if (sign_extension) sarl(hi, 31);
 285   else                xorl(hi, hi);
 286   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 287   bind(L);                                       // s (mod n) < n
 288   shrdl(lo, hi);                                 // x := x >> s
 289   if (sign_extension) sarl(hi);
 290   else                shrl(hi);
 291 }
 292 
 293 void MacroAssembler::movoop(Register dst, jobject obj) {
 294   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 295 }
 296 
 297 void MacroAssembler::movoop(Address dst, jobject obj) {
 298   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 302   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 306   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 307 }
 308 
 309 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 310   // scratch register is not used,
 311   // it is defined to match parameters of 64-bit version of this method.
 312   if (src.is_lval()) {
 313     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 314   } else {
 315     movl(dst, as_Address(src));
 316   }
 317 }
 318 
 319 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 320   movl(as_Address(dst), src);
 321 }
 322 
 323 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 324   movl(dst, as_Address(src));
 325 }
 326 
 327 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 328 void MacroAssembler::movptr(Address dst, intptr_t src) {
 329   movl(dst, src);
 330 }
 331 
 332 
 333 void MacroAssembler::pop_callee_saved_registers() {
 334   pop(rcx);
 335   pop(rdx);
 336   pop(rdi);
 337   pop(rsi);
 338 }
 339 
 340 void MacroAssembler::pop_fTOS() {
 341   fld_d(Address(rsp, 0));
 342   addl(rsp, 2 * wordSize);
 343 }
 344 
 345 void MacroAssembler::push_callee_saved_registers() {
 346   push(rsi);
 347   push(rdi);
 348   push(rdx);
 349   push(rcx);
 350 }
 351 
 352 void MacroAssembler::push_fTOS() {
 353   subl(rsp, 2 * wordSize);
 354   fstp_d(Address(rsp, 0));
 355 }
 356 
 357 
 358 void MacroAssembler::pushoop(jobject obj) {
 359   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 360 }
 361 
 362 void MacroAssembler::pushklass(Metadata* obj) {
 363   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 364 }
 365 
 366 void MacroAssembler::pushptr(AddressLiteral src) {
 367   if (src.is_lval()) {
 368     push_literal32((int32_t)src.target(), src.rspec());
 369   } else {
 370     pushl(as_Address(src));
 371   }
 372 }
 373 
 374 void MacroAssembler::set_word_if_not_zero(Register dst) {
 375   xorl(dst, dst);
 376   set_byte_if_not_zero(dst);
 377 }
 378 
 379 static void pass_arg0(MacroAssembler* masm, Register arg) {
 380   masm->push(arg);
 381 }
 382 
 383 static void pass_arg1(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg2(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 static void pass_arg3(MacroAssembler* masm, Register arg) {
 392   masm->push(arg);
 393 }
 394 
 395 #ifndef PRODUCT
 396 extern "C" void findpc(intptr_t x);
 397 #endif
 398 
 399 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 400   // In order to get locks to work, we need to fake a in_VM state
 401   JavaThread* thread = JavaThread::current();
 402   JavaThreadState saved_state = thread->thread_state();
 403   thread->set_thread_state(_thread_in_vm);
 404   if (ShowMessageBoxOnError) {
 405     JavaThread* thread = JavaThread::current();
 406     JavaThreadState saved_state = thread->thread_state();
 407     thread->set_thread_state(_thread_in_vm);
 408     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 409       ttyLocker ttyl;
 410       BytecodeCounter::print();
 411     }
 412     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 413     // This is the value of eip which points to where verify_oop will return.
 414     if (os::message_box(msg, "Execution stopped, print registers?")) {
 415       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 416       BREAKPOINT;
 417     }
 418   } else {
 419     ttyLocker ttyl;
 420     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 421   }
 422   // Don't assert holding the ttyLock
 423     assert(false, "DEBUG MESSAGE: %s", msg);
 424   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 425 }
 426 
 427 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 428   ttyLocker ttyl;
 429   FlagSetting fs(Debugging, true);
 430   tty->print_cr("eip = 0x%08x", eip);
 431 #ifndef PRODUCT
 432   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 433     tty->cr();
 434     findpc(eip);
 435     tty->cr();
 436   }
 437 #endif
 438 #define PRINT_REG(rax) \
 439   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 440   PRINT_REG(rax);
 441   PRINT_REG(rbx);
 442   PRINT_REG(rcx);
 443   PRINT_REG(rdx);
 444   PRINT_REG(rdi);
 445   PRINT_REG(rsi);
 446   PRINT_REG(rbp);
 447   PRINT_REG(rsp);
 448 #undef PRINT_REG
 449   // Print some words near top of staack.
 450   int* dump_sp = (int*) rsp;
 451   for (int col1 = 0; col1 < 8; col1++) {
 452     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 453     os::print_location(tty, *dump_sp++);
 454   }
 455   for (int row = 0; row < 16; row++) {
 456     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 457     for (int col = 0; col < 8; col++) {
 458       tty->print(" 0x%08x", *dump_sp++);
 459     }
 460     tty->cr();
 461   }
 462   // Print some instructions around pc:
 463   Disassembler::decode((address)eip-64, (address)eip);
 464   tty->print_cr("--------");
 465   Disassembler::decode((address)eip, (address)eip+32);
 466 }
 467 
 468 void MacroAssembler::stop(const char* msg) {
 469   ExternalAddress message((address)msg);
 470   // push address of message
 471   pushptr(message.addr());
 472   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 473   pusha();                                            // push registers
 474   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 475   hlt();
 476 }
 477 
 478 void MacroAssembler::warn(const char* msg) {
 479   push_CPU_state();
 480 
 481   ExternalAddress message((address) msg);
 482   // push address of message
 483   pushptr(message.addr());
 484 
 485   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 486   addl(rsp, wordSize);       // discard argument
 487   pop_CPU_state();
 488 }
 489 
 490 void MacroAssembler::print_state() {
 491   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 492   pusha();                                            // push registers
 493 
 494   push_CPU_state();
 495   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 496   pop_CPU_state();
 497 
 498   popa();
 499   addl(rsp, wordSize);
 500 }
 501 
 502 #else // _LP64
 503 
 504 // 64 bit versions
 505 
 506 Address MacroAssembler::as_Address(AddressLiteral adr) {
 507   // amd64 always does this as a pc-rel
 508   // we can be absolute or disp based on the instruction type
 509   // jmp/call are displacements others are absolute
 510   assert(!adr.is_lval(), "must be rval");
 511   assert(reachable(adr), "must be");
 512   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 513 
 514 }
 515 
 516 Address MacroAssembler::as_Address(ArrayAddress adr) {
 517   AddressLiteral base = adr.base();
 518   lea(rscratch1, base);
 519   Address index = adr.index();
 520   assert(index._disp == 0, "must not have disp"); // maybe it can?
 521   Address array(rscratch1, index._index, index._scale, index._disp);
 522   return array;
 523 }
 524 
 525 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 526   Label L, E;
 527 
 528 #ifdef _WIN64
 529   // Windows always allocates space for it's register args
 530   assert(num_args <= 4, "only register arguments supported");
 531   subq(rsp,  frame::arg_reg_save_area_bytes);
 532 #endif
 533 
 534   // Align stack if necessary
 535   testl(rsp, 15);
 536   jcc(Assembler::zero, L);
 537 
 538   subq(rsp, 8);
 539   {
 540     call(RuntimeAddress(entry_point));
 541   }
 542   addq(rsp, 8);
 543   jmp(E);
 544 
 545   bind(L);
 546   {
 547     call(RuntimeAddress(entry_point));
 548   }
 549 
 550   bind(E);
 551 
 552 #ifdef _WIN64
 553   // restore stack pointer
 554   addq(rsp, frame::arg_reg_save_area_bytes);
 555 #endif
 556 
 557 }
 558 
 559 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 560   assert(!src2.is_lval(), "should use cmpptr");
 561 
 562   if (reachable(src2)) {
 563     cmpq(src1, as_Address(src2));
 564   } else {
 565     lea(rscratch1, src2);
 566     Assembler::cmpq(src1, Address(rscratch1, 0));
 567   }
 568 }
 569 
 570 int MacroAssembler::corrected_idivq(Register reg) {
 571   // Full implementation of Java ldiv and lrem; checks for special
 572   // case as described in JVM spec., p.243 & p.271.  The function
 573   // returns the (pc) offset of the idivl instruction - may be needed
 574   // for implicit exceptions.
 575   //
 576   //         normal case                           special case
 577   //
 578   // input : rax: dividend                         min_long
 579   //         reg: divisor   (may not be eax/edx)   -1
 580   //
 581   // output: rax: quotient  (= rax idiv reg)       min_long
 582   //         rdx: remainder (= rax irem reg)       0
 583   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 584   static const int64_t min_long = 0x8000000000000000;
 585   Label normal_case, special_case;
 586 
 587   // check for special case
 588   cmp64(rax, ExternalAddress((address) &min_long));
 589   jcc(Assembler::notEqual, normal_case);
 590   xorl(rdx, rdx); // prepare rdx for possible special case (where
 591                   // remainder = 0)
 592   cmpq(reg, -1);
 593   jcc(Assembler::equal, special_case);
 594 
 595   // handle normal case
 596   bind(normal_case);
 597   cdqq();
 598   int idivq_offset = offset();
 599   idivq(reg);
 600 
 601   // normal and special case exit
 602   bind(special_case);
 603 
 604   return idivq_offset;
 605 }
 606 
 607 void MacroAssembler::decrementq(Register reg, int value) {
 608   if (value == min_jint) { subq(reg, value); return; }
 609   if (value <  0) { incrementq(reg, -value); return; }
 610   if (value == 0) {                        ; return; }
 611   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 612   /* else */      { subq(reg, value)       ; return; }
 613 }
 614 
 615 void MacroAssembler::decrementq(Address dst, int value) {
 616   if (value == min_jint) { subq(dst, value); return; }
 617   if (value <  0) { incrementq(dst, -value); return; }
 618   if (value == 0) {                        ; return; }
 619   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 620   /* else */      { subq(dst, value)       ; return; }
 621 }
 622 
 623 void MacroAssembler::incrementq(AddressLiteral dst) {
 624   if (reachable(dst)) {
 625     incrementq(as_Address(dst));
 626   } else {
 627     lea(rscratch1, dst);
 628     incrementq(Address(rscratch1, 0));
 629   }
 630 }
 631 
 632 void MacroAssembler::incrementq(Register reg, int value) {
 633   if (value == min_jint) { addq(reg, value); return; }
 634   if (value <  0) { decrementq(reg, -value); return; }
 635   if (value == 0) {                        ; return; }
 636   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 637   /* else */      { addq(reg, value)       ; return; }
 638 }
 639 
 640 void MacroAssembler::incrementq(Address dst, int value) {
 641   if (value == min_jint) { addq(dst, value); return; }
 642   if (value <  0) { decrementq(dst, -value); return; }
 643   if (value == 0) {                        ; return; }
 644   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 645   /* else */      { addq(dst, value)       ; return; }
 646 }
 647 
 648 // 32bit can do a case table jump in one instruction but we no longer allow the base
 649 // to be installed in the Address class
 650 void MacroAssembler::jump(ArrayAddress entry) {
 651   lea(rscratch1, entry.base());
 652   Address dispatch = entry.index();
 653   assert(dispatch._base == noreg, "must be");
 654   dispatch._base = rscratch1;
 655   jmp(dispatch);
 656 }
 657 
 658 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 659   ShouldNotReachHere(); // 64bit doesn't use two regs
 660   cmpq(x_lo, y_lo);
 661 }
 662 
 663 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 664     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 665 }
 666 
 667 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 668   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 669   movptr(dst, rscratch1);
 670 }
 671 
 672 void MacroAssembler::leave() {
 673   // %%% is this really better? Why not on 32bit too?
 674   emit_int8((unsigned char)0xC9); // LEAVE
 675 }
 676 
 677 void MacroAssembler::lneg(Register hi, Register lo) {
 678   ShouldNotReachHere(); // 64bit doesn't use two regs
 679   negq(lo);
 680 }
 681 
 682 void MacroAssembler::movoop(Register dst, jobject obj) {
 683   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 684 }
 685 
 686 void MacroAssembler::movoop(Address dst, jobject obj) {
 687   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 688   movq(dst, rscratch1);
 689 }
 690 
 691 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 692   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 693 }
 694 
 695 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 696   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 697   movq(dst, rscratch1);
 698 }
 699 
 700 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 701   if (src.is_lval()) {
 702     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 703   } else {
 704     if (reachable(src)) {
 705       movq(dst, as_Address(src));
 706     } else {
 707       lea(scratch, src);
 708       movq(dst, Address(scratch, 0));
 709     }
 710   }
 711 }
 712 
 713 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 714   movq(as_Address(dst), src);
 715 }
 716 
 717 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 718   movq(dst, as_Address(src));
 719 }
 720 
 721 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 722 void MacroAssembler::movptr(Address dst, intptr_t src) {
 723   mov64(rscratch1, src);
 724   movq(dst, rscratch1);
 725 }
 726 
 727 // These are mostly for initializing NULL
 728 void MacroAssembler::movptr(Address dst, int32_t src) {
 729   movslq(dst, src);
 730 }
 731 
 732 void MacroAssembler::movptr(Register dst, int32_t src) {
 733   mov64(dst, (intptr_t)src);
 734 }
 735 
 736 void MacroAssembler::pushoop(jobject obj) {
 737   movoop(rscratch1, obj);
 738   push(rscratch1);
 739 }
 740 
 741 void MacroAssembler::pushklass(Metadata* obj) {
 742   mov_metadata(rscratch1, obj);
 743   push(rscratch1);
 744 }
 745 
 746 void MacroAssembler::pushptr(AddressLiteral src) {
 747   lea(rscratch1, src);
 748   if (src.is_lval()) {
 749     push(rscratch1);
 750   } else {
 751     pushq(Address(rscratch1, 0));
 752   }
 753 }
 754 
 755 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 756   // we must set sp to zero to clear frame
 757   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 758   // must clear fp, so that compiled frames are not confused; it is
 759   // possible that we need it only for debugging
 760   if (clear_fp) {
 761     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 762   }
 763 
 764   // Always clear the pc because it could have been set by make_walkable()
 765   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 766   vzeroupper();
 767 }
 768 
 769 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 770                                          Register last_java_fp,
 771                                          address  last_java_pc) {
 772   vzeroupper();
 773   // determine last_java_sp register
 774   if (!last_java_sp->is_valid()) {
 775     last_java_sp = rsp;
 776   }
 777 
 778   // last_java_fp is optional
 779   if (last_java_fp->is_valid()) {
 780     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 781            last_java_fp);
 782   }
 783 
 784   // last_java_pc is optional
 785   if (last_java_pc != NULL) {
 786     Address java_pc(r15_thread,
 787                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 788     lea(rscratch1, InternalAddress(last_java_pc));
 789     movptr(java_pc, rscratch1);
 790   }
 791 
 792   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 793 }
 794 
 795 static void pass_arg0(MacroAssembler* masm, Register arg) {
 796   if (c_rarg0 != arg ) {
 797     masm->mov(c_rarg0, arg);
 798   }
 799 }
 800 
 801 static void pass_arg1(MacroAssembler* masm, Register arg) {
 802   if (c_rarg1 != arg ) {
 803     masm->mov(c_rarg1, arg);
 804   }
 805 }
 806 
 807 static void pass_arg2(MacroAssembler* masm, Register arg) {
 808   if (c_rarg2 != arg ) {
 809     masm->mov(c_rarg2, arg);
 810   }
 811 }
 812 
 813 static void pass_arg3(MacroAssembler* masm, Register arg) {
 814   if (c_rarg3 != arg ) {
 815     masm->mov(c_rarg3, arg);
 816   }
 817 }
 818 
 819 void MacroAssembler::stop(const char* msg) {
 820   address rip = pc();
 821   pusha(); // get regs on stack
 822   lea(c_rarg0, ExternalAddress((address) msg));
 823   lea(c_rarg1, InternalAddress(rip));
 824   movq(c_rarg2, rsp); // pass pointer to regs array
 825   andq(rsp, -16); // align stack as required by ABI
 826   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 827   hlt();
 828 }
 829 
 830 void MacroAssembler::warn(const char* msg) {
 831   push(rbp);
 832   movq(rbp, rsp);
 833   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 834   push_CPU_state();   // keeps alignment at 16 bytes
 835   lea(c_rarg0, ExternalAddress((address) msg));
 836   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 837   call(rax);
 838   pop_CPU_state();
 839   mov(rsp, rbp);
 840   pop(rbp);
 841 }
 842 
 843 void MacroAssembler::print_state() {
 844   address rip = pc();
 845   pusha();            // get regs on stack
 846   push(rbp);
 847   movq(rbp, rsp);
 848   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 849   push_CPU_state();   // keeps alignment at 16 bytes
 850 
 851   lea(c_rarg0, InternalAddress(rip));
 852   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 853   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 854 
 855   pop_CPU_state();
 856   mov(rsp, rbp);
 857   pop(rbp);
 858   popa();
 859 }
 860 
 861 #ifndef PRODUCT
 862 extern "C" void findpc(intptr_t x);
 863 #endif
 864 
 865 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 866   // In order to get locks to work, we need to fake a in_VM state
 867   if (ShowMessageBoxOnError) {
 868     JavaThread* thread = JavaThread::current();
 869     JavaThreadState saved_state = thread->thread_state();
 870     thread->set_thread_state(_thread_in_vm);
 871 #ifndef PRODUCT
 872     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 873       ttyLocker ttyl;
 874       BytecodeCounter::print();
 875     }
 876 #endif
 877     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 878     // XXX correct this offset for amd64
 879     // This is the value of eip which points to where verify_oop will return.
 880     if (os::message_box(msg, "Execution stopped, print registers?")) {
 881       print_state64(pc, regs);
 882       BREAKPOINT;
 883       assert(false, "start up GDB");
 884     }
 885     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 886   } else {
 887     ttyLocker ttyl;
 888     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 889                     msg);
 890     assert(false, "DEBUG MESSAGE: %s", msg);
 891   }
 892 }
 893 
 894 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 895   ttyLocker ttyl;
 896   FlagSetting fs(Debugging, true);
 897   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 898 #ifndef PRODUCT
 899   tty->cr();
 900   findpc(pc);
 901   tty->cr();
 902 #endif
 903 #define PRINT_REG(rax, value) \
 904   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 905   PRINT_REG(rax, regs[15]);
 906   PRINT_REG(rbx, regs[12]);
 907   PRINT_REG(rcx, regs[14]);
 908   PRINT_REG(rdx, regs[13]);
 909   PRINT_REG(rdi, regs[8]);
 910   PRINT_REG(rsi, regs[9]);
 911   PRINT_REG(rbp, regs[10]);
 912   PRINT_REG(rsp, regs[11]);
 913   PRINT_REG(r8 , regs[7]);
 914   PRINT_REG(r9 , regs[6]);
 915   PRINT_REG(r10, regs[5]);
 916   PRINT_REG(r11, regs[4]);
 917   PRINT_REG(r12, regs[3]);
 918   PRINT_REG(r13, regs[2]);
 919   PRINT_REG(r14, regs[1]);
 920   PRINT_REG(r15, regs[0]);
 921 #undef PRINT_REG
 922   // Print some words near top of staack.
 923   int64_t* rsp = (int64_t*) regs[11];
 924   int64_t* dump_sp = rsp;
 925   for (int col1 = 0; col1 < 8; col1++) {
 926     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 927     os::print_location(tty, *dump_sp++);
 928   }
 929   for (int row = 0; row < 25; row++) {
 930     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 931     for (int col = 0; col < 4; col++) {
 932       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 933     }
 934     tty->cr();
 935   }
 936   // Print some instructions around pc:
 937   Disassembler::decode((address)pc-64, (address)pc);
 938   tty->print_cr("--------");
 939   Disassembler::decode((address)pc, (address)pc+32);
 940 }
 941 
 942 #endif // _LP64
 943 
 944 // Now versions that are common to 32/64 bit
 945 
 946 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 947   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 948 }
 949 
 950 void MacroAssembler::addptr(Register dst, Register src) {
 951   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 952 }
 953 
 954 void MacroAssembler::addptr(Address dst, Register src) {
 955   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 956 }
 957 
 958 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 959   if (reachable(src)) {
 960     Assembler::addsd(dst, as_Address(src));
 961   } else {
 962     lea(rscratch1, src);
 963     Assembler::addsd(dst, Address(rscratch1, 0));
 964   }
 965 }
 966 
 967 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 968   if (reachable(src)) {
 969     addss(dst, as_Address(src));
 970   } else {
 971     lea(rscratch1, src);
 972     addss(dst, Address(rscratch1, 0));
 973   }
 974 }
 975 
 976 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 977   if (reachable(src)) {
 978     Assembler::addpd(dst, as_Address(src));
 979   } else {
 980     lea(rscratch1, src);
 981     Assembler::addpd(dst, Address(rscratch1, 0));
 982   }
 983 }
 984 
 985 void MacroAssembler::align(int modulus) {
 986   align(modulus, offset());
 987 }
 988 
 989 void MacroAssembler::align(int modulus, int target) {
 990   if (target % modulus != 0) {
 991     nop(modulus - (target % modulus));
 992   }
 993 }
 994 
 995 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 996   // Used in sign-masking with aligned address.
 997   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 998   if (reachable(src)) {
 999     Assembler::andpd(dst, as_Address(src));
1000   } else {
1001     lea(rscratch1, src);
1002     Assembler::andpd(dst, Address(rscratch1, 0));
1003   }
1004 }
1005 
1006 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1007   // Used in sign-masking with aligned address.
1008   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1009   if (reachable(src)) {
1010     Assembler::andps(dst, as_Address(src));
1011   } else {
1012     lea(rscratch1, src);
1013     Assembler::andps(dst, Address(rscratch1, 0));
1014   }
1015 }
1016 
1017 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1018   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1019 }
1020 
1021 void MacroAssembler::atomic_incl(Address counter_addr) {
1022   if (os::is_MP())
1023     lock();
1024   incrementl(counter_addr);
1025 }
1026 
1027 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1028   if (reachable(counter_addr)) {
1029     atomic_incl(as_Address(counter_addr));
1030   } else {
1031     lea(scr, counter_addr);
1032     atomic_incl(Address(scr, 0));
1033   }
1034 }
1035 
1036 #ifdef _LP64
1037 void MacroAssembler::atomic_incq(Address counter_addr) {
1038   if (os::is_MP())
1039     lock();
1040   incrementq(counter_addr);
1041 }
1042 
1043 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1044   if (reachable(counter_addr)) {
1045     atomic_incq(as_Address(counter_addr));
1046   } else {
1047     lea(scr, counter_addr);
1048     atomic_incq(Address(scr, 0));
1049   }
1050 }
1051 #endif
1052 
1053 // Writes to stack successive pages until offset reached to check for
1054 // stack overflow + shadow pages.  This clobbers tmp.
1055 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1056   movptr(tmp, rsp);
1057   // Bang stack for total size given plus shadow page size.
1058   // Bang one page at a time because large size can bang beyond yellow and
1059   // red zones.
1060   Label loop;
1061   bind(loop);
1062   movl(Address(tmp, (-os::vm_page_size())), size );
1063   subptr(tmp, os::vm_page_size());
1064   subl(size, os::vm_page_size());
1065   jcc(Assembler::greater, loop);
1066 
1067   // Bang down shadow pages too.
1068   // At this point, (tmp-0) is the last address touched, so don't
1069   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1070   // was post-decremented.)  Skip this address by starting at i=1, and
1071   // touch a few more pages below.  N.B.  It is important to touch all
1072   // the way down including all pages in the shadow zone.
1073   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1074     // this could be any sized move but this is can be a debugging crumb
1075     // so the bigger the better.
1076     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1077   }
1078 }
1079 
1080 void MacroAssembler::reserved_stack_check() {
1081     // testing if reserved zone needs to be enabled
1082     Label no_reserved_zone_enabling;
1083     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1084     NOT_LP64(get_thread(rsi);)
1085 
1086     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1087     jcc(Assembler::below, no_reserved_zone_enabling);
1088 
1089     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1090     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1091     should_not_reach_here();
1092 
1093     bind(no_reserved_zone_enabling);
1094 }
1095 
1096 int MacroAssembler::biased_locking_enter(Register lock_reg,
1097                                          Register obj_reg,
1098                                          Register swap_reg,
1099                                          Register tmp_reg,
1100                                          bool swap_reg_contains_mark,
1101                                          Label& done,
1102                                          Label* slow_case,
1103                                          BiasedLockingCounters* counters) {
1104   assert(UseBiasedLocking, "why call this otherwise?");
1105   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1106   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1107   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1108   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1109   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1110   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1111 
1112   if (PrintBiasedLockingStatistics && counters == NULL) {
1113     counters = BiasedLocking::counters();
1114   }
1115   // Biased locking
1116   // See whether the lock is currently biased toward our thread and
1117   // whether the epoch is still valid
1118   // Note that the runtime guarantees sufficient alignment of JavaThread
1119   // pointers to allow age to be placed into low bits
1120   // First check to see whether biasing is even enabled for this object
1121   Label cas_label;
1122   int null_check_offset = -1;
1123   if (!swap_reg_contains_mark) {
1124     null_check_offset = offset();
1125     movptr(swap_reg, mark_addr);
1126   }
1127   movptr(tmp_reg, swap_reg);
1128   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1129   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1130   jcc(Assembler::notEqual, cas_label);
1131   // The bias pattern is present in the object's header. Need to check
1132   // whether the bias owner and the epoch are both still current.
1133 #ifndef _LP64
1134   // Note that because there is no current thread register on x86_32 we
1135   // need to store off the mark word we read out of the object to
1136   // avoid reloading it and needing to recheck invariants below. This
1137   // store is unfortunate but it makes the overall code shorter and
1138   // simpler.
1139   movptr(saved_mark_addr, swap_reg);
1140 #endif
1141   if (swap_reg_contains_mark) {
1142     null_check_offset = offset();
1143   }
1144   load_prototype_header(tmp_reg, obj_reg);
1145 #ifdef _LP64
1146   orptr(tmp_reg, r15_thread);
1147   xorptr(tmp_reg, swap_reg);
1148   Register header_reg = tmp_reg;
1149 #else
1150   xorptr(tmp_reg, swap_reg);
1151   get_thread(swap_reg);
1152   xorptr(swap_reg, tmp_reg);
1153   Register header_reg = swap_reg;
1154 #endif
1155   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1156   if (counters != NULL) {
1157     cond_inc32(Assembler::zero,
1158                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1159   }
1160   jcc(Assembler::equal, done);
1161 
1162   Label try_revoke_bias;
1163   Label try_rebias;
1164 
1165   // At this point we know that the header has the bias pattern and
1166   // that we are not the bias owner in the current epoch. We need to
1167   // figure out more details about the state of the header in order to
1168   // know what operations can be legally performed on the object's
1169   // header.
1170 
1171   // If the low three bits in the xor result aren't clear, that means
1172   // the prototype header is no longer biased and we have to revoke
1173   // the bias on this object.
1174   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1175   jccb(Assembler::notZero, try_revoke_bias);
1176 
1177   // Biasing is still enabled for this data type. See whether the
1178   // epoch of the current bias is still valid, meaning that the epoch
1179   // bits of the mark word are equal to the epoch bits of the
1180   // prototype header. (Note that the prototype header's epoch bits
1181   // only change at a safepoint.) If not, attempt to rebias the object
1182   // toward the current thread. Note that we must be absolutely sure
1183   // that the current epoch is invalid in order to do this because
1184   // otherwise the manipulations it performs on the mark word are
1185   // illegal.
1186   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1187   jccb(Assembler::notZero, try_rebias);
1188 
1189   // The epoch of the current bias is still valid but we know nothing
1190   // about the owner; it might be set or it might be clear. Try to
1191   // acquire the bias of the object using an atomic operation. If this
1192   // fails we will go in to the runtime to revoke the object's bias.
1193   // Note that we first construct the presumed unbiased header so we
1194   // don't accidentally blow away another thread's valid bias.
1195   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1196   andptr(swap_reg,
1197          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1198 #ifdef _LP64
1199   movptr(tmp_reg, swap_reg);
1200   orptr(tmp_reg, r15_thread);
1201 #else
1202   get_thread(tmp_reg);
1203   orptr(tmp_reg, swap_reg);
1204 #endif
1205   if (os::is_MP()) {
1206     lock();
1207   }
1208   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1209   // If the biasing toward our thread failed, this means that
1210   // another thread succeeded in biasing it toward itself and we
1211   // need to revoke that bias. The revocation will occur in the
1212   // interpreter runtime in the slow case.
1213   if (counters != NULL) {
1214     cond_inc32(Assembler::zero,
1215                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1216   }
1217   if (slow_case != NULL) {
1218     jcc(Assembler::notZero, *slow_case);
1219   }
1220   jmp(done);
1221 
1222   bind(try_rebias);
1223   // At this point we know the epoch has expired, meaning that the
1224   // current "bias owner", if any, is actually invalid. Under these
1225   // circumstances _only_, we are allowed to use the current header's
1226   // value as the comparison value when doing the cas to acquire the
1227   // bias in the current epoch. In other words, we allow transfer of
1228   // the bias from one thread to another directly in this situation.
1229   //
1230   // FIXME: due to a lack of registers we currently blow away the age
1231   // bits in this situation. Should attempt to preserve them.
1232   load_prototype_header(tmp_reg, obj_reg);
1233 #ifdef _LP64
1234   orptr(tmp_reg, r15_thread);
1235 #else
1236   get_thread(swap_reg);
1237   orptr(tmp_reg, swap_reg);
1238   movptr(swap_reg, saved_mark_addr);
1239 #endif
1240   if (os::is_MP()) {
1241     lock();
1242   }
1243   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1244   // If the biasing toward our thread failed, then another thread
1245   // succeeded in biasing it toward itself and we need to revoke that
1246   // bias. The revocation will occur in the runtime in the slow case.
1247   if (counters != NULL) {
1248     cond_inc32(Assembler::zero,
1249                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1250   }
1251   if (slow_case != NULL) {
1252     jcc(Assembler::notZero, *slow_case);
1253   }
1254   jmp(done);
1255 
1256   bind(try_revoke_bias);
1257   // The prototype mark in the klass doesn't have the bias bit set any
1258   // more, indicating that objects of this data type are not supposed
1259   // to be biased any more. We are going to try to reset the mark of
1260   // this object to the prototype value and fall through to the
1261   // CAS-based locking scheme. Note that if our CAS fails, it means
1262   // that another thread raced us for the privilege of revoking the
1263   // bias of this particular object, so it's okay to continue in the
1264   // normal locking code.
1265   //
1266   // FIXME: due to a lack of registers we currently blow away the age
1267   // bits in this situation. Should attempt to preserve them.
1268   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1269   load_prototype_header(tmp_reg, obj_reg);
1270   if (os::is_MP()) {
1271     lock();
1272   }
1273   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1274   // Fall through to the normal CAS-based lock, because no matter what
1275   // the result of the above CAS, some thread must have succeeded in
1276   // removing the bias bit from the object's header.
1277   if (counters != NULL) {
1278     cond_inc32(Assembler::zero,
1279                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1280   }
1281 
1282   bind(cas_label);
1283 
1284   return null_check_offset;
1285 }
1286 
1287 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1288   assert(UseBiasedLocking, "why call this otherwise?");
1289 
1290   // Check for biased locking unlock case, which is a no-op
1291   // Note: we do not have to check the thread ID for two reasons.
1292   // First, the interpreter checks for IllegalMonitorStateException at
1293   // a higher level. Second, if the bias was revoked while we held the
1294   // lock, the object could not be rebiased toward another thread, so
1295   // the bias bit would be clear.
1296   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1297   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1298   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1299   jcc(Assembler::equal, done);
1300 }
1301 
1302 #ifdef COMPILER2
1303 
1304 #if INCLUDE_RTM_OPT
1305 
1306 // Update rtm_counters based on abort status
1307 // input: abort_status
1308 //        rtm_counters (RTMLockingCounters*)
1309 // flags are killed
1310 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1311 
1312   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1313   if (PrintPreciseRTMLockingStatistics) {
1314     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1315       Label check_abort;
1316       testl(abort_status, (1<<i));
1317       jccb(Assembler::equal, check_abort);
1318       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1319       bind(check_abort);
1320     }
1321   }
1322 }
1323 
1324 // Branch if (random & (count-1) != 0), count is 2^n
1325 // tmp, scr and flags are killed
1326 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1327   assert(tmp == rax, "");
1328   assert(scr == rdx, "");
1329   rdtsc(); // modifies EDX:EAX
1330   andptr(tmp, count-1);
1331   jccb(Assembler::notZero, brLabel);
1332 }
1333 
1334 // Perform abort ratio calculation, set no_rtm bit if high ratio
1335 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1336 // tmpReg, rtm_counters_Reg and flags are killed
1337 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1338                                                  Register rtm_counters_Reg,
1339                                                  RTMLockingCounters* rtm_counters,
1340                                                  Metadata* method_data) {
1341   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1342 
1343   if (RTMLockingCalculationDelay > 0) {
1344     // Delay calculation
1345     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1346     testptr(tmpReg, tmpReg);
1347     jccb(Assembler::equal, L_done);
1348   }
1349   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1350   //   Aborted transactions = abort_count * 100
1351   //   All transactions = total_count *  RTMTotalCountIncrRate
1352   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1353 
1354   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1355   cmpptr(tmpReg, RTMAbortThreshold);
1356   jccb(Assembler::below, L_check_always_rtm2);
1357   imulptr(tmpReg, tmpReg, 100);
1358 
1359   Register scrReg = rtm_counters_Reg;
1360   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1361   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1362   imulptr(scrReg, scrReg, RTMAbortRatio);
1363   cmpptr(tmpReg, scrReg);
1364   jccb(Assembler::below, L_check_always_rtm1);
1365   if (method_data != NULL) {
1366     // set rtm_state to "no rtm" in MDO
1367     mov_metadata(tmpReg, method_data);
1368     if (os::is_MP()) {
1369       lock();
1370     }
1371     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1372   }
1373   jmpb(L_done);
1374   bind(L_check_always_rtm1);
1375   // Reload RTMLockingCounters* address
1376   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1377   bind(L_check_always_rtm2);
1378   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1379   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1380   jccb(Assembler::below, L_done);
1381   if (method_data != NULL) {
1382     // set rtm_state to "always rtm" in MDO
1383     mov_metadata(tmpReg, method_data);
1384     if (os::is_MP()) {
1385       lock();
1386     }
1387     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1388   }
1389   bind(L_done);
1390 }
1391 
1392 // Update counters and perform abort ratio calculation
1393 // input:  abort_status_Reg
1394 // rtm_counters_Reg, flags are killed
1395 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1396                                    Register rtm_counters_Reg,
1397                                    RTMLockingCounters* rtm_counters,
1398                                    Metadata* method_data,
1399                                    bool profile_rtm) {
1400 
1401   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1402   // update rtm counters based on rax value at abort
1403   // reads abort_status_Reg, updates flags
1404   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1405   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1406   if (profile_rtm) {
1407     // Save abort status because abort_status_Reg is used by following code.
1408     if (RTMRetryCount > 0) {
1409       push(abort_status_Reg);
1410     }
1411     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1412     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1413     // restore abort status
1414     if (RTMRetryCount > 0) {
1415       pop(abort_status_Reg);
1416     }
1417   }
1418 }
1419 
1420 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1421 // inputs: retry_count_Reg
1422 //       : abort_status_Reg
1423 // output: retry_count_Reg decremented by 1
1424 // flags are killed
1425 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1426   Label doneRetry;
1427   assert(abort_status_Reg == rax, "");
1428   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1429   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1430   // if reason is in 0x6 and retry count != 0 then retry
1431   andptr(abort_status_Reg, 0x6);
1432   jccb(Assembler::zero, doneRetry);
1433   testl(retry_count_Reg, retry_count_Reg);
1434   jccb(Assembler::zero, doneRetry);
1435   pause();
1436   decrementl(retry_count_Reg);
1437   jmp(retryLabel);
1438   bind(doneRetry);
1439 }
1440 
1441 // Spin and retry if lock is busy,
1442 // inputs: box_Reg (monitor address)
1443 //       : retry_count_Reg
1444 // output: retry_count_Reg decremented by 1
1445 //       : clear z flag if retry count exceeded
1446 // tmp_Reg, scr_Reg, flags are killed
1447 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1448                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1449   Label SpinLoop, SpinExit, doneRetry;
1450   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1451 
1452   testl(retry_count_Reg, retry_count_Reg);
1453   jccb(Assembler::zero, doneRetry);
1454   decrementl(retry_count_Reg);
1455   movptr(scr_Reg, RTMSpinLoopCount);
1456 
1457   bind(SpinLoop);
1458   pause();
1459   decrementl(scr_Reg);
1460   jccb(Assembler::lessEqual, SpinExit);
1461   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1462   testptr(tmp_Reg, tmp_Reg);
1463   jccb(Assembler::notZero, SpinLoop);
1464 
1465   bind(SpinExit);
1466   jmp(retryLabel);
1467   bind(doneRetry);
1468   incrementl(retry_count_Reg); // clear z flag
1469 }
1470 
1471 // Use RTM for normal stack locks
1472 // Input: objReg (object to lock)
1473 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1474                                        Register retry_on_abort_count_Reg,
1475                                        RTMLockingCounters* stack_rtm_counters,
1476                                        Metadata* method_data, bool profile_rtm,
1477                                        Label& DONE_LABEL, Label& IsInflated) {
1478   assert(UseRTMForStackLocks, "why call this otherwise?");
1479   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1480   assert(tmpReg == rax, "");
1481   assert(scrReg == rdx, "");
1482   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1483 
1484   if (RTMRetryCount > 0) {
1485     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1486     bind(L_rtm_retry);
1487   }
1488   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1489   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1490   jcc(Assembler::notZero, IsInflated);
1491 
1492   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1493     Label L_noincrement;
1494     if (RTMTotalCountIncrRate > 1) {
1495       // tmpReg, scrReg and flags are killed
1496       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1497     }
1498     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1499     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1500     bind(L_noincrement);
1501   }
1502   xbegin(L_on_abort);
1503   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1504   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1505   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1506   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1507 
1508   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1509   if (UseRTMXendForLockBusy) {
1510     xend();
1511     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1512     jmp(L_decrement_retry);
1513   }
1514   else {
1515     xabort(0);
1516   }
1517   bind(L_on_abort);
1518   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1519     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1520   }
1521   bind(L_decrement_retry);
1522   if (RTMRetryCount > 0) {
1523     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1524     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1525   }
1526 }
1527 
1528 // Use RTM for inflating locks
1529 // inputs: objReg (object to lock)
1530 //         boxReg (on-stack box address (displaced header location) - KILLED)
1531 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1532 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1533                                           Register scrReg, Register retry_on_busy_count_Reg,
1534                                           Register retry_on_abort_count_Reg,
1535                                           RTMLockingCounters* rtm_counters,
1536                                           Metadata* method_data, bool profile_rtm,
1537                                           Label& DONE_LABEL) {
1538   assert(UseRTMLocking, "why call this otherwise?");
1539   assert(tmpReg == rax, "");
1540   assert(scrReg == rdx, "");
1541   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1542   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1543 
1544   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1545   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1546   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1547 
1548   if (RTMRetryCount > 0) {
1549     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1550     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1551     bind(L_rtm_retry);
1552   }
1553   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1554     Label L_noincrement;
1555     if (RTMTotalCountIncrRate > 1) {
1556       // tmpReg, scrReg and flags are killed
1557       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1558     }
1559     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1560     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1561     bind(L_noincrement);
1562   }
1563   xbegin(L_on_abort);
1564   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1565   movptr(tmpReg, Address(tmpReg, owner_offset));
1566   testptr(tmpReg, tmpReg);
1567   jcc(Assembler::zero, DONE_LABEL);
1568   if (UseRTMXendForLockBusy) {
1569     xend();
1570     jmp(L_decrement_retry);
1571   }
1572   else {
1573     xabort(0);
1574   }
1575   bind(L_on_abort);
1576   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1577   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1578     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1579   }
1580   if (RTMRetryCount > 0) {
1581     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1582     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1583   }
1584 
1585   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1586   testptr(tmpReg, tmpReg) ;
1587   jccb(Assembler::notZero, L_decrement_retry) ;
1588 
1589   // Appears unlocked - try to swing _owner from null to non-null.
1590   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1591 #ifdef _LP64
1592   Register threadReg = r15_thread;
1593 #else
1594   get_thread(scrReg);
1595   Register threadReg = scrReg;
1596 #endif
1597   if (os::is_MP()) {
1598     lock();
1599   }
1600   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1601 
1602   if (RTMRetryCount > 0) {
1603     // success done else retry
1604     jccb(Assembler::equal, DONE_LABEL) ;
1605     bind(L_decrement_retry);
1606     // Spin and retry if lock is busy.
1607     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1608   }
1609   else {
1610     bind(L_decrement_retry);
1611   }
1612 }
1613 
1614 #endif //  INCLUDE_RTM_OPT
1615 
1616 // Fast_Lock and Fast_Unlock used by C2
1617 
1618 // Because the transitions from emitted code to the runtime
1619 // monitorenter/exit helper stubs are so slow it's critical that
1620 // we inline both the stack-locking fast-path and the inflated fast path.
1621 //
1622 // See also: cmpFastLock and cmpFastUnlock.
1623 //
1624 // What follows is a specialized inline transliteration of the code
1625 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1626 // another option would be to emit TrySlowEnter and TrySlowExit methods
1627 // at startup-time.  These methods would accept arguments as
1628 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1629 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1630 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1631 // In practice, however, the # of lock sites is bounded and is usually small.
1632 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1633 // if the processor uses simple bimodal branch predictors keyed by EIP
1634 // Since the helper routines would be called from multiple synchronization
1635 // sites.
1636 //
1637 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1638 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1639 // to those specialized methods.  That'd give us a mostly platform-independent
1640 // implementation that the JITs could optimize and inline at their pleasure.
1641 // Done correctly, the only time we'd need to cross to native could would be
1642 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1643 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1644 // (b) explicit barriers or fence operations.
1645 //
1646 // TODO:
1647 //
1648 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1649 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1650 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1651 //    the lock operators would typically be faster than reifying Self.
1652 //
1653 // *  Ideally I'd define the primitives as:
1654 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1655 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1656 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1657 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1658 //    Furthermore the register assignments are overconstrained, possibly resulting in
1659 //    sub-optimal code near the synchronization site.
1660 //
1661 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1662 //    Alternately, use a better sp-proximity test.
1663 //
1664 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1665 //    Either one is sufficient to uniquely identify a thread.
1666 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1667 //
1668 // *  Intrinsify notify() and notifyAll() for the common cases where the
1669 //    object is locked by the calling thread but the waitlist is empty.
1670 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1671 //
1672 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1673 //    But beware of excessive branch density on AMD Opterons.
1674 //
1675 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1676 //    or failure of the fast-path.  If the fast-path fails then we pass
1677 //    control to the slow-path, typically in C.  In Fast_Lock and
1678 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1679 //    will emit a conditional branch immediately after the node.
1680 //    So we have branches to branches and lots of ICC.ZF games.
1681 //    Instead, it might be better to have C2 pass a "FailureLabel"
1682 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1683 //    will drop through the node.  ICC.ZF is undefined at exit.
1684 //    In the case of failure, the node will branch directly to the
1685 //    FailureLabel
1686 
1687 
1688 // obj: object to lock
1689 // box: on-stack box address (displaced header location) - KILLED
1690 // rax,: tmp -- KILLED
1691 // scr: tmp -- KILLED
1692 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1693                                Register scrReg, Register cx1Reg, Register cx2Reg,
1694                                BiasedLockingCounters* counters,
1695                                RTMLockingCounters* rtm_counters,
1696                                RTMLockingCounters* stack_rtm_counters,
1697                                Metadata* method_data,
1698                                bool use_rtm, bool profile_rtm) {
1699   // Ensure the register assignments are disjoint
1700   assert(tmpReg == rax, "");
1701 
1702   if (use_rtm) {
1703     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1704   } else {
1705     assert(cx1Reg == noreg, "");
1706     assert(cx2Reg == noreg, "");
1707     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1708   }
1709 
1710   if (counters != NULL) {
1711     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1712   }
1713   if (EmitSync & 1) {
1714       // set box->dhw = markOopDesc::unused_mark()
1715       // Force all sync thru slow-path: slow_enter() and slow_exit()
1716       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1717       cmpptr (rsp, (int32_t)NULL_WORD);
1718   } else {
1719     // Possible cases that we'll encounter in fast_lock
1720     // ------------------------------------------------
1721     // * Inflated
1722     //    -- unlocked
1723     //    -- Locked
1724     //       = by self
1725     //       = by other
1726     // * biased
1727     //    -- by Self
1728     //    -- by other
1729     // * neutral
1730     // * stack-locked
1731     //    -- by self
1732     //       = sp-proximity test hits
1733     //       = sp-proximity test generates false-negative
1734     //    -- by other
1735     //
1736 
1737     Label IsInflated, DONE_LABEL;
1738 
1739     // it's stack-locked, biased or neutral
1740     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1741     // order to reduce the number of conditional branches in the most common cases.
1742     // Beware -- there's a subtle invariant that fetch of the markword
1743     // at [FETCH], below, will never observe a biased encoding (*101b).
1744     // If this invariant is not held we risk exclusion (safety) failure.
1745     if (UseBiasedLocking && !UseOptoBiasInlining) {
1746       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1747     }
1748 
1749 #if INCLUDE_RTM_OPT
1750     if (UseRTMForStackLocks && use_rtm) {
1751       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1752                         stack_rtm_counters, method_data, profile_rtm,
1753                         DONE_LABEL, IsInflated);
1754     }
1755 #endif // INCLUDE_RTM_OPT
1756 
1757     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1758     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1759     jccb(Assembler::notZero, IsInflated);
1760 
1761     // Attempt stack-locking ...
1762     orptr (tmpReg, markOopDesc::unlocked_value);
1763     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1764     if (os::is_MP()) {
1765       lock();
1766     }
1767     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1768     if (counters != NULL) {
1769       cond_inc32(Assembler::equal,
1770                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1771     }
1772     jcc(Assembler::equal, DONE_LABEL);           // Success
1773 
1774     // Recursive locking.
1775     // The object is stack-locked: markword contains stack pointer to BasicLock.
1776     // Locked by current thread if difference with current SP is less than one page.
1777     subptr(tmpReg, rsp);
1778     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1779     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1780     movptr(Address(boxReg, 0), tmpReg);
1781     if (counters != NULL) {
1782       cond_inc32(Assembler::equal,
1783                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1784     }
1785     jmp(DONE_LABEL);
1786 
1787     bind(IsInflated);
1788     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1789 
1790 #if INCLUDE_RTM_OPT
1791     // Use the same RTM locking code in 32- and 64-bit VM.
1792     if (use_rtm) {
1793       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1794                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1795     } else {
1796 #endif // INCLUDE_RTM_OPT
1797 
1798 #ifndef _LP64
1799     // The object is inflated.
1800 
1801     // boxReg refers to the on-stack BasicLock in the current frame.
1802     // We'd like to write:
1803     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1804     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1805     // additional latency as we have another ST in the store buffer that must drain.
1806 
1807     if (EmitSync & 8192) {
1808        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1809        get_thread (scrReg);
1810        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1811        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1812        if (os::is_MP()) {
1813          lock();
1814        }
1815        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1816     } else
1817     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1818        // register juggle because we need tmpReg for cmpxchgptr below
1819        movptr(scrReg, boxReg);
1820        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1821 
1822        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1823        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1824           // prefetchw [eax + Offset(_owner)-2]
1825           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1826        }
1827 
1828        if ((EmitSync & 64) == 0) {
1829          // Optimistic form: consider XORL tmpReg,tmpReg
1830          movptr(tmpReg, NULL_WORD);
1831        } else {
1832          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1833          // Test-And-CAS instead of CAS
1834          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1835          testptr(tmpReg, tmpReg);                   // Locked ?
1836          jccb  (Assembler::notZero, DONE_LABEL);
1837        }
1838 
1839        // Appears unlocked - try to swing _owner from null to non-null.
1840        // Ideally, I'd manifest "Self" with get_thread and then attempt
1841        // to CAS the register containing Self into m->Owner.
1842        // But we don't have enough registers, so instead we can either try to CAS
1843        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1844        // we later store "Self" into m->Owner.  Transiently storing a stack address
1845        // (rsp or the address of the box) into  m->owner is harmless.
1846        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1847        if (os::is_MP()) {
1848          lock();
1849        }
1850        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1851        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1852        // If we weren't able to swing _owner from NULL to the BasicLock
1853        // then take the slow path.
1854        jccb  (Assembler::notZero, DONE_LABEL);
1855        // update _owner from BasicLock to thread
1856        get_thread (scrReg);                    // beware: clobbers ICCs
1857        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1858        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1859 
1860        // If the CAS fails we can either retry or pass control to the slow-path.
1861        // We use the latter tactic.
1862        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1863        // If the CAS was successful ...
1864        //   Self has acquired the lock
1865        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1866        // Intentional fall-through into DONE_LABEL ...
1867     } else {
1868        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1869        movptr(boxReg, tmpReg);
1870 
1871        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1872        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1873           // prefetchw [eax + Offset(_owner)-2]
1874           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1875        }
1876 
1877        if ((EmitSync & 64) == 0) {
1878          // Optimistic form
1879          xorptr  (tmpReg, tmpReg);
1880        } else {
1881          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1882          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1883          testptr(tmpReg, tmpReg);                   // Locked ?
1884          jccb  (Assembler::notZero, DONE_LABEL);
1885        }
1886 
1887        // Appears unlocked - try to swing _owner from null to non-null.
1888        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1889        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1890        get_thread (scrReg);
1891        if (os::is_MP()) {
1892          lock();
1893        }
1894        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1895 
1896        // If the CAS fails we can either retry or pass control to the slow-path.
1897        // We use the latter tactic.
1898        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1899        // If the CAS was successful ...
1900        //   Self has acquired the lock
1901        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1902        // Intentional fall-through into DONE_LABEL ...
1903     }
1904 #else // _LP64
1905     // It's inflated
1906     movq(scrReg, tmpReg);
1907     xorq(tmpReg, tmpReg);
1908 
1909     if (os::is_MP()) {
1910       lock();
1911     }
1912     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1913     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1914     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1915     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1916     // Intentional fall-through into DONE_LABEL ...
1917     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1918 #endif // _LP64
1919 #if INCLUDE_RTM_OPT
1920     } // use_rtm()
1921 #endif
1922     // DONE_LABEL is a hot target - we'd really like to place it at the
1923     // start of cache line by padding with NOPs.
1924     // See the AMD and Intel software optimization manuals for the
1925     // most efficient "long" NOP encodings.
1926     // Unfortunately none of our alignment mechanisms suffice.
1927     bind(DONE_LABEL);
1928 
1929     // At DONE_LABEL the icc ZFlag is set as follows ...
1930     // Fast_Unlock uses the same protocol.
1931     // ZFlag == 1 -> Success
1932     // ZFlag == 0 -> Failure - force control through the slow-path
1933   }
1934 }
1935 
1936 // obj: object to unlock
1937 // box: box address (displaced header location), killed.  Must be EAX.
1938 // tmp: killed, cannot be obj nor box.
1939 //
1940 // Some commentary on balanced locking:
1941 //
1942 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1943 // Methods that don't have provably balanced locking are forced to run in the
1944 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1945 // The interpreter provides two properties:
1946 // I1:  At return-time the interpreter automatically and quietly unlocks any
1947 //      objects acquired the current activation (frame).  Recall that the
1948 //      interpreter maintains an on-stack list of locks currently held by
1949 //      a frame.
1950 // I2:  If a method attempts to unlock an object that is not held by the
1951 //      the frame the interpreter throws IMSX.
1952 //
1953 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1954 // B() doesn't have provably balanced locking so it runs in the interpreter.
1955 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1956 // is still locked by A().
1957 //
1958 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1959 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1960 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1961 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1962 // Arguably given that the spec legislates the JNI case as undefined our implementation
1963 // could reasonably *avoid* checking owner in Fast_Unlock().
1964 // In the interest of performance we elide m->Owner==Self check in unlock.
1965 // A perfectly viable alternative is to elide the owner check except when
1966 // Xcheck:jni is enabled.
1967 
1968 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1969   assert(boxReg == rax, "");
1970   assert_different_registers(objReg, boxReg, tmpReg);
1971 
1972   if (EmitSync & 4) {
1973     // Disable - inhibit all inlining.  Force control through the slow-path
1974     cmpptr (rsp, 0);
1975   } else {
1976     Label DONE_LABEL, Stacked, CheckSucc;
1977 
1978     // Critically, the biased locking test must have precedence over
1979     // and appear before the (box->dhw == 0) recursive stack-lock test.
1980     if (UseBiasedLocking && !UseOptoBiasInlining) {
1981        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1982     }
1983 
1984 #if INCLUDE_RTM_OPT
1985     if (UseRTMForStackLocks && use_rtm) {
1986       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1987       Label L_regular_unlock;
1988       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1989       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1990       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1991       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1992       xend();                                       // otherwise end...
1993       jmp(DONE_LABEL);                              // ... and we're done
1994       bind(L_regular_unlock);
1995     }
1996 #endif
1997 
1998     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1999     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2000     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2001     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2002     jccb  (Assembler::zero, Stacked);
2003 
2004     // It's inflated.
2005 #if INCLUDE_RTM_OPT
2006     if (use_rtm) {
2007       Label L_regular_inflated_unlock;
2008       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2009       movptr(boxReg, Address(tmpReg, owner_offset));
2010       testptr(boxReg, boxReg);
2011       jccb(Assembler::notZero, L_regular_inflated_unlock);
2012       xend();
2013       jmpb(DONE_LABEL);
2014       bind(L_regular_inflated_unlock);
2015     }
2016 #endif
2017 
2018     // Despite our balanced locking property we still check that m->_owner == Self
2019     // as java routines or native JNI code called by this thread might
2020     // have released the lock.
2021     // Refer to the comments in synchronizer.cpp for how we might encode extra
2022     // state in _succ so we can avoid fetching EntryList|cxq.
2023     //
2024     // I'd like to add more cases in fast_lock() and fast_unlock() --
2025     // such as recursive enter and exit -- but we have to be wary of
2026     // I$ bloat, T$ effects and BP$ effects.
2027     //
2028     // If there's no contention try a 1-0 exit.  That is, exit without
2029     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2030     // we detect and recover from the race that the 1-0 exit admits.
2031     //
2032     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2033     // before it STs null into _owner, releasing the lock.  Updates
2034     // to data protected by the critical section must be visible before
2035     // we drop the lock (and thus before any other thread could acquire
2036     // the lock and observe the fields protected by the lock).
2037     // IA32's memory-model is SPO, so STs are ordered with respect to
2038     // each other and there's no need for an explicit barrier (fence).
2039     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2040 #ifndef _LP64
2041     get_thread (boxReg);
2042     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2043       // prefetchw [ebx + Offset(_owner)-2]
2044       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2045     }
2046 
2047     // Note that we could employ various encoding schemes to reduce
2048     // the number of loads below (currently 4) to just 2 or 3.
2049     // Refer to the comments in synchronizer.cpp.
2050     // In practice the chain of fetches doesn't seem to impact performance, however.
2051     xorptr(boxReg, boxReg);
2052     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2053        // Attempt to reduce branch density - AMD's branch predictor.
2054        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2055        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2056        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2057        jccb  (Assembler::notZero, DONE_LABEL);
2058        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2059        jmpb  (DONE_LABEL);
2060     } else {
2061        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2062        jccb  (Assembler::notZero, DONE_LABEL);
2063        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2064        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2065        jccb  (Assembler::notZero, CheckSucc);
2066        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2067        jmpb  (DONE_LABEL);
2068     }
2069 
2070     // The Following code fragment (EmitSync & 65536) improves the performance of
2071     // contended applications and contended synchronization microbenchmarks.
2072     // Unfortunately the emission of the code - even though not executed - causes regressions
2073     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2074     // with an equal number of never-executed NOPs results in the same regression.
2075     // We leave it off by default.
2076 
2077     if ((EmitSync & 65536) != 0) {
2078        Label LSuccess, LGoSlowPath ;
2079 
2080        bind  (CheckSucc);
2081 
2082        // Optional pre-test ... it's safe to elide this
2083        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2084        jccb(Assembler::zero, LGoSlowPath);
2085 
2086        // We have a classic Dekker-style idiom:
2087        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2088        // There are a number of ways to implement the barrier:
2089        // (1) lock:andl &m->_owner, 0
2090        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2091        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2092        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2093        // (2) If supported, an explicit MFENCE is appealing.
2094        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2095        //     particularly if the write-buffer is full as might be the case if
2096        //     if stores closely precede the fence or fence-equivalent instruction.
2097        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2098        //     as the situation has changed with Nehalem and Shanghai.
2099        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2100        //     The $lines underlying the top-of-stack should be in M-state.
2101        //     The locked add instruction is serializing, of course.
2102        // (4) Use xchg, which is serializing
2103        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2104        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2105        //     The integer condition codes will tell us if succ was 0.
2106        //     Since _succ and _owner should reside in the same $line and
2107        //     we just stored into _owner, it's likely that the $line
2108        //     remains in M-state for the lock:orl.
2109        //
2110        // We currently use (3), although it's likely that switching to (2)
2111        // is correct for the future.
2112 
2113        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2114        if (os::is_MP()) {
2115          lock(); addptr(Address(rsp, 0), 0);
2116        }
2117        // Ratify _succ remains non-null
2118        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2119        jccb  (Assembler::notZero, LSuccess);
2120 
2121        xorptr(boxReg, boxReg);                  // box is really EAX
2122        if (os::is_MP()) { lock(); }
2123        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2124        // There's no successor so we tried to regrab the lock with the
2125        // placeholder value. If that didn't work, then another thread
2126        // grabbed the lock so we're done (and exit was a success).
2127        jccb  (Assembler::notEqual, LSuccess);
2128        // Since we're low on registers we installed rsp as a placeholding in _owner.
2129        // Now install Self over rsp.  This is safe as we're transitioning from
2130        // non-null to non=null
2131        get_thread (boxReg);
2132        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2133        // Intentional fall-through into LGoSlowPath ...
2134 
2135        bind  (LGoSlowPath);
2136        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2137        jmpb  (DONE_LABEL);
2138 
2139        bind  (LSuccess);
2140        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2141        jmpb  (DONE_LABEL);
2142     }
2143 
2144     bind (Stacked);
2145     // It's not inflated and it's not recursively stack-locked and it's not biased.
2146     // It must be stack-locked.
2147     // Try to reset the header to displaced header.
2148     // The "box" value on the stack is stable, so we can reload
2149     // and be assured we observe the same value as above.
2150     movptr(tmpReg, Address(boxReg, 0));
2151     if (os::is_MP()) {
2152       lock();
2153     }
2154     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2155     // Intention fall-thru into DONE_LABEL
2156 
2157     // DONE_LABEL is a hot target - we'd really like to place it at the
2158     // start of cache line by padding with NOPs.
2159     // See the AMD and Intel software optimization manuals for the
2160     // most efficient "long" NOP encodings.
2161     // Unfortunately none of our alignment mechanisms suffice.
2162     if ((EmitSync & 65536) == 0) {
2163        bind (CheckSucc);
2164     }
2165 #else // _LP64
2166     // It's inflated
2167     if (EmitSync & 1024) {
2168       // Emit code to check that _owner == Self
2169       // We could fold the _owner test into subsequent code more efficiently
2170       // than using a stand-alone check, but since _owner checking is off by
2171       // default we don't bother. We also might consider predicating the
2172       // _owner==Self check on Xcheck:jni or running on a debug build.
2173       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2174       xorptr(boxReg, r15_thread);
2175     } else {
2176       xorptr(boxReg, boxReg);
2177     }
2178     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2179     jccb  (Assembler::notZero, DONE_LABEL);
2180     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2181     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2182     jccb  (Assembler::notZero, CheckSucc);
2183     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2184     jmpb  (DONE_LABEL);
2185 
2186     if ((EmitSync & 65536) == 0) {
2187       // Try to avoid passing control into the slow_path ...
2188       Label LSuccess, LGoSlowPath ;
2189       bind  (CheckSucc);
2190 
2191       // The following optional optimization can be elided if necessary
2192       // Effectively: if (succ == null) goto SlowPath
2193       // The code reduces the window for a race, however,
2194       // and thus benefits performance.
2195       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2196       jccb  (Assembler::zero, LGoSlowPath);
2197 
2198       xorptr(boxReg, boxReg);
2199       if ((EmitSync & 16) && os::is_MP()) {
2200         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2201       } else {
2202         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2203         if (os::is_MP()) {
2204           // Memory barrier/fence
2205           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2206           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2207           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2208           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2209           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2210           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2211           lock(); addl(Address(rsp, 0), 0);
2212         }
2213       }
2214       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2215       jccb  (Assembler::notZero, LSuccess);
2216 
2217       // Rare inopportune interleaving - race.
2218       // The successor vanished in the small window above.
2219       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2220       // We need to ensure progress and succession.
2221       // Try to reacquire the lock.
2222       // If that fails then the new owner is responsible for succession and this
2223       // thread needs to take no further action and can exit via the fast path (success).
2224       // If the re-acquire succeeds then pass control into the slow path.
2225       // As implemented, this latter mode is horrible because we generated more
2226       // coherence traffic on the lock *and* artifically extended the critical section
2227       // length while by virtue of passing control into the slow path.
2228 
2229       // box is really RAX -- the following CMPXCHG depends on that binding
2230       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2231       if (os::is_MP()) { lock(); }
2232       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2233       // There's no successor so we tried to regrab the lock.
2234       // If that didn't work, then another thread grabbed the
2235       // lock so we're done (and exit was a success).
2236       jccb  (Assembler::notEqual, LSuccess);
2237       // Intentional fall-through into slow-path
2238 
2239       bind  (LGoSlowPath);
2240       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2241       jmpb  (DONE_LABEL);
2242 
2243       bind  (LSuccess);
2244       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2245       jmpb  (DONE_LABEL);
2246     }
2247 
2248     bind  (Stacked);
2249     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2250     if (os::is_MP()) { lock(); }
2251     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2252 
2253     if (EmitSync & 65536) {
2254        bind (CheckSucc);
2255     }
2256 #endif
2257     bind(DONE_LABEL);
2258   }
2259 }
2260 #endif // COMPILER2
2261 
2262 void MacroAssembler::c2bool(Register x) {
2263   // implements x == 0 ? 0 : 1
2264   // note: must only look at least-significant byte of x
2265   //       since C-style booleans are stored in one byte
2266   //       only! (was bug)
2267   andl(x, 0xFF);
2268   setb(Assembler::notZero, x);
2269 }
2270 
2271 // Wouldn't need if AddressLiteral version had new name
2272 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2273   Assembler::call(L, rtype);
2274 }
2275 
2276 void MacroAssembler::call(Register entry) {
2277   Assembler::call(entry);
2278 }
2279 
2280 void MacroAssembler::call(AddressLiteral entry) {
2281   if (reachable(entry)) {
2282     Assembler::call_literal(entry.target(), entry.rspec());
2283   } else {
2284     lea(rscratch1, entry);
2285     Assembler::call(rscratch1);
2286   }
2287 }
2288 
2289 void MacroAssembler::ic_call(address entry, jint method_index) {
2290   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2291   movptr(rax, (intptr_t)Universe::non_oop_word());
2292   call(AddressLiteral(entry, rh));
2293 }
2294 
2295 // Implementation of call_VM versions
2296 
2297 void MacroAssembler::call_VM(Register oop_result,
2298                              address entry_point,
2299                              bool check_exceptions) {
2300   Label C, E;
2301   call(C, relocInfo::none);
2302   jmp(E);
2303 
2304   bind(C);
2305   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2306   ret(0);
2307 
2308   bind(E);
2309 }
2310 
2311 void MacroAssembler::call_VM(Register oop_result,
2312                              address entry_point,
2313                              Register arg_1,
2314                              bool check_exceptions) {
2315   Label C, E;
2316   call(C, relocInfo::none);
2317   jmp(E);
2318 
2319   bind(C);
2320   pass_arg1(this, arg_1);
2321   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2322   ret(0);
2323 
2324   bind(E);
2325 }
2326 
2327 void MacroAssembler::call_VM(Register oop_result,
2328                              address entry_point,
2329                              Register arg_1,
2330                              Register arg_2,
2331                              bool check_exceptions) {
2332   Label C, E;
2333   call(C, relocInfo::none);
2334   jmp(E);
2335 
2336   bind(C);
2337 
2338   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2339 
2340   pass_arg2(this, arg_2);
2341   pass_arg1(this, arg_1);
2342   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2343   ret(0);
2344 
2345   bind(E);
2346 }
2347 
2348 void MacroAssembler::call_VM(Register oop_result,
2349                              address entry_point,
2350                              Register arg_1,
2351                              Register arg_2,
2352                              Register arg_3,
2353                              bool check_exceptions) {
2354   Label C, E;
2355   call(C, relocInfo::none);
2356   jmp(E);
2357 
2358   bind(C);
2359 
2360   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2361   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2362   pass_arg3(this, arg_3);
2363 
2364   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2365   pass_arg2(this, arg_2);
2366 
2367   pass_arg1(this, arg_1);
2368   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2369   ret(0);
2370 
2371   bind(E);
2372 }
2373 
2374 void MacroAssembler::call_VM(Register oop_result,
2375                              Register last_java_sp,
2376                              address entry_point,
2377                              int number_of_arguments,
2378                              bool check_exceptions) {
2379   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2380   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2381 }
2382 
2383 void MacroAssembler::call_VM(Register oop_result,
2384                              Register last_java_sp,
2385                              address entry_point,
2386                              Register arg_1,
2387                              bool check_exceptions) {
2388   pass_arg1(this, arg_1);
2389   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2390 }
2391 
2392 void MacroAssembler::call_VM(Register oop_result,
2393                              Register last_java_sp,
2394                              address entry_point,
2395                              Register arg_1,
2396                              Register arg_2,
2397                              bool check_exceptions) {
2398 
2399   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2400   pass_arg2(this, arg_2);
2401   pass_arg1(this, arg_1);
2402   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2403 }
2404 
2405 void MacroAssembler::call_VM(Register oop_result,
2406                              Register last_java_sp,
2407                              address entry_point,
2408                              Register arg_1,
2409                              Register arg_2,
2410                              Register arg_3,
2411                              bool check_exceptions) {
2412   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2413   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2414   pass_arg3(this, arg_3);
2415   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2416   pass_arg2(this, arg_2);
2417   pass_arg1(this, arg_1);
2418   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2419 }
2420 
2421 void MacroAssembler::super_call_VM(Register oop_result,
2422                                    Register last_java_sp,
2423                                    address entry_point,
2424                                    int number_of_arguments,
2425                                    bool check_exceptions) {
2426   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2427   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2428 }
2429 
2430 void MacroAssembler::super_call_VM(Register oop_result,
2431                                    Register last_java_sp,
2432                                    address entry_point,
2433                                    Register arg_1,
2434                                    bool check_exceptions) {
2435   pass_arg1(this, arg_1);
2436   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2437 }
2438 
2439 void MacroAssembler::super_call_VM(Register oop_result,
2440                                    Register last_java_sp,
2441                                    address entry_point,
2442                                    Register arg_1,
2443                                    Register arg_2,
2444                                    bool check_exceptions) {
2445 
2446   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2447   pass_arg2(this, arg_2);
2448   pass_arg1(this, arg_1);
2449   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2450 }
2451 
2452 void MacroAssembler::super_call_VM(Register oop_result,
2453                                    Register last_java_sp,
2454                                    address entry_point,
2455                                    Register arg_1,
2456                                    Register arg_2,
2457                                    Register arg_3,
2458                                    bool check_exceptions) {
2459   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2460   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2461   pass_arg3(this, arg_3);
2462   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2463   pass_arg2(this, arg_2);
2464   pass_arg1(this, arg_1);
2465   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2466 }
2467 
2468 void MacroAssembler::call_VM_base(Register oop_result,
2469                                   Register java_thread,
2470                                   Register last_java_sp,
2471                                   address  entry_point,
2472                                   int      number_of_arguments,
2473                                   bool     check_exceptions) {
2474   // determine java_thread register
2475   if (!java_thread->is_valid()) {
2476 #ifdef _LP64
2477     java_thread = r15_thread;
2478 #else
2479     java_thread = rdi;
2480     get_thread(java_thread);
2481 #endif // LP64
2482   }
2483   // determine last_java_sp register
2484   if (!last_java_sp->is_valid()) {
2485     last_java_sp = rsp;
2486   }
2487   // debugging support
2488   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2489   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2490 #ifdef ASSERT
2491   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2492   // r12 is the heapbase.
2493   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2494 #endif // ASSERT
2495 
2496   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2497   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2498 
2499   // push java thread (becomes first argument of C function)
2500 
2501   NOT_LP64(push(java_thread); number_of_arguments++);
2502   LP64_ONLY(mov(c_rarg0, r15_thread));
2503 
2504   // set last Java frame before call
2505   assert(last_java_sp != rbp, "can't use ebp/rbp");
2506 
2507   // Only interpreter should have to set fp
2508   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2509 
2510   // do the call, remove parameters
2511   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2512 
2513   // restore the thread (cannot use the pushed argument since arguments
2514   // may be overwritten by C code generated by an optimizing compiler);
2515   // however can use the register value directly if it is callee saved.
2516   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2517     // rdi & rsi (also r15) are callee saved -> nothing to do
2518 #ifdef ASSERT
2519     guarantee(java_thread != rax, "change this code");
2520     push(rax);
2521     { Label L;
2522       get_thread(rax);
2523       cmpptr(java_thread, rax);
2524       jcc(Assembler::equal, L);
2525       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2526       bind(L);
2527     }
2528     pop(rax);
2529 #endif
2530   } else {
2531     get_thread(java_thread);
2532   }
2533   // reset last Java frame
2534   // Only interpreter should have to clear fp
2535   reset_last_Java_frame(java_thread, true);
2536 
2537    // C++ interp handles this in the interpreter
2538   check_and_handle_popframe(java_thread);
2539   check_and_handle_earlyret(java_thread);
2540 
2541   if (check_exceptions) {
2542     // check for pending exceptions (java_thread is set upon return)
2543     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2544 #ifndef _LP64
2545     jump_cc(Assembler::notEqual,
2546             RuntimeAddress(StubRoutines::forward_exception_entry()));
2547 #else
2548     // This used to conditionally jump to forward_exception however it is
2549     // possible if we relocate that the branch will not reach. So we must jump
2550     // around so we can always reach
2551 
2552     Label ok;
2553     jcc(Assembler::equal, ok);
2554     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2555     bind(ok);
2556 #endif // LP64
2557   }
2558 
2559   // get oop result if there is one and reset the value in the thread
2560   if (oop_result->is_valid()) {
2561     get_vm_result(oop_result, java_thread);
2562   }
2563 }
2564 
2565 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2566 
2567   // Calculate the value for last_Java_sp
2568   // somewhat subtle. call_VM does an intermediate call
2569   // which places a return address on the stack just under the
2570   // stack pointer as the user finsihed with it. This allows
2571   // use to retrieve last_Java_pc from last_Java_sp[-1].
2572   // On 32bit we then have to push additional args on the stack to accomplish
2573   // the actual requested call. On 64bit call_VM only can use register args
2574   // so the only extra space is the return address that call_VM created.
2575   // This hopefully explains the calculations here.
2576 
2577 #ifdef _LP64
2578   // We've pushed one address, correct last_Java_sp
2579   lea(rax, Address(rsp, wordSize));
2580 #else
2581   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2582 #endif // LP64
2583 
2584   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2585 
2586 }
2587 
2588 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2589 void MacroAssembler::call_VM_leaf0(address entry_point) {
2590   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2591 }
2592 
2593 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2594   call_VM_leaf_base(entry_point, number_of_arguments);
2595 }
2596 
2597 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2598   pass_arg0(this, arg_0);
2599   call_VM_leaf(entry_point, 1);
2600 }
2601 
2602 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2603 
2604   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2605   pass_arg1(this, arg_1);
2606   pass_arg0(this, arg_0);
2607   call_VM_leaf(entry_point, 2);
2608 }
2609 
2610 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2611   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2612   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2613   pass_arg2(this, arg_2);
2614   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2615   pass_arg1(this, arg_1);
2616   pass_arg0(this, arg_0);
2617   call_VM_leaf(entry_point, 3);
2618 }
2619 
2620 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2621   pass_arg0(this, arg_0);
2622   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2623 }
2624 
2625 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2626 
2627   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2628   pass_arg1(this, arg_1);
2629   pass_arg0(this, arg_0);
2630   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2631 }
2632 
2633 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2634   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2635   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2636   pass_arg2(this, arg_2);
2637   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2638   pass_arg1(this, arg_1);
2639   pass_arg0(this, arg_0);
2640   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2641 }
2642 
2643 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2644   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2645   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2646   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2647   pass_arg3(this, arg_3);
2648   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2649   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2650   pass_arg2(this, arg_2);
2651   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2652   pass_arg1(this, arg_1);
2653   pass_arg0(this, arg_0);
2654   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2655 }
2656 
2657 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2658   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2659   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2660   verify_oop(oop_result, "broken oop in call_VM_base");
2661 }
2662 
2663 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2664   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2665   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2666 }
2667 
2668 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2669 }
2670 
2671 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2672 }
2673 
2674 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2675   if (reachable(src1)) {
2676     cmpl(as_Address(src1), imm);
2677   } else {
2678     lea(rscratch1, src1);
2679     cmpl(Address(rscratch1, 0), imm);
2680   }
2681 }
2682 
2683 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2684   assert(!src2.is_lval(), "use cmpptr");
2685   if (reachable(src2)) {
2686     cmpl(src1, as_Address(src2));
2687   } else {
2688     lea(rscratch1, src2);
2689     cmpl(src1, Address(rscratch1, 0));
2690   }
2691 }
2692 
2693 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2694   Assembler::cmpl(src1, imm);
2695 }
2696 
2697 void MacroAssembler::cmp32(Register src1, Address src2) {
2698   Assembler::cmpl(src1, src2);
2699 }
2700 
2701 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2702   ucomisd(opr1, opr2);
2703 
2704   Label L;
2705   if (unordered_is_less) {
2706     movl(dst, -1);
2707     jcc(Assembler::parity, L);
2708     jcc(Assembler::below , L);
2709     movl(dst, 0);
2710     jcc(Assembler::equal , L);
2711     increment(dst);
2712   } else { // unordered is greater
2713     movl(dst, 1);
2714     jcc(Assembler::parity, L);
2715     jcc(Assembler::above , L);
2716     movl(dst, 0);
2717     jcc(Assembler::equal , L);
2718     decrementl(dst);
2719   }
2720   bind(L);
2721 }
2722 
2723 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2724   ucomiss(opr1, opr2);
2725 
2726   Label L;
2727   if (unordered_is_less) {
2728     movl(dst, -1);
2729     jcc(Assembler::parity, L);
2730     jcc(Assembler::below , L);
2731     movl(dst, 0);
2732     jcc(Assembler::equal , L);
2733     increment(dst);
2734   } else { // unordered is greater
2735     movl(dst, 1);
2736     jcc(Assembler::parity, L);
2737     jcc(Assembler::above , L);
2738     movl(dst, 0);
2739     jcc(Assembler::equal , L);
2740     decrementl(dst);
2741   }
2742   bind(L);
2743 }
2744 
2745 
2746 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2747   if (reachable(src1)) {
2748     cmpb(as_Address(src1), imm);
2749   } else {
2750     lea(rscratch1, src1);
2751     cmpb(Address(rscratch1, 0), imm);
2752   }
2753 }
2754 
2755 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2756 #ifdef _LP64
2757   if (src2.is_lval()) {
2758     movptr(rscratch1, src2);
2759     Assembler::cmpq(src1, rscratch1);
2760   } else if (reachable(src2)) {
2761     cmpq(src1, as_Address(src2));
2762   } else {
2763     lea(rscratch1, src2);
2764     Assembler::cmpq(src1, Address(rscratch1, 0));
2765   }
2766 #else
2767   if (src2.is_lval()) {
2768     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2769   } else {
2770     cmpl(src1, as_Address(src2));
2771   }
2772 #endif // _LP64
2773 }
2774 
2775 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2776   assert(src2.is_lval(), "not a mem-mem compare");
2777 #ifdef _LP64
2778   // moves src2's literal address
2779   movptr(rscratch1, src2);
2780   Assembler::cmpq(src1, rscratch1);
2781 #else
2782   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2783 #endif // _LP64
2784 }
2785 
2786 void MacroAssembler::cmpoop(Register src1, Register src2) {
2787   cmpptr(src1, src2);
2788 }
2789 
2790 void MacroAssembler::cmpoop(Register src1, Address src2) {
2791   cmpptr(src1, src2);
2792 }
2793 
2794 #ifdef _LP64
2795 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2796   movoop(rscratch1, src2);
2797   cmpptr(src1, rscratch1);
2798 }
2799 #endif
2800 
2801 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2802   if (reachable(adr)) {
2803     if (os::is_MP())
2804       lock();
2805     cmpxchgptr(reg, as_Address(adr));
2806   } else {
2807     lea(rscratch1, adr);
2808     if (os::is_MP())
2809       lock();
2810     cmpxchgptr(reg, Address(rscratch1, 0));
2811   }
2812 }
2813 
2814 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2815   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2816 }
2817 
2818 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2819   if (reachable(src)) {
2820     Assembler::comisd(dst, as_Address(src));
2821   } else {
2822     lea(rscratch1, src);
2823     Assembler::comisd(dst, Address(rscratch1, 0));
2824   }
2825 }
2826 
2827 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2828   if (reachable(src)) {
2829     Assembler::comiss(dst, as_Address(src));
2830   } else {
2831     lea(rscratch1, src);
2832     Assembler::comiss(dst, Address(rscratch1, 0));
2833   }
2834 }
2835 
2836 
2837 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2838   Condition negated_cond = negate_condition(cond);
2839   Label L;
2840   jcc(negated_cond, L);
2841   pushf(); // Preserve flags
2842   atomic_incl(counter_addr);
2843   popf();
2844   bind(L);
2845 }
2846 
2847 int MacroAssembler::corrected_idivl(Register reg) {
2848   // Full implementation of Java idiv and irem; checks for
2849   // special case as described in JVM spec., p.243 & p.271.
2850   // The function returns the (pc) offset of the idivl
2851   // instruction - may be needed for implicit exceptions.
2852   //
2853   //         normal case                           special case
2854   //
2855   // input : rax,: dividend                         min_int
2856   //         reg: divisor   (may not be rax,/rdx)   -1
2857   //
2858   // output: rax,: quotient  (= rax, idiv reg)       min_int
2859   //         rdx: remainder (= rax, irem reg)       0
2860   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2861   const int min_int = 0x80000000;
2862   Label normal_case, special_case;
2863 
2864   // check for special case
2865   cmpl(rax, min_int);
2866   jcc(Assembler::notEqual, normal_case);
2867   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2868   cmpl(reg, -1);
2869   jcc(Assembler::equal, special_case);
2870 
2871   // handle normal case
2872   bind(normal_case);
2873   cdql();
2874   int idivl_offset = offset();
2875   idivl(reg);
2876 
2877   // normal and special case exit
2878   bind(special_case);
2879 
2880   return idivl_offset;
2881 }
2882 
2883 
2884 
2885 void MacroAssembler::decrementl(Register reg, int value) {
2886   if (value == min_jint) {subl(reg, value) ; return; }
2887   if (value <  0) { incrementl(reg, -value); return; }
2888   if (value == 0) {                        ; return; }
2889   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2890   /* else */      { subl(reg, value)       ; return; }
2891 }
2892 
2893 void MacroAssembler::decrementl(Address dst, int value) {
2894   if (value == min_jint) {subl(dst, value) ; return; }
2895   if (value <  0) { incrementl(dst, -value); return; }
2896   if (value == 0) {                        ; return; }
2897   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2898   /* else */      { subl(dst, value)       ; return; }
2899 }
2900 
2901 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2902   assert (shift_value > 0, "illegal shift value");
2903   Label _is_positive;
2904   testl (reg, reg);
2905   jcc (Assembler::positive, _is_positive);
2906   int offset = (1 << shift_value) - 1 ;
2907 
2908   if (offset == 1) {
2909     incrementl(reg);
2910   } else {
2911     addl(reg, offset);
2912   }
2913 
2914   bind (_is_positive);
2915   sarl(reg, shift_value);
2916 }
2917 
2918 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2919   if (reachable(src)) {
2920     Assembler::divsd(dst, as_Address(src));
2921   } else {
2922     lea(rscratch1, src);
2923     Assembler::divsd(dst, Address(rscratch1, 0));
2924   }
2925 }
2926 
2927 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2928   if (reachable(src)) {
2929     Assembler::divss(dst, as_Address(src));
2930   } else {
2931     lea(rscratch1, src);
2932     Assembler::divss(dst, Address(rscratch1, 0));
2933   }
2934 }
2935 
2936 // !defined(COMPILER2) is because of stupid core builds
2937 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2938 void MacroAssembler::empty_FPU_stack() {
2939   if (VM_Version::supports_mmx()) {
2940     emms();
2941   } else {
2942     for (int i = 8; i-- > 0; ) ffree(i);
2943   }
2944 }
2945 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2946 
2947 
2948 // Defines obj, preserves var_size_in_bytes
2949 void MacroAssembler::eden_allocate(Register obj,
2950                                    Register var_size_in_bytes,
2951                                    int con_size_in_bytes,
2952                                    Register t1,
2953                                    Label& slow_case) {
2954   assert(obj == rax, "obj must be in rax, for cmpxchg");
2955   assert_different_registers(obj, var_size_in_bytes, t1);
2956   if (!Universe::heap()->supports_inline_contig_alloc()) {
2957     jmp(slow_case);
2958   } else {
2959     Register end = t1;
2960     Label retry;
2961     bind(retry);
2962     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2963     movptr(obj, heap_top);
2964     if (var_size_in_bytes == noreg) {
2965       lea(end, Address(obj, con_size_in_bytes));
2966     } else {
2967       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2968     }
2969     // if end < obj then we wrapped around => object too long => slow case
2970     cmpptr(end, obj);
2971     jcc(Assembler::below, slow_case);
2972     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2973     jcc(Assembler::above, slow_case);
2974     // Compare obj with the top addr, and if still equal, store the new top addr in
2975     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2976     // it otherwise. Use lock prefix for atomicity on MPs.
2977     locked_cmpxchgptr(end, heap_top);
2978     jcc(Assembler::notEqual, retry);
2979   }
2980 }
2981 
2982 void MacroAssembler::enter() {
2983   push(rbp);
2984   mov(rbp, rsp);
2985 }
2986 
2987 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2988 void MacroAssembler::fat_nop() {
2989   if (UseAddressNop) {
2990     addr_nop_5();
2991   } else {
2992     emit_int8(0x26); // es:
2993     emit_int8(0x2e); // cs:
2994     emit_int8(0x64); // fs:
2995     emit_int8(0x65); // gs:
2996     emit_int8((unsigned char)0x90);
2997   }
2998 }
2999 
3000 void MacroAssembler::fcmp(Register tmp) {
3001   fcmp(tmp, 1, true, true);
3002 }
3003 
3004 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3005   assert(!pop_right || pop_left, "usage error");
3006   if (VM_Version::supports_cmov()) {
3007     assert(tmp == noreg, "unneeded temp");
3008     if (pop_left) {
3009       fucomip(index);
3010     } else {
3011       fucomi(index);
3012     }
3013     if (pop_right) {
3014       fpop();
3015     }
3016   } else {
3017     assert(tmp != noreg, "need temp");
3018     if (pop_left) {
3019       if (pop_right) {
3020         fcompp();
3021       } else {
3022         fcomp(index);
3023       }
3024     } else {
3025       fcom(index);
3026     }
3027     // convert FPU condition into eflags condition via rax,
3028     save_rax(tmp);
3029     fwait(); fnstsw_ax();
3030     sahf();
3031     restore_rax(tmp);
3032   }
3033   // condition codes set as follows:
3034   //
3035   // CF (corresponds to C0) if x < y
3036   // PF (corresponds to C2) if unordered
3037   // ZF (corresponds to C3) if x = y
3038 }
3039 
3040 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3041   fcmp2int(dst, unordered_is_less, 1, true, true);
3042 }
3043 
3044 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3045   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3046   Label L;
3047   if (unordered_is_less) {
3048     movl(dst, -1);
3049     jcc(Assembler::parity, L);
3050     jcc(Assembler::below , L);
3051     movl(dst, 0);
3052     jcc(Assembler::equal , L);
3053     increment(dst);
3054   } else { // unordered is greater
3055     movl(dst, 1);
3056     jcc(Assembler::parity, L);
3057     jcc(Assembler::above , L);
3058     movl(dst, 0);
3059     jcc(Assembler::equal , L);
3060     decrementl(dst);
3061   }
3062   bind(L);
3063 }
3064 
3065 void MacroAssembler::fld_d(AddressLiteral src) {
3066   fld_d(as_Address(src));
3067 }
3068 
3069 void MacroAssembler::fld_s(AddressLiteral src) {
3070   fld_s(as_Address(src));
3071 }
3072 
3073 void MacroAssembler::fld_x(AddressLiteral src) {
3074   Assembler::fld_x(as_Address(src));
3075 }
3076 
3077 void MacroAssembler::fldcw(AddressLiteral src) {
3078   Assembler::fldcw(as_Address(src));
3079 }
3080 
3081 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3082   if (reachable(src)) {
3083     Assembler::mulpd(dst, as_Address(src));
3084   } else {
3085     lea(rscratch1, src);
3086     Assembler::mulpd(dst, Address(rscratch1, 0));
3087   }
3088 }
3089 
3090 void MacroAssembler::increase_precision() {
3091   subptr(rsp, BytesPerWord);
3092   fnstcw(Address(rsp, 0));
3093   movl(rax, Address(rsp, 0));
3094   orl(rax, 0x300);
3095   push(rax);
3096   fldcw(Address(rsp, 0));
3097   pop(rax);
3098 }
3099 
3100 void MacroAssembler::restore_precision() {
3101   fldcw(Address(rsp, 0));
3102   addptr(rsp, BytesPerWord);
3103 }
3104 
3105 void MacroAssembler::fpop() {
3106   ffree();
3107   fincstp();
3108 }
3109 
3110 void MacroAssembler::load_float(Address src) {
3111   if (UseSSE >= 1) {
3112     movflt(xmm0, src);
3113   } else {
3114     LP64_ONLY(ShouldNotReachHere());
3115     NOT_LP64(fld_s(src));
3116   }
3117 }
3118 
3119 void MacroAssembler::store_float(Address dst) {
3120   if (UseSSE >= 1) {
3121     movflt(dst, xmm0);
3122   } else {
3123     LP64_ONLY(ShouldNotReachHere());
3124     NOT_LP64(fstp_s(dst));
3125   }
3126 }
3127 
3128 void MacroAssembler::load_double(Address src) {
3129   if (UseSSE >= 2) {
3130     movdbl(xmm0, src);
3131   } else {
3132     LP64_ONLY(ShouldNotReachHere());
3133     NOT_LP64(fld_d(src));
3134   }
3135 }
3136 
3137 void MacroAssembler::store_double(Address dst) {
3138   if (UseSSE >= 2) {
3139     movdbl(dst, xmm0);
3140   } else {
3141     LP64_ONLY(ShouldNotReachHere());
3142     NOT_LP64(fstp_d(dst));
3143   }
3144 }
3145 
3146 void MacroAssembler::fremr(Register tmp) {
3147   save_rax(tmp);
3148   { Label L;
3149     bind(L);
3150     fprem();
3151     fwait(); fnstsw_ax();
3152 #ifdef _LP64
3153     testl(rax, 0x400);
3154     jcc(Assembler::notEqual, L);
3155 #else
3156     sahf();
3157     jcc(Assembler::parity, L);
3158 #endif // _LP64
3159   }
3160   restore_rax(tmp);
3161   // Result is in ST0.
3162   // Note: fxch & fpop to get rid of ST1
3163   // (otherwise FPU stack could overflow eventually)
3164   fxch(1);
3165   fpop();
3166 }
3167 
3168 // dst = c = a * b + c
3169 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3170   Assembler::vfmadd231sd(c, a, b);
3171   if (dst != c) {
3172     movdbl(dst, c);
3173   }
3174 }
3175 
3176 // dst = c = a * b + c
3177 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3178   Assembler::vfmadd231ss(c, a, b);
3179   if (dst != c) {
3180     movflt(dst, c);
3181   }
3182 }
3183 
3184 // dst = c = a * b + c
3185 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3186   Assembler::vfmadd231pd(c, a, b, vector_len);
3187   if (dst != c) {
3188     vmovdqu(dst, c);
3189   }
3190 }
3191 
3192 // dst = c = a * b + c
3193 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3194   Assembler::vfmadd231ps(c, a, b, vector_len);
3195   if (dst != c) {
3196     vmovdqu(dst, c);
3197   }
3198 }
3199 
3200 // dst = c = a * b + c
3201 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3202   Assembler::vfmadd231pd(c, a, b, vector_len);
3203   if (dst != c) {
3204     vmovdqu(dst, c);
3205   }
3206 }
3207 
3208 // dst = c = a * b + c
3209 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3210   Assembler::vfmadd231ps(c, a, b, vector_len);
3211   if (dst != c) {
3212     vmovdqu(dst, c);
3213   }
3214 }
3215 
3216 void MacroAssembler::incrementl(AddressLiteral dst) {
3217   if (reachable(dst)) {
3218     incrementl(as_Address(dst));
3219   } else {
3220     lea(rscratch1, dst);
3221     incrementl(Address(rscratch1, 0));
3222   }
3223 }
3224 
3225 void MacroAssembler::incrementl(ArrayAddress dst) {
3226   incrementl(as_Address(dst));
3227 }
3228 
3229 void MacroAssembler::incrementl(Register reg, int value) {
3230   if (value == min_jint) {addl(reg, value) ; return; }
3231   if (value <  0) { decrementl(reg, -value); return; }
3232   if (value == 0) {                        ; return; }
3233   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3234   /* else */      { addl(reg, value)       ; return; }
3235 }
3236 
3237 void MacroAssembler::incrementl(Address dst, int value) {
3238   if (value == min_jint) {addl(dst, value) ; return; }
3239   if (value <  0) { decrementl(dst, -value); return; }
3240   if (value == 0) {                        ; return; }
3241   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3242   /* else */      { addl(dst, value)       ; return; }
3243 }
3244 
3245 void MacroAssembler::jump(AddressLiteral dst) {
3246   if (reachable(dst)) {
3247     jmp_literal(dst.target(), dst.rspec());
3248   } else {
3249     lea(rscratch1, dst);
3250     jmp(rscratch1);
3251   }
3252 }
3253 
3254 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3255   if (reachable(dst)) {
3256     InstructionMark im(this);
3257     relocate(dst.reloc());
3258     const int short_size = 2;
3259     const int long_size = 6;
3260     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3261     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3262       // 0111 tttn #8-bit disp
3263       emit_int8(0x70 | cc);
3264       emit_int8((offs - short_size) & 0xFF);
3265     } else {
3266       // 0000 1111 1000 tttn #32-bit disp
3267       emit_int8(0x0F);
3268       emit_int8((unsigned char)(0x80 | cc));
3269       emit_int32(offs - long_size);
3270     }
3271   } else {
3272 #ifdef ASSERT
3273     warning("reversing conditional branch");
3274 #endif /* ASSERT */
3275     Label skip;
3276     jccb(reverse[cc], skip);
3277     lea(rscratch1, dst);
3278     Assembler::jmp(rscratch1);
3279     bind(skip);
3280   }
3281 }
3282 
3283 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3284   if (reachable(src)) {
3285     Assembler::ldmxcsr(as_Address(src));
3286   } else {
3287     lea(rscratch1, src);
3288     Assembler::ldmxcsr(Address(rscratch1, 0));
3289   }
3290 }
3291 
3292 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3293   int off;
3294   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3295     off = offset();
3296     movsbl(dst, src); // movsxb
3297   } else {
3298     off = load_unsigned_byte(dst, src);
3299     shll(dst, 24);
3300     sarl(dst, 24);
3301   }
3302   return off;
3303 }
3304 
3305 // Note: load_signed_short used to be called load_signed_word.
3306 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3307 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3308 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3309 int MacroAssembler::load_signed_short(Register dst, Address src) {
3310   int off;
3311   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3312     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3313     // version but this is what 64bit has always done. This seems to imply
3314     // that users are only using 32bits worth.
3315     off = offset();
3316     movswl(dst, src); // movsxw
3317   } else {
3318     off = load_unsigned_short(dst, src);
3319     shll(dst, 16);
3320     sarl(dst, 16);
3321   }
3322   return off;
3323 }
3324 
3325 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3326   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3327   // and "3.9 Partial Register Penalties", p. 22).
3328   int off;
3329   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3330     off = offset();
3331     movzbl(dst, src); // movzxb
3332   } else {
3333     xorl(dst, dst);
3334     off = offset();
3335     movb(dst, src);
3336   }
3337   return off;
3338 }
3339 
3340 // Note: load_unsigned_short used to be called load_unsigned_word.
3341 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3342   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3343   // and "3.9 Partial Register Penalties", p. 22).
3344   int off;
3345   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3346     off = offset();
3347     movzwl(dst, src); // movzxw
3348   } else {
3349     xorl(dst, dst);
3350     off = offset();
3351     movw(dst, src);
3352   }
3353   return off;
3354 }
3355 
3356 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3357   switch (size_in_bytes) {
3358 #ifndef _LP64
3359   case  8:
3360     assert(dst2 != noreg, "second dest register required");
3361     movl(dst,  src);
3362     movl(dst2, src.plus_disp(BytesPerInt));
3363     break;
3364 #else
3365   case  8:  movq(dst, src); break;
3366 #endif
3367   case  4:  movl(dst, src); break;
3368   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3369   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3370   default:  ShouldNotReachHere();
3371   }
3372 }
3373 
3374 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3375   switch (size_in_bytes) {
3376 #ifndef _LP64
3377   case  8:
3378     assert(src2 != noreg, "second source register required");
3379     movl(dst,                        src);
3380     movl(dst.plus_disp(BytesPerInt), src2);
3381     break;
3382 #else
3383   case  8:  movq(dst, src); break;
3384 #endif
3385   case  4:  movl(dst, src); break;
3386   case  2:  movw(dst, src); break;
3387   case  1:  movb(dst, src); break;
3388   default:  ShouldNotReachHere();
3389   }
3390 }
3391 
3392 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3393   if (reachable(dst)) {
3394     movl(as_Address(dst), src);
3395   } else {
3396     lea(rscratch1, dst);
3397     movl(Address(rscratch1, 0), src);
3398   }
3399 }
3400 
3401 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3402   if (reachable(src)) {
3403     movl(dst, as_Address(src));
3404   } else {
3405     lea(rscratch1, src);
3406     movl(dst, Address(rscratch1, 0));
3407   }
3408 }
3409 
3410 // C++ bool manipulation
3411 
3412 void MacroAssembler::movbool(Register dst, Address src) {
3413   if(sizeof(bool) == 1)
3414     movb(dst, src);
3415   else if(sizeof(bool) == 2)
3416     movw(dst, src);
3417   else if(sizeof(bool) == 4)
3418     movl(dst, src);
3419   else
3420     // unsupported
3421     ShouldNotReachHere();
3422 }
3423 
3424 void MacroAssembler::movbool(Address dst, bool boolconst) {
3425   if(sizeof(bool) == 1)
3426     movb(dst, (int) boolconst);
3427   else if(sizeof(bool) == 2)
3428     movw(dst, (int) boolconst);
3429   else if(sizeof(bool) == 4)
3430     movl(dst, (int) boolconst);
3431   else
3432     // unsupported
3433     ShouldNotReachHere();
3434 }
3435 
3436 void MacroAssembler::movbool(Address dst, Register src) {
3437   if(sizeof(bool) == 1)
3438     movb(dst, src);
3439   else if(sizeof(bool) == 2)
3440     movw(dst, src);
3441   else if(sizeof(bool) == 4)
3442     movl(dst, src);
3443   else
3444     // unsupported
3445     ShouldNotReachHere();
3446 }
3447 
3448 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3449   movb(as_Address(dst), src);
3450 }
3451 
3452 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3453   if (reachable(src)) {
3454     movdl(dst, as_Address(src));
3455   } else {
3456     lea(rscratch1, src);
3457     movdl(dst, Address(rscratch1, 0));
3458   }
3459 }
3460 
3461 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3462   if (reachable(src)) {
3463     movq(dst, as_Address(src));
3464   } else {
3465     lea(rscratch1, src);
3466     movq(dst, Address(rscratch1, 0));
3467   }
3468 }
3469 
3470 void MacroAssembler::setvectmask(Register dst, Register src) {
3471   Assembler::movl(dst, 1);
3472   Assembler::shlxl(dst, dst, src);
3473   Assembler::decl(dst);
3474   Assembler::kmovdl(k1, dst);
3475   Assembler::movl(dst, src);
3476 }
3477 
3478 void MacroAssembler::restorevectmask() {
3479   Assembler::knotwl(k1, k0);
3480 }
3481 
3482 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3483   if (reachable(src)) {
3484     if (UseXmmLoadAndClearUpper) {
3485       movsd (dst, as_Address(src));
3486     } else {
3487       movlpd(dst, as_Address(src));
3488     }
3489   } else {
3490     lea(rscratch1, src);
3491     if (UseXmmLoadAndClearUpper) {
3492       movsd (dst, Address(rscratch1, 0));
3493     } else {
3494       movlpd(dst, Address(rscratch1, 0));
3495     }
3496   }
3497 }
3498 
3499 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3500   if (reachable(src)) {
3501     movss(dst, as_Address(src));
3502   } else {
3503     lea(rscratch1, src);
3504     movss(dst, Address(rscratch1, 0));
3505   }
3506 }
3507 
3508 void MacroAssembler::movptr(Register dst, Register src) {
3509   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3510 }
3511 
3512 void MacroAssembler::movptr(Register dst, Address src) {
3513   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3514 }
3515 
3516 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3517 void MacroAssembler::movptr(Register dst, intptr_t src) {
3518   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3519 }
3520 
3521 void MacroAssembler::movptr(Address dst, Register src) {
3522   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3523 }
3524 
3525 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3526   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3527     Assembler::vextractf32x4(dst, src, 0);
3528   } else {
3529     Assembler::movdqu(dst, src);
3530   }
3531 }
3532 
3533 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3534   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3535     Assembler::vinsertf32x4(dst, dst, src, 0);
3536   } else {
3537     Assembler::movdqu(dst, src);
3538   }
3539 }
3540 
3541 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3542   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3543     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3544   } else {
3545     Assembler::movdqu(dst, src);
3546   }
3547 }
3548 
3549 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3550   if (reachable(src)) {
3551     movdqu(dst, as_Address(src));
3552   } else {
3553     lea(scratchReg, src);
3554     movdqu(dst, Address(scratchReg, 0));
3555   }
3556 }
3557 
3558 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3559   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3560     vextractf64x4_low(dst, src);
3561   } else {
3562     Assembler::vmovdqu(dst, src);
3563   }
3564 }
3565 
3566 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3567   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3568     vinsertf64x4_low(dst, src);
3569   } else {
3570     Assembler::vmovdqu(dst, src);
3571   }
3572 }
3573 
3574 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3575   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3576     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3577   }
3578   else {
3579     Assembler::vmovdqu(dst, src);
3580   }
3581 }
3582 
3583 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3584   if (reachable(src)) {
3585     vmovdqu(dst, as_Address(src));
3586   }
3587   else {
3588     lea(rscratch1, src);
3589     vmovdqu(dst, Address(rscratch1, 0));
3590   }
3591 }
3592 
3593 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3594   if (reachable(src)) {
3595     Assembler::movdqa(dst, as_Address(src));
3596   } else {
3597     lea(rscratch1, src);
3598     Assembler::movdqa(dst, Address(rscratch1, 0));
3599   }
3600 }
3601 
3602 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3603   if (reachable(src)) {
3604     Assembler::movsd(dst, as_Address(src));
3605   } else {
3606     lea(rscratch1, src);
3607     Assembler::movsd(dst, Address(rscratch1, 0));
3608   }
3609 }
3610 
3611 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3612   if (reachable(src)) {
3613     Assembler::movss(dst, as_Address(src));
3614   } else {
3615     lea(rscratch1, src);
3616     Assembler::movss(dst, Address(rscratch1, 0));
3617   }
3618 }
3619 
3620 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3621   if (reachable(src)) {
3622     Assembler::mulsd(dst, as_Address(src));
3623   } else {
3624     lea(rscratch1, src);
3625     Assembler::mulsd(dst, Address(rscratch1, 0));
3626   }
3627 }
3628 
3629 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3630   if (reachable(src)) {
3631     Assembler::mulss(dst, as_Address(src));
3632   } else {
3633     lea(rscratch1, src);
3634     Assembler::mulss(dst, Address(rscratch1, 0));
3635   }
3636 }
3637 
3638 void MacroAssembler::null_check(Register reg, int offset) {
3639   if (needs_explicit_null_check(offset)) {
3640     // provoke OS NULL exception if reg = NULL by
3641     // accessing M[reg] w/o changing any (non-CC) registers
3642     // NOTE: cmpl is plenty here to provoke a segv
3643     cmpptr(rax, Address(reg, 0));
3644     // Note: should probably use testl(rax, Address(reg, 0));
3645     //       may be shorter code (however, this version of
3646     //       testl needs to be implemented first)
3647   } else {
3648     // nothing to do, (later) access of M[reg + offset]
3649     // will provoke OS NULL exception if reg = NULL
3650   }
3651 }
3652 
3653 void MacroAssembler::os_breakpoint() {
3654   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3655   // (e.g., MSVC can't call ps() otherwise)
3656   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3657 }
3658 
3659 void MacroAssembler::unimplemented(const char* what) {
3660   const char* buf = NULL;
3661   {
3662     ResourceMark rm;
3663     stringStream ss;
3664     ss.print("unimplemented: %s", what);
3665     buf = code_string(ss.as_string());
3666   }
3667   stop(buf);
3668 }
3669 
3670 #ifdef _LP64
3671 #define XSTATE_BV 0x200
3672 #endif
3673 
3674 void MacroAssembler::pop_CPU_state() {
3675   pop_FPU_state();
3676   pop_IU_state();
3677 }
3678 
3679 void MacroAssembler::pop_FPU_state() {
3680 #ifndef _LP64
3681   frstor(Address(rsp, 0));
3682 #else
3683   fxrstor(Address(rsp, 0));
3684 #endif
3685   addptr(rsp, FPUStateSizeInWords * wordSize);
3686 }
3687 
3688 void MacroAssembler::pop_IU_state() {
3689   popa();
3690   LP64_ONLY(addq(rsp, 8));
3691   popf();
3692 }
3693 
3694 // Save Integer and Float state
3695 // Warning: Stack must be 16 byte aligned (64bit)
3696 void MacroAssembler::push_CPU_state() {
3697   push_IU_state();
3698   push_FPU_state();
3699 }
3700 
3701 void MacroAssembler::push_FPU_state() {
3702   subptr(rsp, FPUStateSizeInWords * wordSize);
3703 #ifndef _LP64
3704   fnsave(Address(rsp, 0));
3705   fwait();
3706 #else
3707   fxsave(Address(rsp, 0));
3708 #endif // LP64
3709 }
3710 
3711 void MacroAssembler::push_IU_state() {
3712   // Push flags first because pusha kills them
3713   pushf();
3714   // Make sure rsp stays 16-byte aligned
3715   LP64_ONLY(subq(rsp, 8));
3716   pusha();
3717 }
3718 
3719 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3720   if (!java_thread->is_valid()) {
3721     java_thread = rdi;
3722     get_thread(java_thread);
3723   }
3724   // we must set sp to zero to clear frame
3725   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3726   if (clear_fp) {
3727     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3728   }
3729 
3730   // Always clear the pc because it could have been set by make_walkable()
3731   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3732 
3733   vzeroupper();
3734 }
3735 
3736 void MacroAssembler::restore_rax(Register tmp) {
3737   if (tmp == noreg) pop(rax);
3738   else if (tmp != rax) mov(rax, tmp);
3739 }
3740 
3741 void MacroAssembler::round_to(Register reg, int modulus) {
3742   addptr(reg, modulus - 1);
3743   andptr(reg, -modulus);
3744 }
3745 
3746 void MacroAssembler::save_rax(Register tmp) {
3747   if (tmp == noreg) push(rax);
3748   else if (tmp != rax) mov(tmp, rax);
3749 }
3750 
3751 // Write serialization page so VM thread can do a pseudo remote membar.
3752 // We use the current thread pointer to calculate a thread specific
3753 // offset to write to within the page. This minimizes bus traffic
3754 // due to cache line collision.
3755 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3756   movl(tmp, thread);
3757   shrl(tmp, os::get_serialize_page_shift_count());
3758   andl(tmp, (os::vm_page_size() - sizeof(int)));
3759 
3760   Address index(noreg, tmp, Address::times_1);
3761   ExternalAddress page(os::get_memory_serialize_page());
3762 
3763   // Size of store must match masking code above
3764   movl(as_Address(ArrayAddress(page, index)), tmp);
3765 }
3766 
3767 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3768   if (SafepointMechanism::uses_thread_local_poll()) {
3769 #ifdef _LP64
3770     assert(thread_reg == r15_thread, "should be");
3771 #else
3772     if (thread_reg == noreg) {
3773       thread_reg = temp_reg;
3774       get_thread(thread_reg);
3775     }
3776 #endif
3777     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3778     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3779   } else {
3780     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3781         SafepointSynchronize::_not_synchronized);
3782     jcc(Assembler::notEqual, slow_path);
3783   }
3784 }
3785 
3786 // Calls to C land
3787 //
3788 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3789 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3790 // has to be reset to 0. This is required to allow proper stack traversal.
3791 void MacroAssembler::set_last_Java_frame(Register java_thread,
3792                                          Register last_java_sp,
3793                                          Register last_java_fp,
3794                                          address  last_java_pc) {
3795   vzeroupper();
3796   // determine java_thread register
3797   if (!java_thread->is_valid()) {
3798     java_thread = rdi;
3799     get_thread(java_thread);
3800   }
3801   // determine last_java_sp register
3802   if (!last_java_sp->is_valid()) {
3803     last_java_sp = rsp;
3804   }
3805 
3806   // last_java_fp is optional
3807 
3808   if (last_java_fp->is_valid()) {
3809     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3810   }
3811 
3812   // last_java_pc is optional
3813 
3814   if (last_java_pc != NULL) {
3815     lea(Address(java_thread,
3816                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3817         InternalAddress(last_java_pc));
3818 
3819   }
3820   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3821 }
3822 
3823 void MacroAssembler::shlptr(Register dst, int imm8) {
3824   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3825 }
3826 
3827 void MacroAssembler::shrptr(Register dst, int imm8) {
3828   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3829 }
3830 
3831 void MacroAssembler::sign_extend_byte(Register reg) {
3832   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3833     movsbl(reg, reg); // movsxb
3834   } else {
3835     shll(reg, 24);
3836     sarl(reg, 24);
3837   }
3838 }
3839 
3840 void MacroAssembler::sign_extend_short(Register reg) {
3841   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3842     movswl(reg, reg); // movsxw
3843   } else {
3844     shll(reg, 16);
3845     sarl(reg, 16);
3846   }
3847 }
3848 
3849 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3850   assert(reachable(src), "Address should be reachable");
3851   testl(dst, as_Address(src));
3852 }
3853 
3854 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3855   int dst_enc = dst->encoding();
3856   int src_enc = src->encoding();
3857   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3858     Assembler::pcmpeqb(dst, src);
3859   } else if ((dst_enc < 16) && (src_enc < 16)) {
3860     Assembler::pcmpeqb(dst, src);
3861   } else if (src_enc < 16) {
3862     subptr(rsp, 64);
3863     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3864     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3865     Assembler::pcmpeqb(xmm0, src);
3866     movdqu(dst, xmm0);
3867     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3868     addptr(rsp, 64);
3869   } else if (dst_enc < 16) {
3870     subptr(rsp, 64);
3871     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3872     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3873     Assembler::pcmpeqb(dst, xmm0);
3874     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3875     addptr(rsp, 64);
3876   } else {
3877     subptr(rsp, 64);
3878     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3879     subptr(rsp, 64);
3880     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3881     movdqu(xmm0, src);
3882     movdqu(xmm1, dst);
3883     Assembler::pcmpeqb(xmm1, xmm0);
3884     movdqu(dst, xmm1);
3885     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3886     addptr(rsp, 64);
3887     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3888     addptr(rsp, 64);
3889   }
3890 }
3891 
3892 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3893   int dst_enc = dst->encoding();
3894   int src_enc = src->encoding();
3895   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3896     Assembler::pcmpeqw(dst, src);
3897   } else if ((dst_enc < 16) && (src_enc < 16)) {
3898     Assembler::pcmpeqw(dst, src);
3899   } else if (src_enc < 16) {
3900     subptr(rsp, 64);
3901     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3902     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3903     Assembler::pcmpeqw(xmm0, src);
3904     movdqu(dst, xmm0);
3905     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3906     addptr(rsp, 64);
3907   } else if (dst_enc < 16) {
3908     subptr(rsp, 64);
3909     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3910     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3911     Assembler::pcmpeqw(dst, xmm0);
3912     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3913     addptr(rsp, 64);
3914   } else {
3915     subptr(rsp, 64);
3916     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3917     subptr(rsp, 64);
3918     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3919     movdqu(xmm0, src);
3920     movdqu(xmm1, dst);
3921     Assembler::pcmpeqw(xmm1, xmm0);
3922     movdqu(dst, xmm1);
3923     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3924     addptr(rsp, 64);
3925     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3926     addptr(rsp, 64);
3927   }
3928 }
3929 
3930 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3931   int dst_enc = dst->encoding();
3932   if (dst_enc < 16) {
3933     Assembler::pcmpestri(dst, src, imm8);
3934   } else {
3935     subptr(rsp, 64);
3936     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3937     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3938     Assembler::pcmpestri(xmm0, src, imm8);
3939     movdqu(dst, xmm0);
3940     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3941     addptr(rsp, 64);
3942   }
3943 }
3944 
3945 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3946   int dst_enc = dst->encoding();
3947   int src_enc = src->encoding();
3948   if ((dst_enc < 16) && (src_enc < 16)) {
3949     Assembler::pcmpestri(dst, src, imm8);
3950   } else if (src_enc < 16) {
3951     subptr(rsp, 64);
3952     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3953     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3954     Assembler::pcmpestri(xmm0, src, imm8);
3955     movdqu(dst, xmm0);
3956     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3957     addptr(rsp, 64);
3958   } else if (dst_enc < 16) {
3959     subptr(rsp, 64);
3960     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3961     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3962     Assembler::pcmpestri(dst, xmm0, imm8);
3963     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3964     addptr(rsp, 64);
3965   } else {
3966     subptr(rsp, 64);
3967     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3968     subptr(rsp, 64);
3969     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3970     movdqu(xmm0, src);
3971     movdqu(xmm1, dst);
3972     Assembler::pcmpestri(xmm1, xmm0, imm8);
3973     movdqu(dst, xmm1);
3974     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3975     addptr(rsp, 64);
3976     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3977     addptr(rsp, 64);
3978   }
3979 }
3980 
3981 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3982   int dst_enc = dst->encoding();
3983   int src_enc = src->encoding();
3984   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3985     Assembler::pmovzxbw(dst, src);
3986   } else if ((dst_enc < 16) && (src_enc < 16)) {
3987     Assembler::pmovzxbw(dst, src);
3988   } else if (src_enc < 16) {
3989     subptr(rsp, 64);
3990     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3991     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3992     Assembler::pmovzxbw(xmm0, src);
3993     movdqu(dst, xmm0);
3994     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3995     addptr(rsp, 64);
3996   } else if (dst_enc < 16) {
3997     subptr(rsp, 64);
3998     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3999     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4000     Assembler::pmovzxbw(dst, xmm0);
4001     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4002     addptr(rsp, 64);
4003   } else {
4004     subptr(rsp, 64);
4005     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4006     subptr(rsp, 64);
4007     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4008     movdqu(xmm0, src);
4009     movdqu(xmm1, dst);
4010     Assembler::pmovzxbw(xmm1, xmm0);
4011     movdqu(dst, xmm1);
4012     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4013     addptr(rsp, 64);
4014     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4015     addptr(rsp, 64);
4016   }
4017 }
4018 
4019 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4020   int dst_enc = dst->encoding();
4021   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4022     Assembler::pmovzxbw(dst, src);
4023   } else if (dst_enc < 16) {
4024     Assembler::pmovzxbw(dst, src);
4025   } else {
4026     subptr(rsp, 64);
4027     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4028     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4029     Assembler::pmovzxbw(xmm0, src);
4030     movdqu(dst, xmm0);
4031     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4032     addptr(rsp, 64);
4033   }
4034 }
4035 
4036 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4037   int src_enc = src->encoding();
4038   if (src_enc < 16) {
4039     Assembler::pmovmskb(dst, src);
4040   } else {
4041     subptr(rsp, 64);
4042     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4043     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4044     Assembler::pmovmskb(dst, xmm0);
4045     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4046     addptr(rsp, 64);
4047   }
4048 }
4049 
4050 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4051   int dst_enc = dst->encoding();
4052   int src_enc = src->encoding();
4053   if ((dst_enc < 16) && (src_enc < 16)) {
4054     Assembler::ptest(dst, src);
4055   } else if (src_enc < 16) {
4056     subptr(rsp, 64);
4057     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4058     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4059     Assembler::ptest(xmm0, src);
4060     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4061     addptr(rsp, 64);
4062   } else if (dst_enc < 16) {
4063     subptr(rsp, 64);
4064     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4065     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4066     Assembler::ptest(dst, xmm0);
4067     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4068     addptr(rsp, 64);
4069   } else {
4070     subptr(rsp, 64);
4071     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4072     subptr(rsp, 64);
4073     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4074     movdqu(xmm0, src);
4075     movdqu(xmm1, dst);
4076     Assembler::ptest(xmm1, xmm0);
4077     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4078     addptr(rsp, 64);
4079     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4080     addptr(rsp, 64);
4081   }
4082 }
4083 
4084 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4085   if (reachable(src)) {
4086     Assembler::sqrtsd(dst, as_Address(src));
4087   } else {
4088     lea(rscratch1, src);
4089     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4090   }
4091 }
4092 
4093 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4094   if (reachable(src)) {
4095     Assembler::sqrtss(dst, as_Address(src));
4096   } else {
4097     lea(rscratch1, src);
4098     Assembler::sqrtss(dst, Address(rscratch1, 0));
4099   }
4100 }
4101 
4102 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4103   if (reachable(src)) {
4104     Assembler::subsd(dst, as_Address(src));
4105   } else {
4106     lea(rscratch1, src);
4107     Assembler::subsd(dst, Address(rscratch1, 0));
4108   }
4109 }
4110 
4111 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4112   if (reachable(src)) {
4113     Assembler::subss(dst, as_Address(src));
4114   } else {
4115     lea(rscratch1, src);
4116     Assembler::subss(dst, Address(rscratch1, 0));
4117   }
4118 }
4119 
4120 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4121   if (reachable(src)) {
4122     Assembler::ucomisd(dst, as_Address(src));
4123   } else {
4124     lea(rscratch1, src);
4125     Assembler::ucomisd(dst, Address(rscratch1, 0));
4126   }
4127 }
4128 
4129 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4130   if (reachable(src)) {
4131     Assembler::ucomiss(dst, as_Address(src));
4132   } else {
4133     lea(rscratch1, src);
4134     Assembler::ucomiss(dst, Address(rscratch1, 0));
4135   }
4136 }
4137 
4138 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4139   // Used in sign-bit flipping with aligned address.
4140   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4141   if (reachable(src)) {
4142     Assembler::xorpd(dst, as_Address(src));
4143   } else {
4144     lea(rscratch1, src);
4145     Assembler::xorpd(dst, Address(rscratch1, 0));
4146   }
4147 }
4148 
4149 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4150   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4151     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4152   }
4153   else {
4154     Assembler::xorpd(dst, src);
4155   }
4156 }
4157 
4158 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4159   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4160     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4161   } else {
4162     Assembler::xorps(dst, src);
4163   }
4164 }
4165 
4166 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4167   // Used in sign-bit flipping with aligned address.
4168   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4169   if (reachable(src)) {
4170     Assembler::xorps(dst, as_Address(src));
4171   } else {
4172     lea(rscratch1, src);
4173     Assembler::xorps(dst, Address(rscratch1, 0));
4174   }
4175 }
4176 
4177 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4178   // Used in sign-bit flipping with aligned address.
4179   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4180   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4181   if (reachable(src)) {
4182     Assembler::pshufb(dst, as_Address(src));
4183   } else {
4184     lea(rscratch1, src);
4185     Assembler::pshufb(dst, Address(rscratch1, 0));
4186   }
4187 }
4188 
4189 // AVX 3-operands instructions
4190 
4191 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4192   if (reachable(src)) {
4193     vaddsd(dst, nds, as_Address(src));
4194   } else {
4195     lea(rscratch1, src);
4196     vaddsd(dst, nds, Address(rscratch1, 0));
4197   }
4198 }
4199 
4200 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4201   if (reachable(src)) {
4202     vaddss(dst, nds, as_Address(src));
4203   } else {
4204     lea(rscratch1, src);
4205     vaddss(dst, nds, Address(rscratch1, 0));
4206   }
4207 }
4208 
4209 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4210   int dst_enc = dst->encoding();
4211   int nds_enc = nds->encoding();
4212   int src_enc = src->encoding();
4213   if ((dst_enc < 16) && (nds_enc < 16)) {
4214     vandps(dst, nds, negate_field, vector_len);
4215   } else if ((src_enc < 16) && (dst_enc < 16)) {
4216     evmovdqul(src, nds, Assembler::AVX_512bit);
4217     vandps(dst, src, negate_field, vector_len);
4218   } else if (src_enc < 16) {
4219     evmovdqul(src, nds, Assembler::AVX_512bit);
4220     vandps(src, src, negate_field, vector_len);
4221     evmovdqul(dst, src, Assembler::AVX_512bit);
4222   } else if (dst_enc < 16) {
4223     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4224     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4225     vandps(dst, xmm0, negate_field, vector_len);
4226     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4227   } else {
4228     if (src_enc != dst_enc) {
4229       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4230       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4231       vandps(xmm0, xmm0, negate_field, vector_len);
4232       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4233       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4234     } else {
4235       subptr(rsp, 64);
4236       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4237       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4238       vandps(xmm0, xmm0, negate_field, vector_len);
4239       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4240       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4241       addptr(rsp, 64);
4242     }
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     evmovdqul(src, nds, Assembler::AVX_512bit);
4254     vandpd(dst, src, negate_field, vector_len);
4255   } else if (src_enc < 16) {
4256     evmovdqul(src, nds, Assembler::AVX_512bit);
4257     vandpd(src, src, negate_field, vector_len);
4258     evmovdqul(dst, src, Assembler::AVX_512bit);
4259   } else if (dst_enc < 16) {
4260     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4261     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4262     vandpd(dst, xmm0, negate_field, vector_len);
4263     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4264   } else {
4265     if (src_enc != dst_enc) {
4266       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4267       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4268       vandpd(xmm0, xmm0, negate_field, vector_len);
4269       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4270       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4271     } else {
4272       subptr(rsp, 64);
4273       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4274       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4275       vandpd(xmm0, xmm0, negate_field, vector_len);
4276       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4277       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4278       addptr(rsp, 64);
4279     }
4280   }
4281 }
4282 
4283 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4284   int dst_enc = dst->encoding();
4285   int nds_enc = nds->encoding();
4286   int src_enc = src->encoding();
4287   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4288     Assembler::vpaddb(dst, nds, src, vector_len);
4289   } else if ((dst_enc < 16) && (src_enc < 16)) {
4290     Assembler::vpaddb(dst, dst, src, vector_len);
4291   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4292     // use nds as scratch for src
4293     evmovdqul(nds, src, Assembler::AVX_512bit);
4294     Assembler::vpaddb(dst, dst, nds, vector_len);
4295   } else if ((src_enc < 16) && (nds_enc < 16)) {
4296     // use nds as scratch for dst
4297     evmovdqul(nds, dst, Assembler::AVX_512bit);
4298     Assembler::vpaddb(nds, nds, src, vector_len);
4299     evmovdqul(dst, nds, Assembler::AVX_512bit);
4300   } else if (dst_enc < 16) {
4301     // use nds as scatch for xmm0 to hold src
4302     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4303     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4304     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4305     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4306   } else {
4307     // worse case scenario, all regs are in the upper bank
4308     subptr(rsp, 64);
4309     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4310     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4311     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4312     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4313     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4314     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4315     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4316     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4317     addptr(rsp, 64);
4318   }
4319 }
4320 
4321 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4322   int dst_enc = dst->encoding();
4323   int nds_enc = nds->encoding();
4324   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4325     Assembler::vpaddb(dst, nds, src, vector_len);
4326   } else if (dst_enc < 16) {
4327     Assembler::vpaddb(dst, dst, src, vector_len);
4328   } else if (nds_enc < 16) {
4329     // implies dst_enc in upper bank with src as scratch
4330     evmovdqul(nds, dst, Assembler::AVX_512bit);
4331     Assembler::vpaddb(nds, nds, src, vector_len);
4332     evmovdqul(dst, nds, Assembler::AVX_512bit);
4333   } else {
4334     // worse case scenario, all regs in upper bank
4335     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4336     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4337     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4338     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4339   }
4340 }
4341 
4342 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4343   int dst_enc = dst->encoding();
4344   int nds_enc = nds->encoding();
4345   int src_enc = src->encoding();
4346   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4347     Assembler::vpaddw(dst, nds, src, vector_len);
4348   } else if ((dst_enc < 16) && (src_enc < 16)) {
4349     Assembler::vpaddw(dst, dst, src, vector_len);
4350   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4351     // use nds as scratch for src
4352     evmovdqul(nds, src, Assembler::AVX_512bit);
4353     Assembler::vpaddw(dst, dst, nds, vector_len);
4354   } else if ((src_enc < 16) && (nds_enc < 16)) {
4355     // use nds as scratch for dst
4356     evmovdqul(nds, dst, Assembler::AVX_512bit);
4357     Assembler::vpaddw(nds, nds, src, vector_len);
4358     evmovdqul(dst, nds, Assembler::AVX_512bit);
4359   } else if (dst_enc < 16) {
4360     // use nds as scatch for xmm0 to hold src
4361     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4362     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4363     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4364     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4365   } else {
4366     // worse case scenario, all regs are in the upper bank
4367     subptr(rsp, 64);
4368     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4369     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4370     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4371     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4372     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4373     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4374     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4375     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4376     addptr(rsp, 64);
4377   }
4378 }
4379 
4380 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4381   int dst_enc = dst->encoding();
4382   int nds_enc = nds->encoding();
4383   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4384     Assembler::vpaddw(dst, nds, src, vector_len);
4385   } else if (dst_enc < 16) {
4386     Assembler::vpaddw(dst, dst, src, vector_len);
4387   } else if (nds_enc < 16) {
4388     // implies dst_enc in upper bank with src as scratch
4389     evmovdqul(nds, dst, Assembler::AVX_512bit);
4390     Assembler::vpaddw(nds, nds, src, vector_len);
4391     evmovdqul(dst, nds, Assembler::AVX_512bit);
4392   } else {
4393     // worse case scenario, all regs in upper bank
4394     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4395     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4396     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4397     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4398   }
4399 }
4400 
4401 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4402   if (reachable(src)) {
4403     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4404   } else {
4405     lea(rscratch1, src);
4406     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4407   }
4408 }
4409 
4410 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4411   int dst_enc = dst->encoding();
4412   int src_enc = src->encoding();
4413   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4414     Assembler::vpbroadcastw(dst, src);
4415   } else if ((dst_enc < 16) && (src_enc < 16)) {
4416     Assembler::vpbroadcastw(dst, src);
4417   } else if (src_enc < 16) {
4418     subptr(rsp, 64);
4419     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4420     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4421     Assembler::vpbroadcastw(xmm0, src);
4422     movdqu(dst, xmm0);
4423     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4424     addptr(rsp, 64);
4425   } else if (dst_enc < 16) {
4426     subptr(rsp, 64);
4427     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4428     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4429     Assembler::vpbroadcastw(dst, xmm0);
4430     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4431     addptr(rsp, 64);
4432   } else {
4433     subptr(rsp, 64);
4434     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4435     subptr(rsp, 64);
4436     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4437     movdqu(xmm0, src);
4438     movdqu(xmm1, dst);
4439     Assembler::vpbroadcastw(xmm1, xmm0);
4440     movdqu(dst, xmm1);
4441     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4442     addptr(rsp, 64);
4443     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4444     addptr(rsp, 64);
4445   }
4446 }
4447 
4448 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4449   int dst_enc = dst->encoding();
4450   int nds_enc = nds->encoding();
4451   int src_enc = src->encoding();
4452   assert(dst_enc == nds_enc, "");
4453   if ((dst_enc < 16) && (src_enc < 16)) {
4454     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4455   } else if (src_enc < 16) {
4456     subptr(rsp, 64);
4457     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4458     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4459     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4460     movdqu(dst, xmm0);
4461     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4462     addptr(rsp, 64);
4463   } else if (dst_enc < 16) {
4464     subptr(rsp, 64);
4465     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4466     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4467     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4468     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4469     addptr(rsp, 64);
4470   } else {
4471     subptr(rsp, 64);
4472     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4473     subptr(rsp, 64);
4474     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4475     movdqu(xmm0, src);
4476     movdqu(xmm1, dst);
4477     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4478     movdqu(dst, xmm1);
4479     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4480     addptr(rsp, 64);
4481     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4482     addptr(rsp, 64);
4483   }
4484 }
4485 
4486 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4487   int dst_enc = dst->encoding();
4488   int nds_enc = nds->encoding();
4489   int src_enc = src->encoding();
4490   assert(dst_enc == nds_enc, "");
4491   if ((dst_enc < 16) && (src_enc < 16)) {
4492     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4493   } else if (src_enc < 16) {
4494     subptr(rsp, 64);
4495     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4496     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4497     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4498     movdqu(dst, xmm0);
4499     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4500     addptr(rsp, 64);
4501   } else if (dst_enc < 16) {
4502     subptr(rsp, 64);
4503     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4504     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4505     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4506     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4507     addptr(rsp, 64);
4508   } else {
4509     subptr(rsp, 64);
4510     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4511     subptr(rsp, 64);
4512     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4513     movdqu(xmm0, src);
4514     movdqu(xmm1, dst);
4515     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4516     movdqu(dst, xmm1);
4517     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4518     addptr(rsp, 64);
4519     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4520     addptr(rsp, 64);
4521   }
4522 }
4523 
4524 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4525   int dst_enc = dst->encoding();
4526   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4527     Assembler::vpmovzxbw(dst, src, vector_len);
4528   } else if (dst_enc < 16) {
4529     Assembler::vpmovzxbw(dst, src, vector_len);
4530   } else {
4531     subptr(rsp, 64);
4532     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4533     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4534     Assembler::vpmovzxbw(xmm0, src, vector_len);
4535     movdqu(dst, xmm0);
4536     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4537     addptr(rsp, 64);
4538   }
4539 }
4540 
4541 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4542   int src_enc = src->encoding();
4543   if (src_enc < 16) {
4544     Assembler::vpmovmskb(dst, src);
4545   } else {
4546     subptr(rsp, 64);
4547     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4548     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4549     Assembler::vpmovmskb(dst, xmm0);
4550     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4551     addptr(rsp, 64);
4552   }
4553 }
4554 
4555 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4556   int dst_enc = dst->encoding();
4557   int nds_enc = nds->encoding();
4558   int src_enc = src->encoding();
4559   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4560     Assembler::vpmullw(dst, nds, src, vector_len);
4561   } else if ((dst_enc < 16) && (src_enc < 16)) {
4562     Assembler::vpmullw(dst, dst, src, vector_len);
4563   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4564     // use nds as scratch for src
4565     evmovdqul(nds, src, Assembler::AVX_512bit);
4566     Assembler::vpmullw(dst, dst, nds, vector_len);
4567   } else if ((src_enc < 16) && (nds_enc < 16)) {
4568     // use nds as scratch for dst
4569     evmovdqul(nds, dst, Assembler::AVX_512bit);
4570     Assembler::vpmullw(nds, nds, src, vector_len);
4571     evmovdqul(dst, nds, Assembler::AVX_512bit);
4572   } else if (dst_enc < 16) {
4573     // use nds as scatch for xmm0 to hold src
4574     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4575     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4576     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4577     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4578   } else {
4579     // worse case scenario, all regs are in the upper bank
4580     subptr(rsp, 64);
4581     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4582     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4583     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4584     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4585     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4586     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4587     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4588     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4589     addptr(rsp, 64);
4590   }
4591 }
4592 
4593 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4594   int dst_enc = dst->encoding();
4595   int nds_enc = nds->encoding();
4596   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4597     Assembler::vpmullw(dst, nds, src, vector_len);
4598   } else if (dst_enc < 16) {
4599     Assembler::vpmullw(dst, dst, src, vector_len);
4600   } else if (nds_enc < 16) {
4601     // implies dst_enc in upper bank with src as scratch
4602     evmovdqul(nds, dst, Assembler::AVX_512bit);
4603     Assembler::vpmullw(nds, nds, src, vector_len);
4604     evmovdqul(dst, nds, Assembler::AVX_512bit);
4605   } else {
4606     // worse case scenario, all regs in upper bank
4607     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4608     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4609     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4610     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4611   }
4612 }
4613 
4614 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4615   int dst_enc = dst->encoding();
4616   int nds_enc = nds->encoding();
4617   int src_enc = src->encoding();
4618   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4619     Assembler::vpsubb(dst, nds, src, vector_len);
4620   } else if ((dst_enc < 16) && (src_enc < 16)) {
4621     Assembler::vpsubb(dst, dst, src, vector_len);
4622   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4623     // use nds as scratch for src
4624     evmovdqul(nds, src, Assembler::AVX_512bit);
4625     Assembler::vpsubb(dst, dst, nds, vector_len);
4626   } else if ((src_enc < 16) && (nds_enc < 16)) {
4627     // use nds as scratch for dst
4628     evmovdqul(nds, dst, Assembler::AVX_512bit);
4629     Assembler::vpsubb(nds, nds, src, vector_len);
4630     evmovdqul(dst, nds, Assembler::AVX_512bit);
4631   } else if (dst_enc < 16) {
4632     // use nds as scatch for xmm0 to hold src
4633     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4634     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4635     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4636     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4637   } else {
4638     // worse case scenario, all regs are in the upper bank
4639     subptr(rsp, 64);
4640     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4641     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4642     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4643     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4644     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4645     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4646     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4647     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4648     addptr(rsp, 64);
4649   }
4650 }
4651 
4652 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4653   int dst_enc = dst->encoding();
4654   int nds_enc = nds->encoding();
4655   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4656     Assembler::vpsubb(dst, nds, src, vector_len);
4657   } else if (dst_enc < 16) {
4658     Assembler::vpsubb(dst, dst, src, vector_len);
4659   } else if (nds_enc < 16) {
4660     // implies dst_enc in upper bank with src as scratch
4661     evmovdqul(nds, dst, Assembler::AVX_512bit);
4662     Assembler::vpsubb(nds, nds, src, vector_len);
4663     evmovdqul(dst, nds, Assembler::AVX_512bit);
4664   } else {
4665     // worse case scenario, all regs in upper bank
4666     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4667     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4668     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4669     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4670   }
4671 }
4672 
4673 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4674   int dst_enc = dst->encoding();
4675   int nds_enc = nds->encoding();
4676   int src_enc = src->encoding();
4677   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4678     Assembler::vpsubw(dst, nds, src, vector_len);
4679   } else if ((dst_enc < 16) && (src_enc < 16)) {
4680     Assembler::vpsubw(dst, dst, src, vector_len);
4681   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4682     // use nds as scratch for src
4683     evmovdqul(nds, src, Assembler::AVX_512bit);
4684     Assembler::vpsubw(dst, dst, nds, vector_len);
4685   } else if ((src_enc < 16) && (nds_enc < 16)) {
4686     // use nds as scratch for dst
4687     evmovdqul(nds, dst, Assembler::AVX_512bit);
4688     Assembler::vpsubw(nds, nds, src, vector_len);
4689     evmovdqul(dst, nds, Assembler::AVX_512bit);
4690   } else if (dst_enc < 16) {
4691     // use nds as scatch for xmm0 to hold src
4692     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4693     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4694     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4695     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4696   } else {
4697     // worse case scenario, all regs are in the upper bank
4698     subptr(rsp, 64);
4699     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4700     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4701     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4702     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4703     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4704     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4705     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4706     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4707     addptr(rsp, 64);
4708   }
4709 }
4710 
4711 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4712   int dst_enc = dst->encoding();
4713   int nds_enc = nds->encoding();
4714   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4715     Assembler::vpsubw(dst, nds, src, vector_len);
4716   } else if (dst_enc < 16) {
4717     Assembler::vpsubw(dst, dst, src, vector_len);
4718   } else if (nds_enc < 16) {
4719     // implies dst_enc in upper bank with src as scratch
4720     evmovdqul(nds, dst, Assembler::AVX_512bit);
4721     Assembler::vpsubw(nds, nds, src, vector_len);
4722     evmovdqul(dst, nds, Assembler::AVX_512bit);
4723   } else {
4724     // worse case scenario, all regs in upper bank
4725     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4726     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4727     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4728     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4729   }
4730 }
4731 
4732 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4733   int dst_enc = dst->encoding();
4734   int nds_enc = nds->encoding();
4735   int shift_enc = shift->encoding();
4736   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4737     Assembler::vpsraw(dst, nds, shift, vector_len);
4738   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4739     Assembler::vpsraw(dst, dst, shift, vector_len);
4740   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4741     // use nds_enc as scratch with shift
4742     evmovdqul(nds, shift, Assembler::AVX_512bit);
4743     Assembler::vpsraw(dst, dst, nds, vector_len);
4744   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4745     // use nds as scratch with dst
4746     evmovdqul(nds, dst, Assembler::AVX_512bit);
4747     Assembler::vpsraw(nds, nds, shift, vector_len);
4748     evmovdqul(dst, nds, Assembler::AVX_512bit);
4749   } else if (dst_enc < 16) {
4750     // use nds to save a copy of xmm0 and hold shift
4751     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4752     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4753     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4754     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4755   } else if (nds_enc < 16) {
4756     // use nds as dest as temps
4757     evmovdqul(nds, dst, Assembler::AVX_512bit);
4758     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4759     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4760     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4761     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4762     evmovdqul(dst, nds, Assembler::AVX_512bit);
4763   } else {
4764     // worse case scenario, all regs are in the upper bank
4765     subptr(rsp, 64);
4766     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4767     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4768     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4769     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4770     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4771     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4772     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4773     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4774     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4775     addptr(rsp, 64);
4776   }
4777 }
4778 
4779 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4780   int dst_enc = dst->encoding();
4781   int nds_enc = nds->encoding();
4782   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4783     Assembler::vpsraw(dst, nds, shift, vector_len);
4784   } else if (dst_enc < 16) {
4785     Assembler::vpsraw(dst, dst, shift, vector_len);
4786   } else if (nds_enc < 16) {
4787     // use nds as scratch
4788     evmovdqul(nds, dst, Assembler::AVX_512bit);
4789     Assembler::vpsraw(nds, nds, shift, vector_len);
4790     evmovdqul(dst, nds, Assembler::AVX_512bit);
4791   } else {
4792     // use nds as scratch for xmm0
4793     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4794     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4795     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4796     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4797   }
4798 }
4799 
4800 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4801   int dst_enc = dst->encoding();
4802   int nds_enc = nds->encoding();
4803   int shift_enc = shift->encoding();
4804   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4805     Assembler::vpsrlw(dst, nds, shift, vector_len);
4806   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4807     Assembler::vpsrlw(dst, dst, shift, vector_len);
4808   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4809     // use nds_enc as scratch with shift
4810     evmovdqul(nds, shift, Assembler::AVX_512bit);
4811     Assembler::vpsrlw(dst, dst, nds, vector_len);
4812   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4813     // use nds as scratch with dst
4814     evmovdqul(nds, dst, Assembler::AVX_512bit);
4815     Assembler::vpsrlw(nds, nds, shift, vector_len);
4816     evmovdqul(dst, nds, Assembler::AVX_512bit);
4817   } else if (dst_enc < 16) {
4818     // use nds to save a copy of xmm0 and hold shift
4819     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4820     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4821     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4822     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4823   } else if (nds_enc < 16) {
4824     // use nds as dest as temps
4825     evmovdqul(nds, dst, Assembler::AVX_512bit);
4826     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4827     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4828     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4829     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4830     evmovdqul(dst, nds, Assembler::AVX_512bit);
4831   } else {
4832     // worse case scenario, all regs are in the upper bank
4833     subptr(rsp, 64);
4834     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4835     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4836     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4837     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4838     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4839     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4840     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4841     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4842     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4843     addptr(rsp, 64);
4844   }
4845 }
4846 
4847 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4848   int dst_enc = dst->encoding();
4849   int nds_enc = nds->encoding();
4850   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4851     Assembler::vpsrlw(dst, nds, shift, vector_len);
4852   } else if (dst_enc < 16) {
4853     Assembler::vpsrlw(dst, dst, shift, vector_len);
4854   } else if (nds_enc < 16) {
4855     // use nds as scratch
4856     evmovdqul(nds, dst, Assembler::AVX_512bit);
4857     Assembler::vpsrlw(nds, nds, shift, vector_len);
4858     evmovdqul(dst, nds, Assembler::AVX_512bit);
4859   } else {
4860     // use nds as scratch for xmm0
4861     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4862     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4863     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4864     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4865   }
4866 }
4867 
4868 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4869   int dst_enc = dst->encoding();
4870   int nds_enc = nds->encoding();
4871   int shift_enc = shift->encoding();
4872   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4873     Assembler::vpsllw(dst, nds, shift, vector_len);
4874   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4875     Assembler::vpsllw(dst, dst, shift, vector_len);
4876   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4877     // use nds_enc as scratch with shift
4878     evmovdqul(nds, shift, Assembler::AVX_512bit);
4879     Assembler::vpsllw(dst, dst, nds, vector_len);
4880   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4881     // use nds as scratch with dst
4882     evmovdqul(nds, dst, Assembler::AVX_512bit);
4883     Assembler::vpsllw(nds, nds, shift, vector_len);
4884     evmovdqul(dst, nds, Assembler::AVX_512bit);
4885   } else if (dst_enc < 16) {
4886     // use nds to save a copy of xmm0 and hold shift
4887     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4888     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4889     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4890     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4891   } else if (nds_enc < 16) {
4892     // use nds as dest as temps
4893     evmovdqul(nds, dst, Assembler::AVX_512bit);
4894     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4895     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4896     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4897     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4898     evmovdqul(dst, nds, Assembler::AVX_512bit);
4899   } else {
4900     // worse case scenario, all regs are in the upper bank
4901     subptr(rsp, 64);
4902     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4903     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4904     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4905     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4906     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4907     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4908     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4909     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4910     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4911     addptr(rsp, 64);
4912   }
4913 }
4914 
4915 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4916   int dst_enc = dst->encoding();
4917   int nds_enc = nds->encoding();
4918   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4919     Assembler::vpsllw(dst, nds, shift, vector_len);
4920   } else if (dst_enc < 16) {
4921     Assembler::vpsllw(dst, dst, shift, vector_len);
4922   } else if (nds_enc < 16) {
4923     // use nds as scratch
4924     evmovdqul(nds, dst, Assembler::AVX_512bit);
4925     Assembler::vpsllw(nds, nds, shift, vector_len);
4926     evmovdqul(dst, nds, Assembler::AVX_512bit);
4927   } else {
4928     // use nds as scratch for xmm0
4929     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4930     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4931     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4932     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4933   }
4934 }
4935 
4936 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4937   int dst_enc = dst->encoding();
4938   int src_enc = src->encoding();
4939   if ((dst_enc < 16) && (src_enc < 16)) {
4940     Assembler::vptest(dst, src);
4941   } else if (src_enc < 16) {
4942     subptr(rsp, 64);
4943     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4944     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4945     Assembler::vptest(xmm0, src);
4946     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4947     addptr(rsp, 64);
4948   } else if (dst_enc < 16) {
4949     subptr(rsp, 64);
4950     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4951     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4952     Assembler::vptest(dst, xmm0);
4953     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4954     addptr(rsp, 64);
4955   } else {
4956     subptr(rsp, 64);
4957     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4958     subptr(rsp, 64);
4959     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4960     movdqu(xmm0, src);
4961     movdqu(xmm1, dst);
4962     Assembler::vptest(xmm1, xmm0);
4963     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4964     addptr(rsp, 64);
4965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4966     addptr(rsp, 64);
4967   }
4968 }
4969 
4970 // This instruction exists within macros, ergo we cannot control its input
4971 // when emitted through those patterns.
4972 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4973   if (VM_Version::supports_avx512nobw()) {
4974     int dst_enc = dst->encoding();
4975     int src_enc = src->encoding();
4976     if (dst_enc == src_enc) {
4977       if (dst_enc < 16) {
4978         Assembler::punpcklbw(dst, src);
4979       } else {
4980         subptr(rsp, 64);
4981         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4982         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4983         Assembler::punpcklbw(xmm0, xmm0);
4984         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4985         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4986         addptr(rsp, 64);
4987       }
4988     } else {
4989       if ((src_enc < 16) && (dst_enc < 16)) {
4990         Assembler::punpcklbw(dst, src);
4991       } else if (src_enc < 16) {
4992         subptr(rsp, 64);
4993         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4994         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4995         Assembler::punpcklbw(xmm0, src);
4996         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4997         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4998         addptr(rsp, 64);
4999       } else if (dst_enc < 16) {
5000         subptr(rsp, 64);
5001         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5002         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5003         Assembler::punpcklbw(dst, xmm0);
5004         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5005         addptr(rsp, 64);
5006       } else {
5007         subptr(rsp, 64);
5008         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5009         subptr(rsp, 64);
5010         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5011         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5012         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5013         Assembler::punpcklbw(xmm0, xmm1);
5014         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5015         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5016         addptr(rsp, 64);
5017         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5018         addptr(rsp, 64);
5019       }
5020     }
5021   } else {
5022     Assembler::punpcklbw(dst, src);
5023   }
5024 }
5025 
5026 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5027   if (VM_Version::supports_avx512vl()) {
5028     Assembler::pshufd(dst, src, mode);
5029   } else {
5030     int dst_enc = dst->encoding();
5031     if (dst_enc < 16) {
5032       Assembler::pshufd(dst, src, mode);
5033     } else {
5034       subptr(rsp, 64);
5035       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5036       Assembler::pshufd(xmm0, src, mode);
5037       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5038       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5039       addptr(rsp, 64);
5040     }
5041   }
5042 }
5043 
5044 // This instruction exists within macros, ergo we cannot control its input
5045 // when emitted through those patterns.
5046 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5047   if (VM_Version::supports_avx512nobw()) {
5048     int dst_enc = dst->encoding();
5049     int src_enc = src->encoding();
5050     if (dst_enc == src_enc) {
5051       if (dst_enc < 16) {
5052         Assembler::pshuflw(dst, src, mode);
5053       } else {
5054         subptr(rsp, 64);
5055         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5056         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5057         Assembler::pshuflw(xmm0, xmm0, mode);
5058         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5059         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5060         addptr(rsp, 64);
5061       }
5062     } else {
5063       if ((src_enc < 16) && (dst_enc < 16)) {
5064         Assembler::pshuflw(dst, src, mode);
5065       } else if (src_enc < 16) {
5066         subptr(rsp, 64);
5067         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5068         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5069         Assembler::pshuflw(xmm0, src, mode);
5070         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5071         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5072         addptr(rsp, 64);
5073       } else if (dst_enc < 16) {
5074         subptr(rsp, 64);
5075         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5076         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5077         Assembler::pshuflw(dst, xmm0, mode);
5078         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5079         addptr(rsp, 64);
5080       } else {
5081         subptr(rsp, 64);
5082         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5083         subptr(rsp, 64);
5084         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5085         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5086         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5087         Assembler::pshuflw(xmm0, xmm1, mode);
5088         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5089         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5090         addptr(rsp, 64);
5091         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5092         addptr(rsp, 64);
5093       }
5094     }
5095   } else {
5096     Assembler::pshuflw(dst, src, mode);
5097   }
5098 }
5099 
5100 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5101   if (reachable(src)) {
5102     vandpd(dst, nds, as_Address(src), vector_len);
5103   } else {
5104     lea(rscratch1, src);
5105     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5106   }
5107 }
5108 
5109 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5110   if (reachable(src)) {
5111     vandps(dst, nds, as_Address(src), vector_len);
5112   } else {
5113     lea(rscratch1, src);
5114     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5115   }
5116 }
5117 
5118 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5119   if (reachable(src)) {
5120     vdivsd(dst, nds, as_Address(src));
5121   } else {
5122     lea(rscratch1, src);
5123     vdivsd(dst, nds, Address(rscratch1, 0));
5124   }
5125 }
5126 
5127 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5128   if (reachable(src)) {
5129     vdivss(dst, nds, as_Address(src));
5130   } else {
5131     lea(rscratch1, src);
5132     vdivss(dst, nds, Address(rscratch1, 0));
5133   }
5134 }
5135 
5136 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5137   if (reachable(src)) {
5138     vmulsd(dst, nds, as_Address(src));
5139   } else {
5140     lea(rscratch1, src);
5141     vmulsd(dst, nds, Address(rscratch1, 0));
5142   }
5143 }
5144 
5145 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5146   if (reachable(src)) {
5147     vmulss(dst, nds, as_Address(src));
5148   } else {
5149     lea(rscratch1, src);
5150     vmulss(dst, nds, Address(rscratch1, 0));
5151   }
5152 }
5153 
5154 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5155   if (reachable(src)) {
5156     vsubsd(dst, nds, as_Address(src));
5157   } else {
5158     lea(rscratch1, src);
5159     vsubsd(dst, nds, Address(rscratch1, 0));
5160   }
5161 }
5162 
5163 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5164   if (reachable(src)) {
5165     vsubss(dst, nds, as_Address(src));
5166   } else {
5167     lea(rscratch1, src);
5168     vsubss(dst, nds, Address(rscratch1, 0));
5169   }
5170 }
5171 
5172 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5173   int nds_enc = nds->encoding();
5174   int dst_enc = dst->encoding();
5175   bool dst_upper_bank = (dst_enc > 15);
5176   bool nds_upper_bank = (nds_enc > 15);
5177   if (VM_Version::supports_avx512novl() &&
5178       (nds_upper_bank || dst_upper_bank)) {
5179     if (dst_upper_bank) {
5180       subptr(rsp, 64);
5181       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5182       movflt(xmm0, nds);
5183       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5184       movflt(dst, xmm0);
5185       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5186       addptr(rsp, 64);
5187     } else {
5188       movflt(dst, nds);
5189       vxorps(dst, dst, src, Assembler::AVX_128bit);
5190     }
5191   } else {
5192     vxorps(dst, nds, src, Assembler::AVX_128bit);
5193   }
5194 }
5195 
5196 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5197   int nds_enc = nds->encoding();
5198   int dst_enc = dst->encoding();
5199   bool dst_upper_bank = (dst_enc > 15);
5200   bool nds_upper_bank = (nds_enc > 15);
5201   if (VM_Version::supports_avx512novl() &&
5202       (nds_upper_bank || dst_upper_bank)) {
5203     if (dst_upper_bank) {
5204       subptr(rsp, 64);
5205       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5206       movdbl(xmm0, nds);
5207       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5208       movdbl(dst, xmm0);
5209       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5210       addptr(rsp, 64);
5211     } else {
5212       movdbl(dst, nds);
5213       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5214     }
5215   } else {
5216     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5217   }
5218 }
5219 
5220 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5221   if (reachable(src)) {
5222     vxorpd(dst, nds, as_Address(src), vector_len);
5223   } else {
5224     lea(rscratch1, src);
5225     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5226   }
5227 }
5228 
5229 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5230   if (reachable(src)) {
5231     vxorps(dst, nds, as_Address(src), vector_len);
5232   } else {
5233     lea(rscratch1, src);
5234     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5235   }
5236 }
5237 
5238 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5239   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5240   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5241   // The inverted mask is sign-extended
5242   andptr(possibly_jweak, inverted_jweak_mask);
5243 }
5244 
5245 void MacroAssembler::resolve_jobject(Register value,
5246                                      Register thread,
5247                                      Register tmp) {
5248   assert_different_registers(value, thread, tmp);
5249   Label done, not_weak;
5250   testptr(value, value);
5251   jcc(Assembler::zero, done);                // Use NULL as-is.
5252   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5253   jcc(Assembler::zero, not_weak);
5254   // Resolve jweak.
5255   access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
5256                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
5257   verify_oop(value);
5258   jmp(done);
5259   bind(not_weak);
5260   // Resolve (untagged) jobject.
5261   access_load_at(T_OBJECT, IN_ROOT | IN_CONCURRENT_ROOT,
5262                  value, Address(value, 0), tmp, thread);
5263   verify_oop(value);
5264   bind(done);
5265 }
5266 
5267 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5268   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5269 }
5270 
5271 // Force generation of a 4 byte immediate value even if it fits into 8bit
5272 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5273   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5274 }
5275 
5276 void MacroAssembler::subptr(Register dst, Register src) {
5277   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5278 }
5279 
5280 // C++ bool manipulation
5281 void MacroAssembler::testbool(Register dst) {
5282   if(sizeof(bool) == 1)
5283     testb(dst, 0xff);
5284   else if(sizeof(bool) == 2) {
5285     // testw implementation needed for two byte bools
5286     ShouldNotReachHere();
5287   } else if(sizeof(bool) == 4)
5288     testl(dst, dst);
5289   else
5290     // unsupported
5291     ShouldNotReachHere();
5292 }
5293 
5294 void MacroAssembler::testptr(Register dst, Register src) {
5295   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5296 }
5297 
5298 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5299 void MacroAssembler::tlab_allocate(Register obj,
5300                                    Register var_size_in_bytes,
5301                                    int con_size_in_bytes,
5302                                    Register t1,
5303                                    Register t2,
5304                                    Label& slow_case) {
5305   assert_different_registers(obj, t1, t2);
5306   assert_different_registers(obj, var_size_in_bytes, t1);
5307   Register end = t2;
5308   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5309 
5310   verify_tlab();
5311 
5312   NOT_LP64(get_thread(thread));
5313 
5314   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5315   if (var_size_in_bytes == noreg) {
5316     lea(end, Address(obj, con_size_in_bytes));
5317   } else {
5318     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5319   }
5320   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5321   jcc(Assembler::above, slow_case);
5322 
5323   // update the tlab top pointer
5324   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5325 
5326   // recover var_size_in_bytes if necessary
5327   if (var_size_in_bytes == end) {
5328     subptr(var_size_in_bytes, obj);
5329   }
5330   verify_tlab();
5331 }
5332 
5333 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5334 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5335   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5336   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5337   Label done;
5338 
5339   testptr(length_in_bytes, length_in_bytes);
5340   jcc(Assembler::zero, done);
5341 
5342   // initialize topmost word, divide index by 2, check if odd and test if zero
5343   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5344 #ifdef ASSERT
5345   {
5346     Label L;
5347     testptr(length_in_bytes, BytesPerWord - 1);
5348     jcc(Assembler::zero, L);
5349     stop("length must be a multiple of BytesPerWord");
5350     bind(L);
5351   }
5352 #endif
5353   Register index = length_in_bytes;
5354   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5355   if (UseIncDec) {
5356     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5357   } else {
5358     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5359     shrptr(index, 1);
5360   }
5361 #ifndef _LP64
5362   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5363   {
5364     Label even;
5365     // note: if index was a multiple of 8, then it cannot
5366     //       be 0 now otherwise it must have been 0 before
5367     //       => if it is even, we don't need to check for 0 again
5368     jcc(Assembler::carryClear, even);
5369     // clear topmost word (no jump would be needed if conditional assignment worked here)
5370     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5371     // index could be 0 now, must check again
5372     jcc(Assembler::zero, done);
5373     bind(even);
5374   }
5375 #endif // !_LP64
5376   // initialize remaining object fields: index is a multiple of 2 now
5377   {
5378     Label loop;
5379     bind(loop);
5380     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5381     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5382     decrement(index);
5383     jcc(Assembler::notZero, loop);
5384   }
5385 
5386   bind(done);
5387 }
5388 
5389 void MacroAssembler::incr_allocated_bytes(Register thread,
5390                                           Register var_size_in_bytes,
5391                                           int con_size_in_bytes,
5392                                           Register t1) {
5393   if (!thread->is_valid()) {
5394 #ifdef _LP64
5395     thread = r15_thread;
5396 #else
5397     assert(t1->is_valid(), "need temp reg");
5398     thread = t1;
5399     get_thread(thread);
5400 #endif
5401   }
5402 
5403 #ifdef _LP64
5404   if (var_size_in_bytes->is_valid()) {
5405     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5406   } else {
5407     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5408   }
5409 #else
5410   if (var_size_in_bytes->is_valid()) {
5411     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5412   } else {
5413     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5414   }
5415   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5416 #endif
5417 }
5418 
5419 // Look up the method for a megamorphic invokeinterface call.
5420 // The target method is determined by <intf_klass, itable_index>.
5421 // The receiver klass is in recv_klass.
5422 // On success, the result will be in method_result, and execution falls through.
5423 // On failure, execution transfers to the given label.
5424 void MacroAssembler::lookup_interface_method(Register recv_klass,
5425                                              Register intf_klass,
5426                                              RegisterOrConstant itable_index,
5427                                              Register method_result,
5428                                              Register scan_temp,
5429                                              Label& L_no_such_interface,
5430                                              bool return_method) {
5431   assert_different_registers(recv_klass, intf_klass, scan_temp);
5432   assert_different_registers(method_result, intf_klass, scan_temp);
5433   assert(recv_klass != method_result || !return_method,
5434          "recv_klass can be destroyed when method isn't needed");
5435 
5436   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5437          "caller must use same register for non-constant itable index as for method");
5438 
5439   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5440   int vtable_base = in_bytes(Klass::vtable_start_offset());
5441   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5442   int scan_step   = itableOffsetEntry::size() * wordSize;
5443   int vte_size    = vtableEntry::size_in_bytes();
5444   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5445   assert(vte_size == wordSize, "else adjust times_vte_scale");
5446 
5447   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5448 
5449   // %%% Could store the aligned, prescaled offset in the klassoop.
5450   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5451 
5452   if (return_method) {
5453     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5454     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5455     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5456   }
5457 
5458   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5459   //   if (scan->interface() == intf) {
5460   //     result = (klass + scan->offset() + itable_index);
5461   //   }
5462   // }
5463   Label search, found_method;
5464 
5465   for (int peel = 1; peel >= 0; peel--) {
5466     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5467     cmpptr(intf_klass, method_result);
5468 
5469     if (peel) {
5470       jccb(Assembler::equal, found_method);
5471     } else {
5472       jccb(Assembler::notEqual, search);
5473       // (invert the test to fall through to found_method...)
5474     }
5475 
5476     if (!peel)  break;
5477 
5478     bind(search);
5479 
5480     // Check that the previous entry is non-null.  A null entry means that
5481     // the receiver class doesn't implement the interface, and wasn't the
5482     // same as when the caller was compiled.
5483     testptr(method_result, method_result);
5484     jcc(Assembler::zero, L_no_such_interface);
5485     addptr(scan_temp, scan_step);
5486   }
5487 
5488   bind(found_method);
5489 
5490   if (return_method) {
5491     // Got a hit.
5492     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5493     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5494   }
5495 }
5496 
5497 
5498 // virtual method calling
5499 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5500                                            RegisterOrConstant vtable_index,
5501                                            Register method_result) {
5502   const int base = in_bytes(Klass::vtable_start_offset());
5503   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5504   Address vtable_entry_addr(recv_klass,
5505                             vtable_index, Address::times_ptr,
5506                             base + vtableEntry::method_offset_in_bytes());
5507   movptr(method_result, vtable_entry_addr);
5508 }
5509 
5510 
5511 void MacroAssembler::check_klass_subtype(Register sub_klass,
5512                            Register super_klass,
5513                            Register temp_reg,
5514                            Label& L_success) {
5515   Label L_failure;
5516   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5517   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5518   bind(L_failure);
5519 }
5520 
5521 
5522 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5523                                                    Register super_klass,
5524                                                    Register temp_reg,
5525                                                    Label* L_success,
5526                                                    Label* L_failure,
5527                                                    Label* L_slow_path,
5528                                         RegisterOrConstant super_check_offset) {
5529   assert_different_registers(sub_klass, super_klass, temp_reg);
5530   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5531   if (super_check_offset.is_register()) {
5532     assert_different_registers(sub_klass, super_klass,
5533                                super_check_offset.as_register());
5534   } else if (must_load_sco) {
5535     assert(temp_reg != noreg, "supply either a temp or a register offset");
5536   }
5537 
5538   Label L_fallthrough;
5539   int label_nulls = 0;
5540   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5541   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5542   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5543   assert(label_nulls <= 1, "at most one NULL in the batch");
5544 
5545   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5546   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5547   Address super_check_offset_addr(super_klass, sco_offset);
5548 
5549   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5550   // range of a jccb.  If this routine grows larger, reconsider at
5551   // least some of these.
5552 #define local_jcc(assembler_cond, label)                                \
5553   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5554   else                             jcc( assembler_cond, label) /*omit semi*/
5555 
5556   // Hacked jmp, which may only be used just before L_fallthrough.
5557 #define final_jmp(label)                                                \
5558   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5559   else                            jmp(label)                /*omit semi*/
5560 
5561   // If the pointers are equal, we are done (e.g., String[] elements).
5562   // This self-check enables sharing of secondary supertype arrays among
5563   // non-primary types such as array-of-interface.  Otherwise, each such
5564   // type would need its own customized SSA.
5565   // We move this check to the front of the fast path because many
5566   // type checks are in fact trivially successful in this manner,
5567   // so we get a nicely predicted branch right at the start of the check.
5568   cmpptr(sub_klass, super_klass);
5569   local_jcc(Assembler::equal, *L_success);
5570 
5571   // Check the supertype display:
5572   if (must_load_sco) {
5573     // Positive movl does right thing on LP64.
5574     movl(temp_reg, super_check_offset_addr);
5575     super_check_offset = RegisterOrConstant(temp_reg);
5576   }
5577   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5578   cmpptr(super_klass, super_check_addr); // load displayed supertype
5579 
5580   // This check has worked decisively for primary supers.
5581   // Secondary supers are sought in the super_cache ('super_cache_addr').
5582   // (Secondary supers are interfaces and very deeply nested subtypes.)
5583   // This works in the same check above because of a tricky aliasing
5584   // between the super_cache and the primary super display elements.
5585   // (The 'super_check_addr' can address either, as the case requires.)
5586   // Note that the cache is updated below if it does not help us find
5587   // what we need immediately.
5588   // So if it was a primary super, we can just fail immediately.
5589   // Otherwise, it's the slow path for us (no success at this point).
5590 
5591   if (super_check_offset.is_register()) {
5592     local_jcc(Assembler::equal, *L_success);
5593     cmpl(super_check_offset.as_register(), sc_offset);
5594     if (L_failure == &L_fallthrough) {
5595       local_jcc(Assembler::equal, *L_slow_path);
5596     } else {
5597       local_jcc(Assembler::notEqual, *L_failure);
5598       final_jmp(*L_slow_path);
5599     }
5600   } else if (super_check_offset.as_constant() == sc_offset) {
5601     // Need a slow path; fast failure is impossible.
5602     if (L_slow_path == &L_fallthrough) {
5603       local_jcc(Assembler::equal, *L_success);
5604     } else {
5605       local_jcc(Assembler::notEqual, *L_slow_path);
5606       final_jmp(*L_success);
5607     }
5608   } else {
5609     // No slow path; it's a fast decision.
5610     if (L_failure == &L_fallthrough) {
5611       local_jcc(Assembler::equal, *L_success);
5612     } else {
5613       local_jcc(Assembler::notEqual, *L_failure);
5614       final_jmp(*L_success);
5615     }
5616   }
5617 
5618   bind(L_fallthrough);
5619 
5620 #undef local_jcc
5621 #undef final_jmp
5622 }
5623 
5624 
5625 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5626                                                    Register super_klass,
5627                                                    Register temp_reg,
5628                                                    Register temp2_reg,
5629                                                    Label* L_success,
5630                                                    Label* L_failure,
5631                                                    bool set_cond_codes) {
5632   assert_different_registers(sub_klass, super_klass, temp_reg);
5633   if (temp2_reg != noreg)
5634     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5635 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5636 
5637   Label L_fallthrough;
5638   int label_nulls = 0;
5639   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5640   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5641   assert(label_nulls <= 1, "at most one NULL in the batch");
5642 
5643   // a couple of useful fields in sub_klass:
5644   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5645   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5646   Address secondary_supers_addr(sub_klass, ss_offset);
5647   Address super_cache_addr(     sub_klass, sc_offset);
5648 
5649   // Do a linear scan of the secondary super-klass chain.
5650   // This code is rarely used, so simplicity is a virtue here.
5651   // The repne_scan instruction uses fixed registers, which we must spill.
5652   // Don't worry too much about pre-existing connections with the input regs.
5653 
5654   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5655   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5656 
5657   // Get super_klass value into rax (even if it was in rdi or rcx).
5658   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5659   if (super_klass != rax || UseCompressedOops) {
5660     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5661     mov(rax, super_klass);
5662   }
5663   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5664   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5665 
5666 #ifndef PRODUCT
5667   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5668   ExternalAddress pst_counter_addr((address) pst_counter);
5669   NOT_LP64(  incrementl(pst_counter_addr) );
5670   LP64_ONLY( lea(rcx, pst_counter_addr) );
5671   LP64_ONLY( incrementl(Address(rcx, 0)) );
5672 #endif //PRODUCT
5673 
5674   // We will consult the secondary-super array.
5675   movptr(rdi, secondary_supers_addr);
5676   // Load the array length.  (Positive movl does right thing on LP64.)
5677   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5678   // Skip to start of data.
5679   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5680 
5681   // Scan RCX words at [RDI] for an occurrence of RAX.
5682   // Set NZ/Z based on last compare.
5683   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5684   // not change flags (only scas instruction which is repeated sets flags).
5685   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5686 
5687     testptr(rax,rax); // Set Z = 0
5688     repne_scan();
5689 
5690   // Unspill the temp. registers:
5691   if (pushed_rdi)  pop(rdi);
5692   if (pushed_rcx)  pop(rcx);
5693   if (pushed_rax)  pop(rax);
5694 
5695   if (set_cond_codes) {
5696     // Special hack for the AD files:  rdi is guaranteed non-zero.
5697     assert(!pushed_rdi, "rdi must be left non-NULL");
5698     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5699   }
5700 
5701   if (L_failure == &L_fallthrough)
5702         jccb(Assembler::notEqual, *L_failure);
5703   else  jcc(Assembler::notEqual, *L_failure);
5704 
5705   // Success.  Cache the super we found and proceed in triumph.
5706   movptr(super_cache_addr, super_klass);
5707 
5708   if (L_success != &L_fallthrough) {
5709     jmp(*L_success);
5710   }
5711 
5712 #undef IS_A_TEMP
5713 
5714   bind(L_fallthrough);
5715 }
5716 
5717 
5718 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5719   if (VM_Version::supports_cmov()) {
5720     cmovl(cc, dst, src);
5721   } else {
5722     Label L;
5723     jccb(negate_condition(cc), L);
5724     movl(dst, src);
5725     bind(L);
5726   }
5727 }
5728 
5729 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5730   if (VM_Version::supports_cmov()) {
5731     cmovl(cc, dst, src);
5732   } else {
5733     Label L;
5734     jccb(negate_condition(cc), L);
5735     movl(dst, src);
5736     bind(L);
5737   }
5738 }
5739 
5740 void MacroAssembler::verify_oop(Register reg, const char* s) {
5741   if (!VerifyOops) return;
5742 
5743   // Pass register number to verify_oop_subroutine
5744   const char* b = NULL;
5745   {
5746     ResourceMark rm;
5747     stringStream ss;
5748     ss.print("verify_oop: %s: %s", reg->name(), s);
5749     b = code_string(ss.as_string());
5750   }
5751   BLOCK_COMMENT("verify_oop {");
5752 #ifdef _LP64
5753   push(rscratch1);                    // save r10, trashed by movptr()
5754 #endif
5755   push(rax);                          // save rax,
5756   push(reg);                          // pass register argument
5757   ExternalAddress buffer((address) b);
5758   // avoid using pushptr, as it modifies scratch registers
5759   // and our contract is not to modify anything
5760   movptr(rax, buffer.addr());
5761   push(rax);
5762   // call indirectly to solve generation ordering problem
5763   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5764   call(rax);
5765   // Caller pops the arguments (oop, message) and restores rax, r10
5766   BLOCK_COMMENT("} verify_oop");
5767 }
5768 
5769 
5770 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5771                                                       Register tmp,
5772                                                       int offset) {
5773   intptr_t value = *delayed_value_addr;
5774   if (value != 0)
5775     return RegisterOrConstant(value + offset);
5776 
5777   // load indirectly to solve generation ordering problem
5778   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5779 
5780 #ifdef ASSERT
5781   { Label L;
5782     testptr(tmp, tmp);
5783     if (WizardMode) {
5784       const char* buf = NULL;
5785       {
5786         ResourceMark rm;
5787         stringStream ss;
5788         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5789         buf = code_string(ss.as_string());
5790       }
5791       jcc(Assembler::notZero, L);
5792       STOP(buf);
5793     } else {
5794       jccb(Assembler::notZero, L);
5795       hlt();
5796     }
5797     bind(L);
5798   }
5799 #endif
5800 
5801   if (offset != 0)
5802     addptr(tmp, offset);
5803 
5804   return RegisterOrConstant(tmp);
5805 }
5806 
5807 
5808 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5809                                          int extra_slot_offset) {
5810   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5811   int stackElementSize = Interpreter::stackElementSize;
5812   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5813 #ifdef ASSERT
5814   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5815   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5816 #endif
5817   Register             scale_reg    = noreg;
5818   Address::ScaleFactor scale_factor = Address::no_scale;
5819   if (arg_slot.is_constant()) {
5820     offset += arg_slot.as_constant() * stackElementSize;
5821   } else {
5822     scale_reg    = arg_slot.as_register();
5823     scale_factor = Address::times(stackElementSize);
5824   }
5825   offset += wordSize;           // return PC is on stack
5826   return Address(rsp, scale_reg, scale_factor, offset);
5827 }
5828 
5829 
5830 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5831   if (!VerifyOops) return;
5832 
5833   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5834   // Pass register number to verify_oop_subroutine
5835   const char* b = NULL;
5836   {
5837     ResourceMark rm;
5838     stringStream ss;
5839     ss.print("verify_oop_addr: %s", s);
5840     b = code_string(ss.as_string());
5841   }
5842 #ifdef _LP64
5843   push(rscratch1);                    // save r10, trashed by movptr()
5844 #endif
5845   push(rax);                          // save rax,
5846   // addr may contain rsp so we will have to adjust it based on the push
5847   // we just did (and on 64 bit we do two pushes)
5848   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5849   // stores rax into addr which is backwards of what was intended.
5850   if (addr.uses(rsp)) {
5851     lea(rax, addr);
5852     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5853   } else {
5854     pushptr(addr);
5855   }
5856 
5857   ExternalAddress buffer((address) b);
5858   // pass msg argument
5859   // avoid using pushptr, as it modifies scratch registers
5860   // and our contract is not to modify anything
5861   movptr(rax, buffer.addr());
5862   push(rax);
5863 
5864   // call indirectly to solve generation ordering problem
5865   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5866   call(rax);
5867   // Caller pops the arguments (addr, message) and restores rax, r10.
5868 }
5869 
5870 void MacroAssembler::verify_tlab() {
5871 #ifdef ASSERT
5872   if (UseTLAB && VerifyOops) {
5873     Label next, ok;
5874     Register t1 = rsi;
5875     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5876 
5877     push(t1);
5878     NOT_LP64(push(thread_reg));
5879     NOT_LP64(get_thread(thread_reg));
5880 
5881     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5882     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5883     jcc(Assembler::aboveEqual, next);
5884     STOP("assert(top >= start)");
5885     should_not_reach_here();
5886 
5887     bind(next);
5888     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5889     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5890     jcc(Assembler::aboveEqual, ok);
5891     STOP("assert(top <= end)");
5892     should_not_reach_here();
5893 
5894     bind(ok);
5895     NOT_LP64(pop(thread_reg));
5896     pop(t1);
5897   }
5898 #endif
5899 }
5900 
5901 class ControlWord {
5902  public:
5903   int32_t _value;
5904 
5905   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5906   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5907   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5908   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5909   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5910   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5911   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5912   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5913 
5914   void print() const {
5915     // rounding control
5916     const char* rc;
5917     switch (rounding_control()) {
5918       case 0: rc = "round near"; break;
5919       case 1: rc = "round down"; break;
5920       case 2: rc = "round up  "; break;
5921       case 3: rc = "chop      "; break;
5922     };
5923     // precision control
5924     const char* pc;
5925     switch (precision_control()) {
5926       case 0: pc = "24 bits "; break;
5927       case 1: pc = "reserved"; break;
5928       case 2: pc = "53 bits "; break;
5929       case 3: pc = "64 bits "; break;
5930     };
5931     // flags
5932     char f[9];
5933     f[0] = ' ';
5934     f[1] = ' ';
5935     f[2] = (precision   ()) ? 'P' : 'p';
5936     f[3] = (underflow   ()) ? 'U' : 'u';
5937     f[4] = (overflow    ()) ? 'O' : 'o';
5938     f[5] = (zero_divide ()) ? 'Z' : 'z';
5939     f[6] = (denormalized()) ? 'D' : 'd';
5940     f[7] = (invalid     ()) ? 'I' : 'i';
5941     f[8] = '\x0';
5942     // output
5943     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
5944   }
5945 
5946 };
5947 
5948 class StatusWord {
5949  public:
5950   int32_t _value;
5951 
5952   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
5953   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
5954   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
5955   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
5956   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
5957   int  top() const                     { return  (_value >> 11) & 7      ; }
5958   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
5959   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
5960   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5961   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5962   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5963   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5964   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5965   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5966 
5967   void print() const {
5968     // condition codes
5969     char c[5];
5970     c[0] = (C3()) ? '3' : '-';
5971     c[1] = (C2()) ? '2' : '-';
5972     c[2] = (C1()) ? '1' : '-';
5973     c[3] = (C0()) ? '0' : '-';
5974     c[4] = '\x0';
5975     // flags
5976     char f[9];
5977     f[0] = (error_status()) ? 'E' : '-';
5978     f[1] = (stack_fault ()) ? 'S' : '-';
5979     f[2] = (precision   ()) ? 'P' : '-';
5980     f[3] = (underflow   ()) ? 'U' : '-';
5981     f[4] = (overflow    ()) ? 'O' : '-';
5982     f[5] = (zero_divide ()) ? 'Z' : '-';
5983     f[6] = (denormalized()) ? 'D' : '-';
5984     f[7] = (invalid     ()) ? 'I' : '-';
5985     f[8] = '\x0';
5986     // output
5987     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
5988   }
5989 
5990 };
5991 
5992 class TagWord {
5993  public:
5994   int32_t _value;
5995 
5996   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
5997 
5998   void print() const {
5999     printf("%04x", _value & 0xFFFF);
6000   }
6001 
6002 };
6003 
6004 class FPU_Register {
6005  public:
6006   int32_t _m0;
6007   int32_t _m1;
6008   int16_t _ex;
6009 
6010   bool is_indefinite() const           {
6011     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6012   }
6013 
6014   void print() const {
6015     char  sign = (_ex < 0) ? '-' : '+';
6016     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6017     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6018   };
6019 
6020 };
6021 
6022 class FPU_State {
6023  public:
6024   enum {
6025     register_size       = 10,
6026     number_of_registers =  8,
6027     register_mask       =  7
6028   };
6029 
6030   ControlWord  _control_word;
6031   StatusWord   _status_word;
6032   TagWord      _tag_word;
6033   int32_t      _error_offset;
6034   int32_t      _error_selector;
6035   int32_t      _data_offset;
6036   int32_t      _data_selector;
6037   int8_t       _register[register_size * number_of_registers];
6038 
6039   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6040   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6041 
6042   const char* tag_as_string(int tag) const {
6043     switch (tag) {
6044       case 0: return "valid";
6045       case 1: return "zero";
6046       case 2: return "special";
6047       case 3: return "empty";
6048     }
6049     ShouldNotReachHere();
6050     return NULL;
6051   }
6052 
6053   void print() const {
6054     // print computation registers
6055     { int t = _status_word.top();
6056       for (int i = 0; i < number_of_registers; i++) {
6057         int j = (i - t) & register_mask;
6058         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6059         st(j)->print();
6060         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6061       }
6062     }
6063     printf("\n");
6064     // print control registers
6065     printf("ctrl = "); _control_word.print(); printf("\n");
6066     printf("stat = "); _status_word .print(); printf("\n");
6067     printf("tags = "); _tag_word    .print(); printf("\n");
6068   }
6069 
6070 };
6071 
6072 class Flag_Register {
6073  public:
6074   int32_t _value;
6075 
6076   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6077   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6078   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6079   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6080   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6081   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6082   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6083 
6084   void print() const {
6085     // flags
6086     char f[8];
6087     f[0] = (overflow       ()) ? 'O' : '-';
6088     f[1] = (direction      ()) ? 'D' : '-';
6089     f[2] = (sign           ()) ? 'S' : '-';
6090     f[3] = (zero           ()) ? 'Z' : '-';
6091     f[4] = (auxiliary_carry()) ? 'A' : '-';
6092     f[5] = (parity         ()) ? 'P' : '-';
6093     f[6] = (carry          ()) ? 'C' : '-';
6094     f[7] = '\x0';
6095     // output
6096     printf("%08x  flags = %s", _value, f);
6097   }
6098 
6099 };
6100 
6101 class IU_Register {
6102  public:
6103   int32_t _value;
6104 
6105   void print() const {
6106     printf("%08x  %11d", _value, _value);
6107   }
6108 
6109 };
6110 
6111 class IU_State {
6112  public:
6113   Flag_Register _eflags;
6114   IU_Register   _rdi;
6115   IU_Register   _rsi;
6116   IU_Register   _rbp;
6117   IU_Register   _rsp;
6118   IU_Register   _rbx;
6119   IU_Register   _rdx;
6120   IU_Register   _rcx;
6121   IU_Register   _rax;
6122 
6123   void print() const {
6124     // computation registers
6125     printf("rax,  = "); _rax.print(); printf("\n");
6126     printf("rbx,  = "); _rbx.print(); printf("\n");
6127     printf("rcx  = "); _rcx.print(); printf("\n");
6128     printf("rdx  = "); _rdx.print(); printf("\n");
6129     printf("rdi  = "); _rdi.print(); printf("\n");
6130     printf("rsi  = "); _rsi.print(); printf("\n");
6131     printf("rbp,  = "); _rbp.print(); printf("\n");
6132     printf("rsp  = "); _rsp.print(); printf("\n");
6133     printf("\n");
6134     // control registers
6135     printf("flgs = "); _eflags.print(); printf("\n");
6136   }
6137 };
6138 
6139 
6140 class CPU_State {
6141  public:
6142   FPU_State _fpu_state;
6143   IU_State  _iu_state;
6144 
6145   void print() const {
6146     printf("--------------------------------------------------\n");
6147     _iu_state .print();
6148     printf("\n");
6149     _fpu_state.print();
6150     printf("--------------------------------------------------\n");
6151   }
6152 
6153 };
6154 
6155 
6156 static void _print_CPU_state(CPU_State* state) {
6157   state->print();
6158 };
6159 
6160 
6161 void MacroAssembler::print_CPU_state() {
6162   push_CPU_state();
6163   push(rsp);                // pass CPU state
6164   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6165   addptr(rsp, wordSize);       // discard argument
6166   pop_CPU_state();
6167 }
6168 
6169 
6170 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6171   static int counter = 0;
6172   FPU_State* fs = &state->_fpu_state;
6173   counter++;
6174   // For leaf calls, only verify that the top few elements remain empty.
6175   // We only need 1 empty at the top for C2 code.
6176   if( stack_depth < 0 ) {
6177     if( fs->tag_for_st(7) != 3 ) {
6178       printf("FPR7 not empty\n");
6179       state->print();
6180       assert(false, "error");
6181       return false;
6182     }
6183     return true;                // All other stack states do not matter
6184   }
6185 
6186   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6187          "bad FPU control word");
6188 
6189   // compute stack depth
6190   int i = 0;
6191   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6192   int d = i;
6193   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6194   // verify findings
6195   if (i != FPU_State::number_of_registers) {
6196     // stack not contiguous
6197     printf("%s: stack not contiguous at ST%d\n", s, i);
6198     state->print();
6199     assert(false, "error");
6200     return false;
6201   }
6202   // check if computed stack depth corresponds to expected stack depth
6203   if (stack_depth < 0) {
6204     // expected stack depth is -stack_depth or less
6205     if (d > -stack_depth) {
6206       // too many elements on the stack
6207       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6208       state->print();
6209       assert(false, "error");
6210       return false;
6211     }
6212   } else {
6213     // expected stack depth is stack_depth
6214     if (d != stack_depth) {
6215       // wrong stack depth
6216       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6217       state->print();
6218       assert(false, "error");
6219       return false;
6220     }
6221   }
6222   // everything is cool
6223   return true;
6224 }
6225 
6226 
6227 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6228   if (!VerifyFPU) return;
6229   push_CPU_state();
6230   push(rsp);                // pass CPU state
6231   ExternalAddress msg((address) s);
6232   // pass message string s
6233   pushptr(msg.addr());
6234   push(stack_depth);        // pass stack depth
6235   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6236   addptr(rsp, 3 * wordSize);   // discard arguments
6237   // check for error
6238   { Label L;
6239     testl(rax, rax);
6240     jcc(Assembler::notZero, L);
6241     int3();                  // break if error condition
6242     bind(L);
6243   }
6244   pop_CPU_state();
6245 }
6246 
6247 void MacroAssembler::restore_cpu_control_state_after_jni() {
6248   // Either restore the MXCSR register after returning from the JNI Call
6249   // or verify that it wasn't changed (with -Xcheck:jni flag).
6250   if (VM_Version::supports_sse()) {
6251     if (RestoreMXCSROnJNICalls) {
6252       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6253     } else if (CheckJNICalls) {
6254       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6255     }
6256   }
6257   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6258   vzeroupper();
6259   // Reset k1 to 0xffff.
6260   if (VM_Version::supports_evex()) {
6261     push(rcx);
6262     movl(rcx, 0xffff);
6263     kmovwl(k1, rcx);
6264     pop(rcx);
6265   }
6266 
6267 #ifndef _LP64
6268   // Either restore the x87 floating pointer control word after returning
6269   // from the JNI call or verify that it wasn't changed.
6270   if (CheckJNICalls) {
6271     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6272   }
6273 #endif // _LP64
6274 }
6275 
6276 // ((OopHandle)result).resolve();
6277 void MacroAssembler::resolve_oop_handle(Register result) {
6278   // OopHandle::resolve is an indirection.
6279   movptr(result, Address(result, 0));
6280 }
6281 
6282 void MacroAssembler::load_mirror(Register mirror, Register method) {
6283   // get mirror
6284   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6285   movptr(mirror, Address(method, Method::const_offset()));
6286   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6287   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6288   movptr(mirror, Address(mirror, mirror_offset));
6289   resolve_oop_handle(mirror);
6290 }
6291 
6292 void MacroAssembler::load_klass(Register dst, Register src) {
6293 #ifdef _LP64
6294   if (UseCompressedClassPointers) {
6295     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6296     decode_klass_not_null(dst);
6297   } else
6298 #endif
6299     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6300 }
6301 
6302 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6303   load_klass(dst, src);
6304   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6305 }
6306 
6307 void MacroAssembler::store_klass(Register dst, Register src) {
6308 #ifdef _LP64
6309   if (UseCompressedClassPointers) {
6310     encode_klass_not_null(src);
6311     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6312   } else
6313 #endif
6314     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6315 }
6316 
6317 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6318                                     Register tmp1, Register thread_tmp) {
6319   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6320   bool as_raw = (decorators & AS_RAW) != 0;
6321   if (as_raw) {
6322     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6323   } else {
6324     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6325   }
6326 }
6327 
6328 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6329                                      Register tmp1, Register tmp2) {
6330   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6331   bool as_raw = (decorators & AS_RAW) != 0;
6332   if (as_raw) {
6333     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6334   } else {
6335     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6336   }
6337 }
6338 
6339 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6340                                    Register thread_tmp, DecoratorSet decorators) {
6341   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6342 }
6343 
6344 // Doesn't do verfication, generates fixed size code
6345 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6346                                             Register thread_tmp, DecoratorSet decorators) {
6347   access_load_at(T_OBJECT, IN_HEAP | OOP_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6348 }
6349 
6350 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6351                                     Register tmp2, DecoratorSet decorators) {
6352   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6353 }
6354 
6355 // Used for storing NULLs.
6356 void MacroAssembler::store_heap_oop_null(Address dst) {
6357   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6358 }
6359 
6360 #ifdef _LP64
6361 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6362   if (UseCompressedClassPointers) {
6363     // Store to klass gap in destination
6364     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6365   }
6366 }
6367 
6368 #ifdef ASSERT
6369 void MacroAssembler::verify_heapbase(const char* msg) {
6370   assert (UseCompressedOops, "should be compressed");
6371   assert (Universe::heap() != NULL, "java heap should be initialized");
6372   if (CheckCompressedOops) {
6373     Label ok;
6374     push(rscratch1); // cmpptr trashes rscratch1
6375     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6376     jcc(Assembler::equal, ok);
6377     STOP(msg);
6378     bind(ok);
6379     pop(rscratch1);
6380   }
6381 }
6382 #endif
6383 
6384 // Algorithm must match oop.inline.hpp encode_heap_oop.
6385 void MacroAssembler::encode_heap_oop(Register r) {
6386 #ifdef ASSERT
6387   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6388 #endif
6389   verify_oop(r, "broken oop in encode_heap_oop");
6390   if (Universe::narrow_oop_base() == NULL) {
6391     if (Universe::narrow_oop_shift() != 0) {
6392       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6393       shrq(r, LogMinObjAlignmentInBytes);
6394     }
6395     return;
6396   }
6397   testq(r, r);
6398   cmovq(Assembler::equal, r, r12_heapbase);
6399   subq(r, r12_heapbase);
6400   shrq(r, LogMinObjAlignmentInBytes);
6401 }
6402 
6403 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6404 #ifdef ASSERT
6405   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6406   if (CheckCompressedOops) {
6407     Label ok;
6408     testq(r, r);
6409     jcc(Assembler::notEqual, ok);
6410     STOP("null oop passed to encode_heap_oop_not_null");
6411     bind(ok);
6412   }
6413 #endif
6414   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6415   if (Universe::narrow_oop_base() != NULL) {
6416     subq(r, r12_heapbase);
6417   }
6418   if (Universe::narrow_oop_shift() != 0) {
6419     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6420     shrq(r, LogMinObjAlignmentInBytes);
6421   }
6422 }
6423 
6424 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6425 #ifdef ASSERT
6426   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6427   if (CheckCompressedOops) {
6428     Label ok;
6429     testq(src, src);
6430     jcc(Assembler::notEqual, ok);
6431     STOP("null oop passed to encode_heap_oop_not_null2");
6432     bind(ok);
6433   }
6434 #endif
6435   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6436   if (dst != src) {
6437     movq(dst, src);
6438   }
6439   if (Universe::narrow_oop_base() != NULL) {
6440     subq(dst, r12_heapbase);
6441   }
6442   if (Universe::narrow_oop_shift() != 0) {
6443     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6444     shrq(dst, LogMinObjAlignmentInBytes);
6445   }
6446 }
6447 
6448 void  MacroAssembler::decode_heap_oop(Register r) {
6449 #ifdef ASSERT
6450   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6451 #endif
6452   if (Universe::narrow_oop_base() == NULL) {
6453     if (Universe::narrow_oop_shift() != 0) {
6454       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6455       shlq(r, LogMinObjAlignmentInBytes);
6456     }
6457   } else {
6458     Label done;
6459     shlq(r, LogMinObjAlignmentInBytes);
6460     jccb(Assembler::equal, done);
6461     addq(r, r12_heapbase);
6462     bind(done);
6463   }
6464   verify_oop(r, "broken oop in decode_heap_oop");
6465 }
6466 
6467 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6468   // Note: it will change flags
6469   assert (UseCompressedOops, "should only be used for compressed headers");
6470   assert (Universe::heap() != NULL, "java heap should be initialized");
6471   // Cannot assert, unverified entry point counts instructions (see .ad file)
6472   // vtableStubs also counts instructions in pd_code_size_limit.
6473   // Also do not verify_oop as this is called by verify_oop.
6474   if (Universe::narrow_oop_shift() != 0) {
6475     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6476     shlq(r, LogMinObjAlignmentInBytes);
6477     if (Universe::narrow_oop_base() != NULL) {
6478       addq(r, r12_heapbase);
6479     }
6480   } else {
6481     assert (Universe::narrow_oop_base() == NULL, "sanity");
6482   }
6483 }
6484 
6485 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6486   // Note: it will change flags
6487   assert (UseCompressedOops, "should only be used for compressed headers");
6488   assert (Universe::heap() != NULL, "java heap should be initialized");
6489   // Cannot assert, unverified entry point counts instructions (see .ad file)
6490   // vtableStubs also counts instructions in pd_code_size_limit.
6491   // Also do not verify_oop as this is called by verify_oop.
6492   if (Universe::narrow_oop_shift() != 0) {
6493     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6494     if (LogMinObjAlignmentInBytes == Address::times_8) {
6495       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6496     } else {
6497       if (dst != src) {
6498         movq(dst, src);
6499       }
6500       shlq(dst, LogMinObjAlignmentInBytes);
6501       if (Universe::narrow_oop_base() != NULL) {
6502         addq(dst, r12_heapbase);
6503       }
6504     }
6505   } else {
6506     assert (Universe::narrow_oop_base() == NULL, "sanity");
6507     if (dst != src) {
6508       movq(dst, src);
6509     }
6510   }
6511 }
6512 
6513 void MacroAssembler::encode_klass_not_null(Register r) {
6514   if (Universe::narrow_klass_base() != NULL) {
6515     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6516     assert(r != r12_heapbase, "Encoding a klass in r12");
6517     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6518     subq(r, r12_heapbase);
6519   }
6520   if (Universe::narrow_klass_shift() != 0) {
6521     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6522     shrq(r, LogKlassAlignmentInBytes);
6523   }
6524   if (Universe::narrow_klass_base() != NULL) {
6525     reinit_heapbase();
6526   }
6527 }
6528 
6529 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6530   if (dst == src) {
6531     encode_klass_not_null(src);
6532   } else {
6533     if (Universe::narrow_klass_base() != NULL) {
6534       mov64(dst, (int64_t)Universe::narrow_klass_base());
6535       negq(dst);
6536       addq(dst, src);
6537     } else {
6538       movptr(dst, src);
6539     }
6540     if (Universe::narrow_klass_shift() != 0) {
6541       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6542       shrq(dst, LogKlassAlignmentInBytes);
6543     }
6544   }
6545 }
6546 
6547 // Function instr_size_for_decode_klass_not_null() counts the instructions
6548 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6549 // when (Universe::heap() != NULL).  Hence, if the instructions they
6550 // generate change, then this method needs to be updated.
6551 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6552   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6553   if (Universe::narrow_klass_base() != NULL) {
6554     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6555     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6556   } else {
6557     // longest load decode klass function, mov64, leaq
6558     return 16;
6559   }
6560 }
6561 
6562 // !!! If the instructions that get generated here change then function
6563 // instr_size_for_decode_klass_not_null() needs to get updated.
6564 void  MacroAssembler::decode_klass_not_null(Register r) {
6565   // Note: it will change flags
6566   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6567   assert(r != r12_heapbase, "Decoding a klass in r12");
6568   // Cannot assert, unverified entry point counts instructions (see .ad file)
6569   // vtableStubs also counts instructions in pd_code_size_limit.
6570   // Also do not verify_oop as this is called by verify_oop.
6571   if (Universe::narrow_klass_shift() != 0) {
6572     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6573     shlq(r, LogKlassAlignmentInBytes);
6574   }
6575   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6576   if (Universe::narrow_klass_base() != NULL) {
6577     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6578     addq(r, r12_heapbase);
6579     reinit_heapbase();
6580   }
6581 }
6582 
6583 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6584   // Note: it will change flags
6585   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6586   if (dst == src) {
6587     decode_klass_not_null(dst);
6588   } else {
6589     // Cannot assert, unverified entry point counts instructions (see .ad file)
6590     // vtableStubs also counts instructions in pd_code_size_limit.
6591     // Also do not verify_oop as this is called by verify_oop.
6592     mov64(dst, (int64_t)Universe::narrow_klass_base());
6593     if (Universe::narrow_klass_shift() != 0) {
6594       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6595       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6596       leaq(dst, Address(dst, src, Address::times_8, 0));
6597     } else {
6598       addq(dst, src);
6599     }
6600   }
6601 }
6602 
6603 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6604   assert (UseCompressedOops, "should only be used for compressed headers");
6605   assert (Universe::heap() != NULL, "java heap should be initialized");
6606   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6607   int oop_index = oop_recorder()->find_index(obj);
6608   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6609   mov_narrow_oop(dst, oop_index, rspec);
6610 }
6611 
6612 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6613   assert (UseCompressedOops, "should only be used for compressed headers");
6614   assert (Universe::heap() != NULL, "java heap should be initialized");
6615   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6616   int oop_index = oop_recorder()->find_index(obj);
6617   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6618   mov_narrow_oop(dst, oop_index, rspec);
6619 }
6620 
6621 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6622   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6623   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6624   int klass_index = oop_recorder()->find_index(k);
6625   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6626   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6627 }
6628 
6629 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6630   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6631   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6632   int klass_index = oop_recorder()->find_index(k);
6633   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6634   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6635 }
6636 
6637 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6638   assert (UseCompressedOops, "should only be used for compressed headers");
6639   assert (Universe::heap() != NULL, "java heap should be initialized");
6640   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6641   int oop_index = oop_recorder()->find_index(obj);
6642   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6643   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6644 }
6645 
6646 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6647   assert (UseCompressedOops, "should only be used for compressed headers");
6648   assert (Universe::heap() != NULL, "java heap should be initialized");
6649   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6650   int oop_index = oop_recorder()->find_index(obj);
6651   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6652   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6653 }
6654 
6655 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6656   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6657   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6658   int klass_index = oop_recorder()->find_index(k);
6659   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6660   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6661 }
6662 
6663 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6664   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6665   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6666   int klass_index = oop_recorder()->find_index(k);
6667   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6668   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6669 }
6670 
6671 void MacroAssembler::reinit_heapbase() {
6672   if (UseCompressedOops || UseCompressedClassPointers) {
6673     if (Universe::heap() != NULL) {
6674       if (Universe::narrow_oop_base() == NULL) {
6675         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6676       } else {
6677         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6678       }
6679     } else {
6680       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6681     }
6682   }
6683 }
6684 
6685 #endif // _LP64
6686 
6687 // C2 compiled method's prolog code.
6688 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6689 
6690   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6691   // NativeJump::patch_verified_entry will be able to patch out the entry
6692   // code safely. The push to verify stack depth is ok at 5 bytes,
6693   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6694   // stack bang then we must use the 6 byte frame allocation even if
6695   // we have no frame. :-(
6696   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6697 
6698   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6699   // Remove word for return addr
6700   framesize -= wordSize;
6701   stack_bang_size -= wordSize;
6702 
6703   // Calls to C2R adapters often do not accept exceptional returns.
6704   // We require that their callers must bang for them.  But be careful, because
6705   // some VM calls (such as call site linkage) can use several kilobytes of
6706   // stack.  But the stack safety zone should account for that.
6707   // See bugs 4446381, 4468289, 4497237.
6708   if (stack_bang_size > 0) {
6709     generate_stack_overflow_check(stack_bang_size);
6710 
6711     // We always push rbp, so that on return to interpreter rbp, will be
6712     // restored correctly and we can correct the stack.
6713     push(rbp);
6714     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6715     if (PreserveFramePointer) {
6716       mov(rbp, rsp);
6717     }
6718     // Remove word for ebp
6719     framesize -= wordSize;
6720 
6721     // Create frame
6722     if (framesize) {
6723       subptr(rsp, framesize);
6724     }
6725   } else {
6726     // Create frame (force generation of a 4 byte immediate value)
6727     subptr_imm32(rsp, framesize);
6728 
6729     // Save RBP register now.
6730     framesize -= wordSize;
6731     movptr(Address(rsp, framesize), rbp);
6732     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6733     if (PreserveFramePointer) {
6734       movptr(rbp, rsp);
6735       if (framesize > 0) {
6736         addptr(rbp, framesize);
6737       }
6738     }
6739   }
6740 
6741   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6742     framesize -= wordSize;
6743     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6744   }
6745 
6746 #ifndef _LP64
6747   // If method sets FPU control word do it now
6748   if (fp_mode_24b) {
6749     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6750   }
6751   if (UseSSE >= 2 && VerifyFPU) {
6752     verify_FPU(0, "FPU stack must be clean on entry");
6753   }
6754 #endif
6755 
6756 #ifdef ASSERT
6757   if (VerifyStackAtCalls) {
6758     Label L;
6759     push(rax);
6760     mov(rax, rsp);
6761     andptr(rax, StackAlignmentInBytes-1);
6762     cmpptr(rax, StackAlignmentInBytes-wordSize);
6763     pop(rax);
6764     jcc(Assembler::equal, L);
6765     STOP("Stack is not properly aligned!");
6766     bind(L);
6767   }
6768 #endif
6769 
6770 }
6771 
6772 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6773   // cnt - number of qwords (8-byte words).
6774   // base - start address, qword aligned.
6775   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6776   assert(base==rdi, "base register must be edi for rep stos");
6777   assert(tmp==rax,   "tmp register must be eax for rep stos");
6778   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6779   assert(InitArrayShortSize % BytesPerLong == 0,
6780     "InitArrayShortSize should be the multiple of BytesPerLong");
6781 
6782   Label DONE;
6783 
6784   xorptr(tmp, tmp);
6785 
6786   if (!is_large) {
6787     Label LOOP, LONG;
6788     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6789     jccb(Assembler::greater, LONG);
6790 
6791     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6792 
6793     decrement(cnt);
6794     jccb(Assembler::negative, DONE); // Zero length
6795 
6796     // Use individual pointer-sized stores for small counts:
6797     BIND(LOOP);
6798     movptr(Address(base, cnt, Address::times_ptr), tmp);
6799     decrement(cnt);
6800     jccb(Assembler::greaterEqual, LOOP);
6801     jmpb(DONE);
6802 
6803     BIND(LONG);
6804   }
6805 
6806   // Use longer rep-prefixed ops for non-small counts:
6807   if (UseFastStosb) {
6808     shlptr(cnt, 3); // convert to number of bytes
6809     rep_stosb();
6810   } else {
6811     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6812     rep_stos();
6813   }
6814 
6815   BIND(DONE);
6816 }
6817 
6818 #ifdef COMPILER2
6819 
6820 // IndexOf for constant substrings with size >= 8 chars
6821 // which don't need to be loaded through stack.
6822 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6823                                       Register cnt1, Register cnt2,
6824                                       int int_cnt2,  Register result,
6825                                       XMMRegister vec, Register tmp,
6826                                       int ae) {
6827   ShortBranchVerifier sbv(this);
6828   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6829   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6830 
6831   // This method uses the pcmpestri instruction with bound registers
6832   //   inputs:
6833   //     xmm - substring
6834   //     rax - substring length (elements count)
6835   //     mem - scanned string
6836   //     rdx - string length (elements count)
6837   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6838   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6839   //   outputs:
6840   //     rcx - matched index in string
6841   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6842   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6843   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6844   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6845   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6846 
6847   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6848         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6849         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6850 
6851   // Note, inline_string_indexOf() generates checks:
6852   // if (substr.count > string.count) return -1;
6853   // if (substr.count == 0) return 0;
6854   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6855 
6856   // Load substring.
6857   if (ae == StrIntrinsicNode::UL) {
6858     pmovzxbw(vec, Address(str2, 0));
6859   } else {
6860     movdqu(vec, Address(str2, 0));
6861   }
6862   movl(cnt2, int_cnt2);
6863   movptr(result, str1); // string addr
6864 
6865   if (int_cnt2 > stride) {
6866     jmpb(SCAN_TO_SUBSTR);
6867 
6868     // Reload substr for rescan, this code
6869     // is executed only for large substrings (> 8 chars)
6870     bind(RELOAD_SUBSTR);
6871     if (ae == StrIntrinsicNode::UL) {
6872       pmovzxbw(vec, Address(str2, 0));
6873     } else {
6874       movdqu(vec, Address(str2, 0));
6875     }
6876     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6877 
6878     bind(RELOAD_STR);
6879     // We came here after the beginning of the substring was
6880     // matched but the rest of it was not so we need to search
6881     // again. Start from the next element after the previous match.
6882 
6883     // cnt2 is number of substring reminding elements and
6884     // cnt1 is number of string reminding elements when cmp failed.
6885     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6886     subl(cnt1, cnt2);
6887     addl(cnt1, int_cnt2);
6888     movl(cnt2, int_cnt2); // Now restore cnt2
6889 
6890     decrementl(cnt1);     // Shift to next element
6891     cmpl(cnt1, cnt2);
6892     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6893 
6894     addptr(result, (1<<scale1));
6895 
6896   } // (int_cnt2 > 8)
6897 
6898   // Scan string for start of substr in 16-byte vectors
6899   bind(SCAN_TO_SUBSTR);
6900   pcmpestri(vec, Address(result, 0), mode);
6901   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6902   subl(cnt1, stride);
6903   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6904   cmpl(cnt1, cnt2);
6905   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6906   addptr(result, 16);
6907   jmpb(SCAN_TO_SUBSTR);
6908 
6909   // Found a potential substr
6910   bind(FOUND_CANDIDATE);
6911   // Matched whole vector if first element matched (tmp(rcx) == 0).
6912   if (int_cnt2 == stride) {
6913     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
6914   } else { // int_cnt2 > 8
6915     jccb(Assembler::overflow, FOUND_SUBSTR);
6916   }
6917   // After pcmpestri tmp(rcx) contains matched element index
6918   // Compute start addr of substr
6919   lea(result, Address(result, tmp, scale1));
6920 
6921   // Make sure string is still long enough
6922   subl(cnt1, tmp);
6923   cmpl(cnt1, cnt2);
6924   if (int_cnt2 == stride) {
6925     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
6926   } else { // int_cnt2 > 8
6927     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
6928   }
6929   // Left less then substring.
6930 
6931   bind(RET_NOT_FOUND);
6932   movl(result, -1);
6933   jmp(EXIT);
6934 
6935   if (int_cnt2 > stride) {
6936     // This code is optimized for the case when whole substring
6937     // is matched if its head is matched.
6938     bind(MATCH_SUBSTR_HEAD);
6939     pcmpestri(vec, Address(result, 0), mode);
6940     // Reload only string if does not match
6941     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
6942 
6943     Label CONT_SCAN_SUBSTR;
6944     // Compare the rest of substring (> 8 chars).
6945     bind(FOUND_SUBSTR);
6946     // First 8 chars are already matched.
6947     negptr(cnt2);
6948     addptr(cnt2, stride);
6949 
6950     bind(SCAN_SUBSTR);
6951     subl(cnt1, stride);
6952     cmpl(cnt2, -stride); // Do not read beyond substring
6953     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
6954     // Back-up strings to avoid reading beyond substring:
6955     // cnt1 = cnt1 - cnt2 + 8
6956     addl(cnt1, cnt2); // cnt2 is negative
6957     addl(cnt1, stride);
6958     movl(cnt2, stride); negptr(cnt2);
6959     bind(CONT_SCAN_SUBSTR);
6960     if (int_cnt2 < (int)G) {
6961       int tail_off1 = int_cnt2<<scale1;
6962       int tail_off2 = int_cnt2<<scale2;
6963       if (ae == StrIntrinsicNode::UL) {
6964         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
6965       } else {
6966         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
6967       }
6968       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
6969     } else {
6970       // calculate index in register to avoid integer overflow (int_cnt2*2)
6971       movl(tmp, int_cnt2);
6972       addptr(tmp, cnt2);
6973       if (ae == StrIntrinsicNode::UL) {
6974         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
6975       } else {
6976         movdqu(vec, Address(str2, tmp, scale2, 0));
6977       }
6978       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
6979     }
6980     // Need to reload strings pointers if not matched whole vector
6981     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
6982     addptr(cnt2, stride);
6983     jcc(Assembler::negative, SCAN_SUBSTR);
6984     // Fall through if found full substring
6985 
6986   } // (int_cnt2 > 8)
6987 
6988   bind(RET_FOUND);
6989   // Found result if we matched full small substring.
6990   // Compute substr offset
6991   subptr(result, str1);
6992   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
6993     shrl(result, 1); // index
6994   }
6995   bind(EXIT);
6996 
6997 } // string_indexofC8
6998 
6999 // Small strings are loaded through stack if they cross page boundary.
7000 void MacroAssembler::string_indexof(Register str1, Register str2,
7001                                     Register cnt1, Register cnt2,
7002                                     int int_cnt2,  Register result,
7003                                     XMMRegister vec, Register tmp,
7004                                     int ae) {
7005   ShortBranchVerifier sbv(this);
7006   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7007   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7008 
7009   //
7010   // int_cnt2 is length of small (< 8 chars) constant substring
7011   // or (-1) for non constant substring in which case its length
7012   // is in cnt2 register.
7013   //
7014   // Note, inline_string_indexOf() generates checks:
7015   // if (substr.count > string.count) return -1;
7016   // if (substr.count == 0) return 0;
7017   //
7018   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7019   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7020   // This method uses the pcmpestri instruction with bound registers
7021   //   inputs:
7022   //     xmm - substring
7023   //     rax - substring length (elements count)
7024   //     mem - scanned string
7025   //     rdx - string length (elements count)
7026   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7027   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7028   //   outputs:
7029   //     rcx - matched index in string
7030   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7031   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7032   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7033   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7034 
7035   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7036         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7037         FOUND_CANDIDATE;
7038 
7039   { //========================================================
7040     // We don't know where these strings are located
7041     // and we can't read beyond them. Load them through stack.
7042     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7043 
7044     movptr(tmp, rsp); // save old SP
7045 
7046     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7047       if (int_cnt2 == (1>>scale2)) { // One byte
7048         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7049         load_unsigned_byte(result, Address(str2, 0));
7050         movdl(vec, result); // move 32 bits
7051       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7052         // Not enough header space in 32-bit VM: 12+3 = 15.
7053         movl(result, Address(str2, -1));
7054         shrl(result, 8);
7055         movdl(vec, result); // move 32 bits
7056       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7057         load_unsigned_short(result, Address(str2, 0));
7058         movdl(vec, result); // move 32 bits
7059       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7060         movdl(vec, Address(str2, 0)); // move 32 bits
7061       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7062         movq(vec, Address(str2, 0));  // move 64 bits
7063       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7064         // Array header size is 12 bytes in 32-bit VM
7065         // + 6 bytes for 3 chars == 18 bytes,
7066         // enough space to load vec and shift.
7067         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7068         if (ae == StrIntrinsicNode::UL) {
7069           int tail_off = int_cnt2-8;
7070           pmovzxbw(vec, Address(str2, tail_off));
7071           psrldq(vec, -2*tail_off);
7072         }
7073         else {
7074           int tail_off = int_cnt2*(1<<scale2);
7075           movdqu(vec, Address(str2, tail_off-16));
7076           psrldq(vec, 16-tail_off);
7077         }
7078       }
7079     } else { // not constant substring
7080       cmpl(cnt2, stride);
7081       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7082 
7083       // We can read beyond string if srt+16 does not cross page boundary
7084       // since heaps are aligned and mapped by pages.
7085       assert(os::vm_page_size() < (int)G, "default page should be small");
7086       movl(result, str2); // We need only low 32 bits
7087       andl(result, (os::vm_page_size()-1));
7088       cmpl(result, (os::vm_page_size()-16));
7089       jccb(Assembler::belowEqual, CHECK_STR);
7090 
7091       // Move small strings to stack to allow load 16 bytes into vec.
7092       subptr(rsp, 16);
7093       int stk_offset = wordSize-(1<<scale2);
7094       push(cnt2);
7095 
7096       bind(COPY_SUBSTR);
7097       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7098         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7099         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7100       } else if (ae == StrIntrinsicNode::UU) {
7101         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7102         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7103       }
7104       decrement(cnt2);
7105       jccb(Assembler::notZero, COPY_SUBSTR);
7106 
7107       pop(cnt2);
7108       movptr(str2, rsp);  // New substring address
7109     } // non constant
7110 
7111     bind(CHECK_STR);
7112     cmpl(cnt1, stride);
7113     jccb(Assembler::aboveEqual, BIG_STRINGS);
7114 
7115     // Check cross page boundary.
7116     movl(result, str1); // We need only low 32 bits
7117     andl(result, (os::vm_page_size()-1));
7118     cmpl(result, (os::vm_page_size()-16));
7119     jccb(Assembler::belowEqual, BIG_STRINGS);
7120 
7121     subptr(rsp, 16);
7122     int stk_offset = -(1<<scale1);
7123     if (int_cnt2 < 0) { // not constant
7124       push(cnt2);
7125       stk_offset += wordSize;
7126     }
7127     movl(cnt2, cnt1);
7128 
7129     bind(COPY_STR);
7130     if (ae == StrIntrinsicNode::LL) {
7131       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7132       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7133     } else {
7134       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7135       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7136     }
7137     decrement(cnt2);
7138     jccb(Assembler::notZero, COPY_STR);
7139 
7140     if (int_cnt2 < 0) { // not constant
7141       pop(cnt2);
7142     }
7143     movptr(str1, rsp);  // New string address
7144 
7145     bind(BIG_STRINGS);
7146     // Load substring.
7147     if (int_cnt2 < 0) { // -1
7148       if (ae == StrIntrinsicNode::UL) {
7149         pmovzxbw(vec, Address(str2, 0));
7150       } else {
7151         movdqu(vec, Address(str2, 0));
7152       }
7153       push(cnt2);       // substr count
7154       push(str2);       // substr addr
7155       push(str1);       // string addr
7156     } else {
7157       // Small (< 8 chars) constant substrings are loaded already.
7158       movl(cnt2, int_cnt2);
7159     }
7160     push(tmp);  // original SP
7161 
7162   } // Finished loading
7163 
7164   //========================================================
7165   // Start search
7166   //
7167 
7168   movptr(result, str1); // string addr
7169 
7170   if (int_cnt2  < 0) {  // Only for non constant substring
7171     jmpb(SCAN_TO_SUBSTR);
7172 
7173     // SP saved at sp+0
7174     // String saved at sp+1*wordSize
7175     // Substr saved at sp+2*wordSize
7176     // Substr count saved at sp+3*wordSize
7177 
7178     // Reload substr for rescan, this code
7179     // is executed only for large substrings (> 8 chars)
7180     bind(RELOAD_SUBSTR);
7181     movptr(str2, Address(rsp, 2*wordSize));
7182     movl(cnt2, Address(rsp, 3*wordSize));
7183     if (ae == StrIntrinsicNode::UL) {
7184       pmovzxbw(vec, Address(str2, 0));
7185     } else {
7186       movdqu(vec, Address(str2, 0));
7187     }
7188     // We came here after the beginning of the substring was
7189     // matched but the rest of it was not so we need to search
7190     // again. Start from the next element after the previous match.
7191     subptr(str1, result); // Restore counter
7192     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7193       shrl(str1, 1);
7194     }
7195     addl(cnt1, str1);
7196     decrementl(cnt1);   // Shift to next element
7197     cmpl(cnt1, cnt2);
7198     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7199 
7200     addptr(result, (1<<scale1));
7201   } // non constant
7202 
7203   // Scan string for start of substr in 16-byte vectors
7204   bind(SCAN_TO_SUBSTR);
7205   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7206   pcmpestri(vec, Address(result, 0), mode);
7207   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7208   subl(cnt1, stride);
7209   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7210   cmpl(cnt1, cnt2);
7211   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7212   addptr(result, 16);
7213 
7214   bind(ADJUST_STR);
7215   cmpl(cnt1, stride); // Do not read beyond string
7216   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7217   // Back-up string to avoid reading beyond string.
7218   lea(result, Address(result, cnt1, scale1, -16));
7219   movl(cnt1, stride);
7220   jmpb(SCAN_TO_SUBSTR);
7221 
7222   // Found a potential substr
7223   bind(FOUND_CANDIDATE);
7224   // After pcmpestri tmp(rcx) contains matched element index
7225 
7226   // Make sure string is still long enough
7227   subl(cnt1, tmp);
7228   cmpl(cnt1, cnt2);
7229   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7230   // Left less then substring.
7231 
7232   bind(RET_NOT_FOUND);
7233   movl(result, -1);
7234   jmpb(CLEANUP);
7235 
7236   bind(FOUND_SUBSTR);
7237   // Compute start addr of substr
7238   lea(result, Address(result, tmp, scale1));
7239   if (int_cnt2 > 0) { // Constant substring
7240     // Repeat search for small substring (< 8 chars)
7241     // from new point without reloading substring.
7242     // Have to check that we don't read beyond string.
7243     cmpl(tmp, stride-int_cnt2);
7244     jccb(Assembler::greater, ADJUST_STR);
7245     // Fall through if matched whole substring.
7246   } else { // non constant
7247     assert(int_cnt2 == -1, "should be != 0");
7248 
7249     addl(tmp, cnt2);
7250     // Found result if we matched whole substring.
7251     cmpl(tmp, stride);
7252     jccb(Assembler::lessEqual, RET_FOUND);
7253 
7254     // Repeat search for small substring (<= 8 chars)
7255     // from new point 'str1' without reloading substring.
7256     cmpl(cnt2, stride);
7257     // Have to check that we don't read beyond string.
7258     jccb(Assembler::lessEqual, ADJUST_STR);
7259 
7260     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7261     // Compare the rest of substring (> 8 chars).
7262     movptr(str1, result);
7263 
7264     cmpl(tmp, cnt2);
7265     // First 8 chars are already matched.
7266     jccb(Assembler::equal, CHECK_NEXT);
7267 
7268     bind(SCAN_SUBSTR);
7269     pcmpestri(vec, Address(str1, 0), mode);
7270     // Need to reload strings pointers if not matched whole vector
7271     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7272 
7273     bind(CHECK_NEXT);
7274     subl(cnt2, stride);
7275     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7276     addptr(str1, 16);
7277     if (ae == StrIntrinsicNode::UL) {
7278       addptr(str2, 8);
7279     } else {
7280       addptr(str2, 16);
7281     }
7282     subl(cnt1, stride);
7283     cmpl(cnt2, stride); // Do not read beyond substring
7284     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7285     // Back-up strings to avoid reading beyond substring.
7286 
7287     if (ae == StrIntrinsicNode::UL) {
7288       lea(str2, Address(str2, cnt2, scale2, -8));
7289       lea(str1, Address(str1, cnt2, scale1, -16));
7290     } else {
7291       lea(str2, Address(str2, cnt2, scale2, -16));
7292       lea(str1, Address(str1, cnt2, scale1, -16));
7293     }
7294     subl(cnt1, cnt2);
7295     movl(cnt2, stride);
7296     addl(cnt1, stride);
7297     bind(CONT_SCAN_SUBSTR);
7298     if (ae == StrIntrinsicNode::UL) {
7299       pmovzxbw(vec, Address(str2, 0));
7300     } else {
7301       movdqu(vec, Address(str2, 0));
7302     }
7303     jmp(SCAN_SUBSTR);
7304 
7305     bind(RET_FOUND_LONG);
7306     movptr(str1, Address(rsp, wordSize));
7307   } // non constant
7308 
7309   bind(RET_FOUND);
7310   // Compute substr offset
7311   subptr(result, str1);
7312   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7313     shrl(result, 1); // index
7314   }
7315   bind(CLEANUP);
7316   pop(rsp); // restore SP
7317 
7318 } // string_indexof
7319 
7320 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7321                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7322   ShortBranchVerifier sbv(this);
7323   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7324 
7325   int stride = 8;
7326 
7327   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7328         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7329         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7330         FOUND_SEQ_CHAR, DONE_LABEL;
7331 
7332   movptr(result, str1);
7333   if (UseAVX >= 2) {
7334     cmpl(cnt1, stride);
7335     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7336     cmpl(cnt1, 2*stride);
7337     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7338     movdl(vec1, ch);
7339     vpbroadcastw(vec1, vec1);
7340     vpxor(vec2, vec2);
7341     movl(tmp, cnt1);
7342     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7343     andl(cnt1,0x0000000F);  //tail count (in chars)
7344 
7345     bind(SCAN_TO_16_CHAR_LOOP);
7346     vmovdqu(vec3, Address(result, 0));
7347     vpcmpeqw(vec3, vec3, vec1, 1);
7348     vptest(vec2, vec3);
7349     jcc(Assembler::carryClear, FOUND_CHAR);
7350     addptr(result, 32);
7351     subl(tmp, 2*stride);
7352     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7353     jmp(SCAN_TO_8_CHAR);
7354     bind(SCAN_TO_8_CHAR_INIT);
7355     movdl(vec1, ch);
7356     pshuflw(vec1, vec1, 0x00);
7357     pshufd(vec1, vec1, 0);
7358     pxor(vec2, vec2);
7359   }
7360   bind(SCAN_TO_8_CHAR);
7361   cmpl(cnt1, stride);
7362   if (UseAVX >= 2) {
7363     jcc(Assembler::less, SCAN_TO_CHAR);
7364   } else {
7365     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7366     movdl(vec1, ch);
7367     pshuflw(vec1, vec1, 0x00);
7368     pshufd(vec1, vec1, 0);
7369     pxor(vec2, vec2);
7370   }
7371   movl(tmp, cnt1);
7372   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7373   andl(cnt1,0x00000007);  //tail count (in chars)
7374 
7375   bind(SCAN_TO_8_CHAR_LOOP);
7376   movdqu(vec3, Address(result, 0));
7377   pcmpeqw(vec3, vec1);
7378   ptest(vec2, vec3);
7379   jcc(Assembler::carryClear, FOUND_CHAR);
7380   addptr(result, 16);
7381   subl(tmp, stride);
7382   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7383   bind(SCAN_TO_CHAR);
7384   testl(cnt1, cnt1);
7385   jcc(Assembler::zero, RET_NOT_FOUND);
7386   bind(SCAN_TO_CHAR_LOOP);
7387   load_unsigned_short(tmp, Address(result, 0));
7388   cmpl(ch, tmp);
7389   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7390   addptr(result, 2);
7391   subl(cnt1, 1);
7392   jccb(Assembler::zero, RET_NOT_FOUND);
7393   jmp(SCAN_TO_CHAR_LOOP);
7394 
7395   bind(RET_NOT_FOUND);
7396   movl(result, -1);
7397   jmpb(DONE_LABEL);
7398 
7399   bind(FOUND_CHAR);
7400   if (UseAVX >= 2) {
7401     vpmovmskb(tmp, vec3);
7402   } else {
7403     pmovmskb(tmp, vec3);
7404   }
7405   bsfl(ch, tmp);
7406   addl(result, ch);
7407 
7408   bind(FOUND_SEQ_CHAR);
7409   subptr(result, str1);
7410   shrl(result, 1);
7411 
7412   bind(DONE_LABEL);
7413 } // string_indexof_char
7414 
7415 // helper function for string_compare
7416 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7417                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7418                                         Address::ScaleFactor scale2, Register index, int ae) {
7419   if (ae == StrIntrinsicNode::LL) {
7420     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7421     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7422   } else if (ae == StrIntrinsicNode::UU) {
7423     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7424     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7425   } else {
7426     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7427     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7428   }
7429 }
7430 
7431 // Compare strings, used for char[] and byte[].
7432 void MacroAssembler::string_compare(Register str1, Register str2,
7433                                     Register cnt1, Register cnt2, Register result,
7434                                     XMMRegister vec1, int ae) {
7435   ShortBranchVerifier sbv(this);
7436   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7437   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7438   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7439   int stride2x2 = 0x40;
7440   Address::ScaleFactor scale = Address::no_scale;
7441   Address::ScaleFactor scale1 = Address::no_scale;
7442   Address::ScaleFactor scale2 = Address::no_scale;
7443 
7444   if (ae != StrIntrinsicNode::LL) {
7445     stride2x2 = 0x20;
7446   }
7447 
7448   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7449     shrl(cnt2, 1);
7450   }
7451   // Compute the minimum of the string lengths and the
7452   // difference of the string lengths (stack).
7453   // Do the conditional move stuff
7454   movl(result, cnt1);
7455   subl(cnt1, cnt2);
7456   push(cnt1);
7457   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7458 
7459   // Is the minimum length zero?
7460   testl(cnt2, cnt2);
7461   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7462   if (ae == StrIntrinsicNode::LL) {
7463     // Load first bytes
7464     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7465     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7466   } else if (ae == StrIntrinsicNode::UU) {
7467     // Load first characters
7468     load_unsigned_short(result, Address(str1, 0));
7469     load_unsigned_short(cnt1, Address(str2, 0));
7470   } else {
7471     load_unsigned_byte(result, Address(str1, 0));
7472     load_unsigned_short(cnt1, Address(str2, 0));
7473   }
7474   subl(result, cnt1);
7475   jcc(Assembler::notZero,  POP_LABEL);
7476 
7477   if (ae == StrIntrinsicNode::UU) {
7478     // Divide length by 2 to get number of chars
7479     shrl(cnt2, 1);
7480   }
7481   cmpl(cnt2, 1);
7482   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7483 
7484   // Check if the strings start at the same location and setup scale and stride
7485   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7486     cmpptr(str1, str2);
7487     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7488     if (ae == StrIntrinsicNode::LL) {
7489       scale = Address::times_1;
7490       stride = 16;
7491     } else {
7492       scale = Address::times_2;
7493       stride = 8;
7494     }
7495   } else {
7496     scale1 = Address::times_1;
7497     scale2 = Address::times_2;
7498     // scale not used
7499     stride = 8;
7500   }
7501 
7502   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7503     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7504     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7505     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7506     Label COMPARE_TAIL_LONG;
7507     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7508 
7509     int pcmpmask = 0x19;
7510     if (ae == StrIntrinsicNode::LL) {
7511       pcmpmask &= ~0x01;
7512     }
7513 
7514     // Setup to compare 16-chars (32-bytes) vectors,
7515     // start from first character again because it has aligned address.
7516     if (ae == StrIntrinsicNode::LL) {
7517       stride2 = 32;
7518     } else {
7519       stride2 = 16;
7520     }
7521     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7522       adr_stride = stride << scale;
7523     } else {
7524       adr_stride1 = 8;  //stride << scale1;
7525       adr_stride2 = 16; //stride << scale2;
7526     }
7527 
7528     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7529     // rax and rdx are used by pcmpestri as elements counters
7530     movl(result, cnt2);
7531     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7532     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7533 
7534     // fast path : compare first 2 8-char vectors.
7535     bind(COMPARE_16_CHARS);
7536     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7537       movdqu(vec1, Address(str1, 0));
7538     } else {
7539       pmovzxbw(vec1, Address(str1, 0));
7540     }
7541     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7542     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7543 
7544     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7545       movdqu(vec1, Address(str1, adr_stride));
7546       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7547     } else {
7548       pmovzxbw(vec1, Address(str1, adr_stride1));
7549       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7550     }
7551     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7552     addl(cnt1, stride);
7553 
7554     // Compare the characters at index in cnt1
7555     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7556     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7557     subl(result, cnt2);
7558     jmp(POP_LABEL);
7559 
7560     // Setup the registers to start vector comparison loop
7561     bind(COMPARE_WIDE_VECTORS);
7562     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7563       lea(str1, Address(str1, result, scale));
7564       lea(str2, Address(str2, result, scale));
7565     } else {
7566       lea(str1, Address(str1, result, scale1));
7567       lea(str2, Address(str2, result, scale2));
7568     }
7569     subl(result, stride2);
7570     subl(cnt2, stride2);
7571     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7572     negptr(result);
7573 
7574     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7575     bind(COMPARE_WIDE_VECTORS_LOOP);
7576 
7577 #ifdef _LP64
7578     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7579       cmpl(cnt2, stride2x2);
7580       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7581       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7582       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7583 
7584       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7585       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7586         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7587         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7588       } else {
7589         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7590         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7591       }
7592       kortestql(k7, k7);
7593       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7594       addptr(result, stride2x2);  // update since we already compared at this addr
7595       subl(cnt2, stride2x2);      // and sub the size too
7596       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7597 
7598       vpxor(vec1, vec1);
7599       jmpb(COMPARE_WIDE_TAIL);
7600     }//if (VM_Version::supports_avx512vlbw())
7601 #endif // _LP64
7602 
7603 
7604     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7605     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7606       vmovdqu(vec1, Address(str1, result, scale));
7607       vpxor(vec1, Address(str2, result, scale));
7608     } else {
7609       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7610       vpxor(vec1, Address(str2, result, scale2));
7611     }
7612     vptest(vec1, vec1);
7613     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7614     addptr(result, stride2);
7615     subl(cnt2, stride2);
7616     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7617     // clean upper bits of YMM registers
7618     vpxor(vec1, vec1);
7619 
7620     // compare wide vectors tail
7621     bind(COMPARE_WIDE_TAIL);
7622     testptr(result, result);
7623     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7624 
7625     movl(result, stride2);
7626     movl(cnt2, result);
7627     negptr(result);
7628     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7629 
7630     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7631     bind(VECTOR_NOT_EQUAL);
7632     // clean upper bits of YMM registers
7633     vpxor(vec1, vec1);
7634     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7635       lea(str1, Address(str1, result, scale));
7636       lea(str2, Address(str2, result, scale));
7637     } else {
7638       lea(str1, Address(str1, result, scale1));
7639       lea(str2, Address(str2, result, scale2));
7640     }
7641     jmp(COMPARE_16_CHARS);
7642 
7643     // Compare tail chars, length between 1 to 15 chars
7644     bind(COMPARE_TAIL_LONG);
7645     movl(cnt2, result);
7646     cmpl(cnt2, stride);
7647     jcc(Assembler::less, COMPARE_SMALL_STR);
7648 
7649     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7650       movdqu(vec1, Address(str1, 0));
7651     } else {
7652       pmovzxbw(vec1, Address(str1, 0));
7653     }
7654     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7655     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7656     subptr(cnt2, stride);
7657     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7658     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7659       lea(str1, Address(str1, result, scale));
7660       lea(str2, Address(str2, result, scale));
7661     } else {
7662       lea(str1, Address(str1, result, scale1));
7663       lea(str2, Address(str2, result, scale2));
7664     }
7665     negptr(cnt2);
7666     jmpb(WHILE_HEAD_LABEL);
7667 
7668     bind(COMPARE_SMALL_STR);
7669   } else if (UseSSE42Intrinsics) {
7670     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7671     int pcmpmask = 0x19;
7672     // Setup to compare 8-char (16-byte) vectors,
7673     // start from first character again because it has aligned address.
7674     movl(result, cnt2);
7675     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7676     if (ae == StrIntrinsicNode::LL) {
7677       pcmpmask &= ~0x01;
7678     }
7679     jcc(Assembler::zero, COMPARE_TAIL);
7680     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7681       lea(str1, Address(str1, result, scale));
7682       lea(str2, Address(str2, result, scale));
7683     } else {
7684       lea(str1, Address(str1, result, scale1));
7685       lea(str2, Address(str2, result, scale2));
7686     }
7687     negptr(result);
7688 
7689     // pcmpestri
7690     //   inputs:
7691     //     vec1- substring
7692     //     rax - negative string length (elements count)
7693     //     mem - scanned string
7694     //     rdx - string length (elements count)
7695     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7696     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7697     //   outputs:
7698     //     rcx - first mismatched element index
7699     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7700 
7701     bind(COMPARE_WIDE_VECTORS);
7702     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7703       movdqu(vec1, Address(str1, result, scale));
7704       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7705     } else {
7706       pmovzxbw(vec1, Address(str1, result, scale1));
7707       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7708     }
7709     // After pcmpestri cnt1(rcx) contains mismatched element index
7710 
7711     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7712     addptr(result, stride);
7713     subptr(cnt2, stride);
7714     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7715 
7716     // compare wide vectors tail
7717     testptr(result, result);
7718     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7719 
7720     movl(cnt2, stride);
7721     movl(result, stride);
7722     negptr(result);
7723     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7724       movdqu(vec1, Address(str1, result, scale));
7725       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7726     } else {
7727       pmovzxbw(vec1, Address(str1, result, scale1));
7728       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7729     }
7730     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7731 
7732     // Mismatched characters in the vectors
7733     bind(VECTOR_NOT_EQUAL);
7734     addptr(cnt1, result);
7735     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7736     subl(result, cnt2);
7737     jmpb(POP_LABEL);
7738 
7739     bind(COMPARE_TAIL); // limit is zero
7740     movl(cnt2, result);
7741     // Fallthru to tail compare
7742   }
7743   // Shift str2 and str1 to the end of the arrays, negate min
7744   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7745     lea(str1, Address(str1, cnt2, scale));
7746     lea(str2, Address(str2, cnt2, scale));
7747   } else {
7748     lea(str1, Address(str1, cnt2, scale1));
7749     lea(str2, Address(str2, cnt2, scale2));
7750   }
7751   decrementl(cnt2);  // first character was compared already
7752   negptr(cnt2);
7753 
7754   // Compare the rest of the elements
7755   bind(WHILE_HEAD_LABEL);
7756   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7757   subl(result, cnt1);
7758   jccb(Assembler::notZero, POP_LABEL);
7759   increment(cnt2);
7760   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7761 
7762   // Strings are equal up to min length.  Return the length difference.
7763   bind(LENGTH_DIFF_LABEL);
7764   pop(result);
7765   if (ae == StrIntrinsicNode::UU) {
7766     // Divide diff by 2 to get number of chars
7767     sarl(result, 1);
7768   }
7769   jmpb(DONE_LABEL);
7770 
7771 #ifdef _LP64
7772   if (VM_Version::supports_avx512vlbw()) {
7773 
7774     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7775 
7776     kmovql(cnt1, k7);
7777     notq(cnt1);
7778     bsfq(cnt2, cnt1);
7779     if (ae != StrIntrinsicNode::LL) {
7780       // Divide diff by 2 to get number of chars
7781       sarl(cnt2, 1);
7782     }
7783     addq(result, cnt2);
7784     if (ae == StrIntrinsicNode::LL) {
7785       load_unsigned_byte(cnt1, Address(str2, result));
7786       load_unsigned_byte(result, Address(str1, result));
7787     } else if (ae == StrIntrinsicNode::UU) {
7788       load_unsigned_short(cnt1, Address(str2, result, scale));
7789       load_unsigned_short(result, Address(str1, result, scale));
7790     } else {
7791       load_unsigned_short(cnt1, Address(str2, result, scale2));
7792       load_unsigned_byte(result, Address(str1, result, scale1));
7793     }
7794     subl(result, cnt1);
7795     jmpb(POP_LABEL);
7796   }//if (VM_Version::supports_avx512vlbw())
7797 #endif // _LP64
7798 
7799   // Discard the stored length difference
7800   bind(POP_LABEL);
7801   pop(cnt1);
7802 
7803   // That's it
7804   bind(DONE_LABEL);
7805   if(ae == StrIntrinsicNode::UL) {
7806     negl(result);
7807   }
7808 
7809 }
7810 
7811 // Search for Non-ASCII character (Negative byte value) in a byte array,
7812 // return true if it has any and false otherwise.
7813 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7814 //   @HotSpotIntrinsicCandidate
7815 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7816 //     for (int i = off; i < off + len; i++) {
7817 //       if (ba[i] < 0) {
7818 //         return true;
7819 //       }
7820 //     }
7821 //     return false;
7822 //   }
7823 void MacroAssembler::has_negatives(Register ary1, Register len,
7824   Register result, Register tmp1,
7825   XMMRegister vec1, XMMRegister vec2) {
7826   // rsi: byte array
7827   // rcx: len
7828   // rax: result
7829   ShortBranchVerifier sbv(this);
7830   assert_different_registers(ary1, len, result, tmp1);
7831   assert_different_registers(vec1, vec2);
7832   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7833 
7834   // len == 0
7835   testl(len, len);
7836   jcc(Assembler::zero, FALSE_LABEL);
7837 
7838   if ((UseAVX > 2) && // AVX512
7839     VM_Version::supports_avx512vlbw() &&
7840     VM_Version::supports_bmi2()) {
7841 
7842     set_vector_masking();  // opening of the stub context for programming mask registers
7843 
7844     Label test_64_loop, test_tail;
7845     Register tmp3_aliased = len;
7846 
7847     movl(tmp1, len);
7848     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7849 
7850     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7851     andl(len, ~(64 - 1));    // vector count (in chars)
7852     jccb(Assembler::zero, test_tail);
7853 
7854     lea(ary1, Address(ary1, len, Address::times_1));
7855     negptr(len);
7856 
7857     bind(test_64_loop);
7858     // Check whether our 64 elements of size byte contain negatives
7859     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7860     kortestql(k2, k2);
7861     jcc(Assembler::notZero, TRUE_LABEL);
7862 
7863     addptr(len, 64);
7864     jccb(Assembler::notZero, test_64_loop);
7865 
7866 
7867     bind(test_tail);
7868     // bail out when there is nothing to be done
7869     testl(tmp1, -1);
7870     jcc(Assembler::zero, FALSE_LABEL);
7871 
7872     // Save k1
7873     kmovql(k3, k1);
7874 
7875     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7876 #ifdef _LP64
7877     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7878     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7879     notq(tmp3_aliased);
7880     kmovql(k1, tmp3_aliased);
7881 #else
7882     Label k_init;
7883     jmp(k_init);
7884 
7885     // We could not read 64-bits from a general purpose register thus we move
7886     // data required to compose 64 1's to the instruction stream
7887     // We emit 64 byte wide series of elements from 0..63 which later on would
7888     // be used as a compare targets with tail count contained in tmp1 register.
7889     // Result would be a k1 register having tmp1 consecutive number or 1
7890     // counting from least significant bit.
7891     address tmp = pc();
7892     emit_int64(0x0706050403020100);
7893     emit_int64(0x0F0E0D0C0B0A0908);
7894     emit_int64(0x1716151413121110);
7895     emit_int64(0x1F1E1D1C1B1A1918);
7896     emit_int64(0x2726252423222120);
7897     emit_int64(0x2F2E2D2C2B2A2928);
7898     emit_int64(0x3736353433323130);
7899     emit_int64(0x3F3E3D3C3B3A3938);
7900 
7901     bind(k_init);
7902     lea(len, InternalAddress(tmp));
7903     // create mask to test for negative byte inside a vector
7904     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7905     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7906 
7907 #endif
7908     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7909     ktestq(k2, k1);
7910     // Restore k1
7911     kmovql(k1, k3);
7912     jcc(Assembler::notZero, TRUE_LABEL);
7913 
7914     jmp(FALSE_LABEL);
7915 
7916     clear_vector_masking();   // closing of the stub context for programming mask registers
7917   } else {
7918     movl(result, len); // copy
7919 
7920     if (UseAVX == 2 && UseSSE >= 2) {
7921       // With AVX2, use 32-byte vector compare
7922       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7923 
7924       // Compare 32-byte vectors
7925       andl(result, 0x0000001f);  //   tail count (in bytes)
7926       andl(len, 0xffffffe0);   // vector count (in bytes)
7927       jccb(Assembler::zero, COMPARE_TAIL);
7928 
7929       lea(ary1, Address(ary1, len, Address::times_1));
7930       negptr(len);
7931 
7932       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
7933       movdl(vec2, tmp1);
7934       vpbroadcastd(vec2, vec2);
7935 
7936       bind(COMPARE_WIDE_VECTORS);
7937       vmovdqu(vec1, Address(ary1, len, Address::times_1));
7938       vptest(vec1, vec2);
7939       jccb(Assembler::notZero, TRUE_LABEL);
7940       addptr(len, 32);
7941       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7942 
7943       testl(result, result);
7944       jccb(Assembler::zero, FALSE_LABEL);
7945 
7946       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7947       vptest(vec1, vec2);
7948       jccb(Assembler::notZero, TRUE_LABEL);
7949       jmpb(FALSE_LABEL);
7950 
7951       bind(COMPARE_TAIL); // len is zero
7952       movl(len, result);
7953       // Fallthru to tail compare
7954     } else if (UseSSE42Intrinsics) {
7955       // With SSE4.2, use double quad vector compare
7956       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7957 
7958       // Compare 16-byte vectors
7959       andl(result, 0x0000000f);  //   tail count (in bytes)
7960       andl(len, 0xfffffff0);   // vector count (in bytes)
7961       jccb(Assembler::zero, COMPARE_TAIL);
7962 
7963       lea(ary1, Address(ary1, len, Address::times_1));
7964       negptr(len);
7965 
7966       movl(tmp1, 0x80808080);
7967       movdl(vec2, tmp1);
7968       pshufd(vec2, vec2, 0);
7969 
7970       bind(COMPARE_WIDE_VECTORS);
7971       movdqu(vec1, Address(ary1, len, Address::times_1));
7972       ptest(vec1, vec2);
7973       jccb(Assembler::notZero, TRUE_LABEL);
7974       addptr(len, 16);
7975       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7976 
7977       testl(result, result);
7978       jccb(Assembler::zero, FALSE_LABEL);
7979 
7980       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7981       ptest(vec1, vec2);
7982       jccb(Assembler::notZero, TRUE_LABEL);
7983       jmpb(FALSE_LABEL);
7984 
7985       bind(COMPARE_TAIL); // len is zero
7986       movl(len, result);
7987       // Fallthru to tail compare
7988     }
7989   }
7990   // Compare 4-byte vectors
7991   andl(len, 0xfffffffc); // vector count (in bytes)
7992   jccb(Assembler::zero, COMPARE_CHAR);
7993 
7994   lea(ary1, Address(ary1, len, Address::times_1));
7995   negptr(len);
7996 
7997   bind(COMPARE_VECTORS);
7998   movl(tmp1, Address(ary1, len, Address::times_1));
7999   andl(tmp1, 0x80808080);
8000   jccb(Assembler::notZero, TRUE_LABEL);
8001   addptr(len, 4);
8002   jcc(Assembler::notZero, COMPARE_VECTORS);
8003 
8004   // Compare trailing char (final 2 bytes), if any
8005   bind(COMPARE_CHAR);
8006   testl(result, 0x2);   // tail  char
8007   jccb(Assembler::zero, COMPARE_BYTE);
8008   load_unsigned_short(tmp1, Address(ary1, 0));
8009   andl(tmp1, 0x00008080);
8010   jccb(Assembler::notZero, TRUE_LABEL);
8011   subptr(result, 2);
8012   lea(ary1, Address(ary1, 2));
8013 
8014   bind(COMPARE_BYTE);
8015   testl(result, 0x1);   // tail  byte
8016   jccb(Assembler::zero, FALSE_LABEL);
8017   load_unsigned_byte(tmp1, Address(ary1, 0));
8018   andl(tmp1, 0x00000080);
8019   jccb(Assembler::notEqual, TRUE_LABEL);
8020   jmpb(FALSE_LABEL);
8021 
8022   bind(TRUE_LABEL);
8023   movl(result, 1);   // return true
8024   jmpb(DONE);
8025 
8026   bind(FALSE_LABEL);
8027   xorl(result, result); // return false
8028 
8029   // That's it
8030   bind(DONE);
8031   if (UseAVX >= 2 && UseSSE >= 2) {
8032     // clean upper bits of YMM registers
8033     vpxor(vec1, vec1);
8034     vpxor(vec2, vec2);
8035   }
8036 }
8037 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8038 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8039                                    Register limit, Register result, Register chr,
8040                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8041   ShortBranchVerifier sbv(this);
8042   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8043 
8044   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8045   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8046 
8047   if (is_array_equ) {
8048     // Check the input args
8049     cmpoop(ary1, ary2);
8050     jcc(Assembler::equal, TRUE_LABEL);
8051 
8052     // Need additional checks for arrays_equals.
8053     testptr(ary1, ary1);
8054     jcc(Assembler::zero, FALSE_LABEL);
8055     testptr(ary2, ary2);
8056     jcc(Assembler::zero, FALSE_LABEL);
8057 
8058     // Check the lengths
8059     movl(limit, Address(ary1, length_offset));
8060     cmpl(limit, Address(ary2, length_offset));
8061     jcc(Assembler::notEqual, FALSE_LABEL);
8062   }
8063 
8064   // count == 0
8065   testl(limit, limit);
8066   jcc(Assembler::zero, TRUE_LABEL);
8067 
8068   if (is_array_equ) {
8069     // Load array address
8070     lea(ary1, Address(ary1, base_offset));
8071     lea(ary2, Address(ary2, base_offset));
8072   }
8073 
8074   if (is_array_equ && is_char) {
8075     // arrays_equals when used for char[].
8076     shll(limit, 1);      // byte count != 0
8077   }
8078   movl(result, limit); // copy
8079 
8080   if (UseAVX >= 2) {
8081     // With AVX2, use 32-byte vector compare
8082     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8083 
8084     // Compare 32-byte vectors
8085     andl(result, 0x0000001f);  //   tail count (in bytes)
8086     andl(limit, 0xffffffe0);   // vector count (in bytes)
8087     jcc(Assembler::zero, COMPARE_TAIL);
8088 
8089     lea(ary1, Address(ary1, limit, Address::times_1));
8090     lea(ary2, Address(ary2, limit, Address::times_1));
8091     negptr(limit);
8092 
8093     bind(COMPARE_WIDE_VECTORS);
8094 
8095 #ifdef _LP64
8096     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8097       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8098 
8099       cmpl(limit, -64);
8100       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8101 
8102       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8103 
8104       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8105       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8106       kortestql(k7, k7);
8107       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8108       addptr(limit, 64);  // update since we already compared at this addr
8109       cmpl(limit, -64);
8110       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8111 
8112       // At this point we may still need to compare -limit+result bytes.
8113       // We could execute the next two instruction and just continue via non-wide path:
8114       //  cmpl(limit, 0);
8115       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8116       // But since we stopped at the points ary{1,2}+limit which are
8117       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8118       // (|limit| <= 32 and result < 32),
8119       // we may just compare the last 64 bytes.
8120       //
8121       addptr(result, -64);   // it is safe, bc we just came from this area
8122       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8123       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8124       kortestql(k7, k7);
8125       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8126 
8127       jmp(TRUE_LABEL);
8128 
8129       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8130 
8131     }//if (VM_Version::supports_avx512vlbw())
8132 #endif //_LP64
8133 
8134     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8135     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8136     vpxor(vec1, vec2);
8137 
8138     vptest(vec1, vec1);
8139     jcc(Assembler::notZero, FALSE_LABEL);
8140     addptr(limit, 32);
8141     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8142 
8143     testl(result, result);
8144     jcc(Assembler::zero, TRUE_LABEL);
8145 
8146     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8147     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8148     vpxor(vec1, vec2);
8149 
8150     vptest(vec1, vec1);
8151     jccb(Assembler::notZero, FALSE_LABEL);
8152     jmpb(TRUE_LABEL);
8153 
8154     bind(COMPARE_TAIL); // limit is zero
8155     movl(limit, result);
8156     // Fallthru to tail compare
8157   } else if (UseSSE42Intrinsics) {
8158     // With SSE4.2, use double quad vector compare
8159     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8160 
8161     // Compare 16-byte vectors
8162     andl(result, 0x0000000f);  //   tail count (in bytes)
8163     andl(limit, 0xfffffff0);   // vector count (in bytes)
8164     jcc(Assembler::zero, COMPARE_TAIL);
8165 
8166     lea(ary1, Address(ary1, limit, Address::times_1));
8167     lea(ary2, Address(ary2, limit, Address::times_1));
8168     negptr(limit);
8169 
8170     bind(COMPARE_WIDE_VECTORS);
8171     movdqu(vec1, Address(ary1, limit, Address::times_1));
8172     movdqu(vec2, Address(ary2, limit, Address::times_1));
8173     pxor(vec1, vec2);
8174 
8175     ptest(vec1, vec1);
8176     jcc(Assembler::notZero, FALSE_LABEL);
8177     addptr(limit, 16);
8178     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8179 
8180     testl(result, result);
8181     jcc(Assembler::zero, TRUE_LABEL);
8182 
8183     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8184     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8185     pxor(vec1, vec2);
8186 
8187     ptest(vec1, vec1);
8188     jccb(Assembler::notZero, FALSE_LABEL);
8189     jmpb(TRUE_LABEL);
8190 
8191     bind(COMPARE_TAIL); // limit is zero
8192     movl(limit, result);
8193     // Fallthru to tail compare
8194   }
8195 
8196   // Compare 4-byte vectors
8197   andl(limit, 0xfffffffc); // vector count (in bytes)
8198   jccb(Assembler::zero, COMPARE_CHAR);
8199 
8200   lea(ary1, Address(ary1, limit, Address::times_1));
8201   lea(ary2, Address(ary2, limit, Address::times_1));
8202   negptr(limit);
8203 
8204   bind(COMPARE_VECTORS);
8205   movl(chr, Address(ary1, limit, Address::times_1));
8206   cmpl(chr, Address(ary2, limit, Address::times_1));
8207   jccb(Assembler::notEqual, FALSE_LABEL);
8208   addptr(limit, 4);
8209   jcc(Assembler::notZero, COMPARE_VECTORS);
8210 
8211   // Compare trailing char (final 2 bytes), if any
8212   bind(COMPARE_CHAR);
8213   testl(result, 0x2);   // tail  char
8214   jccb(Assembler::zero, COMPARE_BYTE);
8215   load_unsigned_short(chr, Address(ary1, 0));
8216   load_unsigned_short(limit, Address(ary2, 0));
8217   cmpl(chr, limit);
8218   jccb(Assembler::notEqual, FALSE_LABEL);
8219 
8220   if (is_array_equ && is_char) {
8221     bind(COMPARE_BYTE);
8222   } else {
8223     lea(ary1, Address(ary1, 2));
8224     lea(ary2, Address(ary2, 2));
8225 
8226     bind(COMPARE_BYTE);
8227     testl(result, 0x1);   // tail  byte
8228     jccb(Assembler::zero, TRUE_LABEL);
8229     load_unsigned_byte(chr, Address(ary1, 0));
8230     load_unsigned_byte(limit, Address(ary2, 0));
8231     cmpl(chr, limit);
8232     jccb(Assembler::notEqual, FALSE_LABEL);
8233   }
8234   bind(TRUE_LABEL);
8235   movl(result, 1);   // return true
8236   jmpb(DONE);
8237 
8238   bind(FALSE_LABEL);
8239   xorl(result, result); // return false
8240 
8241   // That's it
8242   bind(DONE);
8243   if (UseAVX >= 2) {
8244     // clean upper bits of YMM registers
8245     vpxor(vec1, vec1);
8246     vpxor(vec2, vec2);
8247   }
8248 }
8249 
8250 #endif
8251 
8252 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8253                                    Register to, Register value, Register count,
8254                                    Register rtmp, XMMRegister xtmp) {
8255   ShortBranchVerifier sbv(this);
8256   assert_different_registers(to, value, count, rtmp);
8257   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8258   Label L_fill_2_bytes, L_fill_4_bytes;
8259 
8260   int shift = -1;
8261   switch (t) {
8262     case T_BYTE:
8263       shift = 2;
8264       break;
8265     case T_SHORT:
8266       shift = 1;
8267       break;
8268     case T_INT:
8269       shift = 0;
8270       break;
8271     default: ShouldNotReachHere();
8272   }
8273 
8274   if (t == T_BYTE) {
8275     andl(value, 0xff);
8276     movl(rtmp, value);
8277     shll(rtmp, 8);
8278     orl(value, rtmp);
8279   }
8280   if (t == T_SHORT) {
8281     andl(value, 0xffff);
8282   }
8283   if (t == T_BYTE || t == T_SHORT) {
8284     movl(rtmp, value);
8285     shll(rtmp, 16);
8286     orl(value, rtmp);
8287   }
8288 
8289   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8290   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8291   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8292     // align source address at 4 bytes address boundary
8293     if (t == T_BYTE) {
8294       // One byte misalignment happens only for byte arrays
8295       testptr(to, 1);
8296       jccb(Assembler::zero, L_skip_align1);
8297       movb(Address(to, 0), value);
8298       increment(to);
8299       decrement(count);
8300       BIND(L_skip_align1);
8301     }
8302     // Two bytes misalignment happens only for byte and short (char) arrays
8303     testptr(to, 2);
8304     jccb(Assembler::zero, L_skip_align2);
8305     movw(Address(to, 0), value);
8306     addptr(to, 2);
8307     subl(count, 1<<(shift-1));
8308     BIND(L_skip_align2);
8309   }
8310   if (UseSSE < 2) {
8311     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8312     // Fill 32-byte chunks
8313     subl(count, 8 << shift);
8314     jcc(Assembler::less, L_check_fill_8_bytes);
8315     align(16);
8316 
8317     BIND(L_fill_32_bytes_loop);
8318 
8319     for (int i = 0; i < 32; i += 4) {
8320       movl(Address(to, i), value);
8321     }
8322 
8323     addptr(to, 32);
8324     subl(count, 8 << shift);
8325     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8326     BIND(L_check_fill_8_bytes);
8327     addl(count, 8 << shift);
8328     jccb(Assembler::zero, L_exit);
8329     jmpb(L_fill_8_bytes);
8330 
8331     //
8332     // length is too short, just fill qwords
8333     //
8334     BIND(L_fill_8_bytes_loop);
8335     movl(Address(to, 0), value);
8336     movl(Address(to, 4), value);
8337     addptr(to, 8);
8338     BIND(L_fill_8_bytes);
8339     subl(count, 1 << (shift + 1));
8340     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8341     // fall through to fill 4 bytes
8342   } else {
8343     Label L_fill_32_bytes;
8344     if (!UseUnalignedLoadStores) {
8345       // align to 8 bytes, we know we are 4 byte aligned to start
8346       testptr(to, 4);
8347       jccb(Assembler::zero, L_fill_32_bytes);
8348       movl(Address(to, 0), value);
8349       addptr(to, 4);
8350       subl(count, 1<<shift);
8351     }
8352     BIND(L_fill_32_bytes);
8353     {
8354       assert( UseSSE >= 2, "supported cpu only" );
8355       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8356       if (UseAVX > 2) {
8357         movl(rtmp, 0xffff);
8358         kmovwl(k1, rtmp);
8359       }
8360       movdl(xtmp, value);
8361       if (UseAVX > 2 && UseUnalignedLoadStores) {
8362         // Fill 64-byte chunks
8363         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8364         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8365 
8366         subl(count, 16 << shift);
8367         jcc(Assembler::less, L_check_fill_32_bytes);
8368         align(16);
8369 
8370         BIND(L_fill_64_bytes_loop);
8371         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8372         addptr(to, 64);
8373         subl(count, 16 << shift);
8374         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8375 
8376         BIND(L_check_fill_32_bytes);
8377         addl(count, 8 << shift);
8378         jccb(Assembler::less, L_check_fill_8_bytes);
8379         vmovdqu(Address(to, 0), xtmp);
8380         addptr(to, 32);
8381         subl(count, 8 << shift);
8382 
8383         BIND(L_check_fill_8_bytes);
8384       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8385         // Fill 64-byte chunks
8386         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8387         vpbroadcastd(xtmp, xtmp);
8388 
8389         subl(count, 16 << shift);
8390         jcc(Assembler::less, L_check_fill_32_bytes);
8391         align(16);
8392 
8393         BIND(L_fill_64_bytes_loop);
8394         vmovdqu(Address(to, 0), xtmp);
8395         vmovdqu(Address(to, 32), xtmp);
8396         addptr(to, 64);
8397         subl(count, 16 << shift);
8398         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8399 
8400         BIND(L_check_fill_32_bytes);
8401         addl(count, 8 << shift);
8402         jccb(Assembler::less, L_check_fill_8_bytes);
8403         vmovdqu(Address(to, 0), xtmp);
8404         addptr(to, 32);
8405         subl(count, 8 << shift);
8406 
8407         BIND(L_check_fill_8_bytes);
8408         // clean upper bits of YMM registers
8409         movdl(xtmp, value);
8410         pshufd(xtmp, xtmp, 0);
8411       } else {
8412         // Fill 32-byte chunks
8413         pshufd(xtmp, xtmp, 0);
8414 
8415         subl(count, 8 << shift);
8416         jcc(Assembler::less, L_check_fill_8_bytes);
8417         align(16);
8418 
8419         BIND(L_fill_32_bytes_loop);
8420 
8421         if (UseUnalignedLoadStores) {
8422           movdqu(Address(to, 0), xtmp);
8423           movdqu(Address(to, 16), xtmp);
8424         } else {
8425           movq(Address(to, 0), xtmp);
8426           movq(Address(to, 8), xtmp);
8427           movq(Address(to, 16), xtmp);
8428           movq(Address(to, 24), xtmp);
8429         }
8430 
8431         addptr(to, 32);
8432         subl(count, 8 << shift);
8433         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8434 
8435         BIND(L_check_fill_8_bytes);
8436       }
8437       addl(count, 8 << shift);
8438       jccb(Assembler::zero, L_exit);
8439       jmpb(L_fill_8_bytes);
8440 
8441       //
8442       // length is too short, just fill qwords
8443       //
8444       BIND(L_fill_8_bytes_loop);
8445       movq(Address(to, 0), xtmp);
8446       addptr(to, 8);
8447       BIND(L_fill_8_bytes);
8448       subl(count, 1 << (shift + 1));
8449       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8450     }
8451   }
8452   // fill trailing 4 bytes
8453   BIND(L_fill_4_bytes);
8454   testl(count, 1<<shift);
8455   jccb(Assembler::zero, L_fill_2_bytes);
8456   movl(Address(to, 0), value);
8457   if (t == T_BYTE || t == T_SHORT) {
8458     addptr(to, 4);
8459     BIND(L_fill_2_bytes);
8460     // fill trailing 2 bytes
8461     testl(count, 1<<(shift-1));
8462     jccb(Assembler::zero, L_fill_byte);
8463     movw(Address(to, 0), value);
8464     if (t == T_BYTE) {
8465       addptr(to, 2);
8466       BIND(L_fill_byte);
8467       // fill trailing byte
8468       testl(count, 1);
8469       jccb(Assembler::zero, L_exit);
8470       movb(Address(to, 0), value);
8471     } else {
8472       BIND(L_fill_byte);
8473     }
8474   } else {
8475     BIND(L_fill_2_bytes);
8476   }
8477   BIND(L_exit);
8478 }
8479 
8480 // encode char[] to byte[] in ISO_8859_1
8481    //@HotSpotIntrinsicCandidate
8482    //private static int implEncodeISOArray(byte[] sa, int sp,
8483    //byte[] da, int dp, int len) {
8484    //  int i = 0;
8485    //  for (; i < len; i++) {
8486    //    char c = StringUTF16.getChar(sa, sp++);
8487    //    if (c > '\u00FF')
8488    //      break;
8489    //    da[dp++] = (byte)c;
8490    //  }
8491    //  return i;
8492    //}
8493 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8494   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8495   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8496   Register tmp5, Register result) {
8497 
8498   // rsi: src
8499   // rdi: dst
8500   // rdx: len
8501   // rcx: tmp5
8502   // rax: result
8503   ShortBranchVerifier sbv(this);
8504   assert_different_registers(src, dst, len, tmp5, result);
8505   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8506 
8507   // set result
8508   xorl(result, result);
8509   // check for zero length
8510   testl(len, len);
8511   jcc(Assembler::zero, L_done);
8512 
8513   movl(result, len);
8514 
8515   // Setup pointers
8516   lea(src, Address(src, len, Address::times_2)); // char[]
8517   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8518   negptr(len);
8519 
8520   if (UseSSE42Intrinsics || UseAVX >= 2) {
8521     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8522     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8523 
8524     if (UseAVX >= 2) {
8525       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8526       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8527       movdl(tmp1Reg, tmp5);
8528       vpbroadcastd(tmp1Reg, tmp1Reg);
8529       jmp(L_chars_32_check);
8530 
8531       bind(L_copy_32_chars);
8532       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8533       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8534       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8535       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8536       jccb(Assembler::notZero, L_copy_32_chars_exit);
8537       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8538       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8539       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8540 
8541       bind(L_chars_32_check);
8542       addptr(len, 32);
8543       jcc(Assembler::lessEqual, L_copy_32_chars);
8544 
8545       bind(L_copy_32_chars_exit);
8546       subptr(len, 16);
8547       jccb(Assembler::greater, L_copy_16_chars_exit);
8548 
8549     } else if (UseSSE42Intrinsics) {
8550       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8551       movdl(tmp1Reg, tmp5);
8552       pshufd(tmp1Reg, tmp1Reg, 0);
8553       jmpb(L_chars_16_check);
8554     }
8555 
8556     bind(L_copy_16_chars);
8557     if (UseAVX >= 2) {
8558       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8559       vptest(tmp2Reg, tmp1Reg);
8560       jcc(Assembler::notZero, L_copy_16_chars_exit);
8561       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8562       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8563     } else {
8564       if (UseAVX > 0) {
8565         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8566         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8567         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8568       } else {
8569         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8570         por(tmp2Reg, tmp3Reg);
8571         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8572         por(tmp2Reg, tmp4Reg);
8573       }
8574       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8575       jccb(Assembler::notZero, L_copy_16_chars_exit);
8576       packuswb(tmp3Reg, tmp4Reg);
8577     }
8578     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8579 
8580     bind(L_chars_16_check);
8581     addptr(len, 16);
8582     jcc(Assembler::lessEqual, L_copy_16_chars);
8583 
8584     bind(L_copy_16_chars_exit);
8585     if (UseAVX >= 2) {
8586       // clean upper bits of YMM registers
8587       vpxor(tmp2Reg, tmp2Reg);
8588       vpxor(tmp3Reg, tmp3Reg);
8589       vpxor(tmp4Reg, tmp4Reg);
8590       movdl(tmp1Reg, tmp5);
8591       pshufd(tmp1Reg, tmp1Reg, 0);
8592     }
8593     subptr(len, 8);
8594     jccb(Assembler::greater, L_copy_8_chars_exit);
8595 
8596     bind(L_copy_8_chars);
8597     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8598     ptest(tmp3Reg, tmp1Reg);
8599     jccb(Assembler::notZero, L_copy_8_chars_exit);
8600     packuswb(tmp3Reg, tmp1Reg);
8601     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8602     addptr(len, 8);
8603     jccb(Assembler::lessEqual, L_copy_8_chars);
8604 
8605     bind(L_copy_8_chars_exit);
8606     subptr(len, 8);
8607     jccb(Assembler::zero, L_done);
8608   }
8609 
8610   bind(L_copy_1_char);
8611   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8612   testl(tmp5, 0xff00);      // check if Unicode char
8613   jccb(Assembler::notZero, L_copy_1_char_exit);
8614   movb(Address(dst, len, Address::times_1, 0), tmp5);
8615   addptr(len, 1);
8616   jccb(Assembler::less, L_copy_1_char);
8617 
8618   bind(L_copy_1_char_exit);
8619   addptr(result, len); // len is negative count of not processed elements
8620 
8621   bind(L_done);
8622 }
8623 
8624 #ifdef _LP64
8625 /**
8626  * Helper for multiply_to_len().
8627  */
8628 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8629   addq(dest_lo, src1);
8630   adcq(dest_hi, 0);
8631   addq(dest_lo, src2);
8632   adcq(dest_hi, 0);
8633 }
8634 
8635 /**
8636  * Multiply 64 bit by 64 bit first loop.
8637  */
8638 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8639                                            Register y, Register y_idx, Register z,
8640                                            Register carry, Register product,
8641                                            Register idx, Register kdx) {
8642   //
8643   //  jlong carry, x[], y[], z[];
8644   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8645   //    huge_128 product = y[idx] * x[xstart] + carry;
8646   //    z[kdx] = (jlong)product;
8647   //    carry  = (jlong)(product >>> 64);
8648   //  }
8649   //  z[xstart] = carry;
8650   //
8651 
8652   Label L_first_loop, L_first_loop_exit;
8653   Label L_one_x, L_one_y, L_multiply;
8654 
8655   decrementl(xstart);
8656   jcc(Assembler::negative, L_one_x);
8657 
8658   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8659   rorq(x_xstart, 32); // convert big-endian to little-endian
8660 
8661   bind(L_first_loop);
8662   decrementl(idx);
8663   jcc(Assembler::negative, L_first_loop_exit);
8664   decrementl(idx);
8665   jcc(Assembler::negative, L_one_y);
8666   movq(y_idx, Address(y, idx, Address::times_4,  0));
8667   rorq(y_idx, 32); // convert big-endian to little-endian
8668   bind(L_multiply);
8669   movq(product, x_xstart);
8670   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8671   addq(product, carry);
8672   adcq(rdx, 0);
8673   subl(kdx, 2);
8674   movl(Address(z, kdx, Address::times_4,  4), product);
8675   shrq(product, 32);
8676   movl(Address(z, kdx, Address::times_4,  0), product);
8677   movq(carry, rdx);
8678   jmp(L_first_loop);
8679 
8680   bind(L_one_y);
8681   movl(y_idx, Address(y,  0));
8682   jmp(L_multiply);
8683 
8684   bind(L_one_x);
8685   movl(x_xstart, Address(x,  0));
8686   jmp(L_first_loop);
8687 
8688   bind(L_first_loop_exit);
8689 }
8690 
8691 /**
8692  * Multiply 64 bit by 64 bit and add 128 bit.
8693  */
8694 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8695                                             Register yz_idx, Register idx,
8696                                             Register carry, Register product, int offset) {
8697   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8698   //     z[kdx] = (jlong)product;
8699 
8700   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8701   rorq(yz_idx, 32); // convert big-endian to little-endian
8702   movq(product, x_xstart);
8703   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8704   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8705   rorq(yz_idx, 32); // convert big-endian to little-endian
8706 
8707   add2_with_carry(rdx, product, carry, yz_idx);
8708 
8709   movl(Address(z, idx, Address::times_4,  offset+4), product);
8710   shrq(product, 32);
8711   movl(Address(z, idx, Address::times_4,  offset), product);
8712 
8713 }
8714 
8715 /**
8716  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8717  */
8718 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8719                                              Register yz_idx, Register idx, Register jdx,
8720                                              Register carry, Register product,
8721                                              Register carry2) {
8722   //   jlong carry, x[], y[], z[];
8723   //   int kdx = ystart+1;
8724   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8725   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8726   //     z[kdx+idx+1] = (jlong)product;
8727   //     jlong carry2  = (jlong)(product >>> 64);
8728   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8729   //     z[kdx+idx] = (jlong)product;
8730   //     carry  = (jlong)(product >>> 64);
8731   //   }
8732   //   idx += 2;
8733   //   if (idx > 0) {
8734   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8735   //     z[kdx+idx] = (jlong)product;
8736   //     carry  = (jlong)(product >>> 64);
8737   //   }
8738   //
8739 
8740   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8741 
8742   movl(jdx, idx);
8743   andl(jdx, 0xFFFFFFFC);
8744   shrl(jdx, 2);
8745 
8746   bind(L_third_loop);
8747   subl(jdx, 1);
8748   jcc(Assembler::negative, L_third_loop_exit);
8749   subl(idx, 4);
8750 
8751   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8752   movq(carry2, rdx);
8753 
8754   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8755   movq(carry, rdx);
8756   jmp(L_third_loop);
8757 
8758   bind (L_third_loop_exit);
8759 
8760   andl (idx, 0x3);
8761   jcc(Assembler::zero, L_post_third_loop_done);
8762 
8763   Label L_check_1;
8764   subl(idx, 2);
8765   jcc(Assembler::negative, L_check_1);
8766 
8767   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8768   movq(carry, rdx);
8769 
8770   bind (L_check_1);
8771   addl (idx, 0x2);
8772   andl (idx, 0x1);
8773   subl(idx, 1);
8774   jcc(Assembler::negative, L_post_third_loop_done);
8775 
8776   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8777   movq(product, x_xstart);
8778   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8779   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8780 
8781   add2_with_carry(rdx, product, yz_idx, carry);
8782 
8783   movl(Address(z, idx, Address::times_4,  0), product);
8784   shrq(product, 32);
8785 
8786   shlq(rdx, 32);
8787   orq(product, rdx);
8788   movq(carry, product);
8789 
8790   bind(L_post_third_loop_done);
8791 }
8792 
8793 /**
8794  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8795  *
8796  */
8797 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8798                                                   Register carry, Register carry2,
8799                                                   Register idx, Register jdx,
8800                                                   Register yz_idx1, Register yz_idx2,
8801                                                   Register tmp, Register tmp3, Register tmp4) {
8802   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8803 
8804   //   jlong carry, x[], y[], z[];
8805   //   int kdx = ystart+1;
8806   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8807   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8808   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8809   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8810   //     carry  = (jlong)(tmp4 >>> 64);
8811   //     z[kdx+idx+1] = (jlong)tmp3;
8812   //     z[kdx+idx] = (jlong)tmp4;
8813   //   }
8814   //   idx += 2;
8815   //   if (idx > 0) {
8816   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8817   //     z[kdx+idx] = (jlong)yz_idx1;
8818   //     carry  = (jlong)(yz_idx1 >>> 64);
8819   //   }
8820   //
8821 
8822   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8823 
8824   movl(jdx, idx);
8825   andl(jdx, 0xFFFFFFFC);
8826   shrl(jdx, 2);
8827 
8828   bind(L_third_loop);
8829   subl(jdx, 1);
8830   jcc(Assembler::negative, L_third_loop_exit);
8831   subl(idx, 4);
8832 
8833   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8834   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8835   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8836   rorxq(yz_idx2, yz_idx2, 32);
8837 
8838   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8839   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8840 
8841   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8842   rorxq(yz_idx1, yz_idx1, 32);
8843   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8844   rorxq(yz_idx2, yz_idx2, 32);
8845 
8846   if (VM_Version::supports_adx()) {
8847     adcxq(tmp3, carry);
8848     adoxq(tmp3, yz_idx1);
8849 
8850     adcxq(tmp4, tmp);
8851     adoxq(tmp4, yz_idx2);
8852 
8853     movl(carry, 0); // does not affect flags
8854     adcxq(carry2, carry);
8855     adoxq(carry2, carry);
8856   } else {
8857     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8858     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8859   }
8860   movq(carry, carry2);
8861 
8862   movl(Address(z, idx, Address::times_4, 12), tmp3);
8863   shrq(tmp3, 32);
8864   movl(Address(z, idx, Address::times_4,  8), tmp3);
8865 
8866   movl(Address(z, idx, Address::times_4,  4), tmp4);
8867   shrq(tmp4, 32);
8868   movl(Address(z, idx, Address::times_4,  0), tmp4);
8869 
8870   jmp(L_third_loop);
8871 
8872   bind (L_third_loop_exit);
8873 
8874   andl (idx, 0x3);
8875   jcc(Assembler::zero, L_post_third_loop_done);
8876 
8877   Label L_check_1;
8878   subl(idx, 2);
8879   jcc(Assembler::negative, L_check_1);
8880 
8881   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8882   rorxq(yz_idx1, yz_idx1, 32);
8883   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8884   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8885   rorxq(yz_idx2, yz_idx2, 32);
8886 
8887   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8888 
8889   movl(Address(z, idx, Address::times_4,  4), tmp3);
8890   shrq(tmp3, 32);
8891   movl(Address(z, idx, Address::times_4,  0), tmp3);
8892   movq(carry, tmp4);
8893 
8894   bind (L_check_1);
8895   addl (idx, 0x2);
8896   andl (idx, 0x1);
8897   subl(idx, 1);
8898   jcc(Assembler::negative, L_post_third_loop_done);
8899   movl(tmp4, Address(y, idx, Address::times_4,  0));
8900   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8901   movl(tmp4, Address(z, idx, Address::times_4,  0));
8902 
8903   add2_with_carry(carry2, tmp3, tmp4, carry);
8904 
8905   movl(Address(z, idx, Address::times_4,  0), tmp3);
8906   shrq(tmp3, 32);
8907 
8908   shlq(carry2, 32);
8909   orq(tmp3, carry2);
8910   movq(carry, tmp3);
8911 
8912   bind(L_post_third_loop_done);
8913 }
8914 
8915 /**
8916  * Code for BigInteger::multiplyToLen() instrinsic.
8917  *
8918  * rdi: x
8919  * rax: xlen
8920  * rsi: y
8921  * rcx: ylen
8922  * r8:  z
8923  * r11: zlen
8924  * r12: tmp1
8925  * r13: tmp2
8926  * r14: tmp3
8927  * r15: tmp4
8928  * rbx: tmp5
8929  *
8930  */
8931 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8932                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8933   ShortBranchVerifier sbv(this);
8934   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8935 
8936   push(tmp1);
8937   push(tmp2);
8938   push(tmp3);
8939   push(tmp4);
8940   push(tmp5);
8941 
8942   push(xlen);
8943   push(zlen);
8944 
8945   const Register idx = tmp1;
8946   const Register kdx = tmp2;
8947   const Register xstart = tmp3;
8948 
8949   const Register y_idx = tmp4;
8950   const Register carry = tmp5;
8951   const Register product  = xlen;
8952   const Register x_xstart = zlen;  // reuse register
8953 
8954   // First Loop.
8955   //
8956   //  final static long LONG_MASK = 0xffffffffL;
8957   //  int xstart = xlen - 1;
8958   //  int ystart = ylen - 1;
8959   //  long carry = 0;
8960   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8961   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8962   //    z[kdx] = (int)product;
8963   //    carry = product >>> 32;
8964   //  }
8965   //  z[xstart] = (int)carry;
8966   //
8967 
8968   movl(idx, ylen);      // idx = ylen;
8969   movl(kdx, zlen);      // kdx = xlen+ylen;
8970   xorq(carry, carry);   // carry = 0;
8971 
8972   Label L_done;
8973 
8974   movl(xstart, xlen);
8975   decrementl(xstart);
8976   jcc(Assembler::negative, L_done);
8977 
8978   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8979 
8980   Label L_second_loop;
8981   testl(kdx, kdx);
8982   jcc(Assembler::zero, L_second_loop);
8983 
8984   Label L_carry;
8985   subl(kdx, 1);
8986   jcc(Assembler::zero, L_carry);
8987 
8988   movl(Address(z, kdx, Address::times_4,  0), carry);
8989   shrq(carry, 32);
8990   subl(kdx, 1);
8991 
8992   bind(L_carry);
8993   movl(Address(z, kdx, Address::times_4,  0), carry);
8994 
8995   // Second and third (nested) loops.
8996   //
8997   // for (int i = xstart-1; i >= 0; i--) { // Second loop
8998   //   carry = 0;
8999   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9000   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9001   //                    (z[k] & LONG_MASK) + carry;
9002   //     z[k] = (int)product;
9003   //     carry = product >>> 32;
9004   //   }
9005   //   z[i] = (int)carry;
9006   // }
9007   //
9008   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9009 
9010   const Register jdx = tmp1;
9011 
9012   bind(L_second_loop);
9013   xorl(carry, carry);    // carry = 0;
9014   movl(jdx, ylen);       // j = ystart+1
9015 
9016   subl(xstart, 1);       // i = xstart-1;
9017   jcc(Assembler::negative, L_done);
9018 
9019   push (z);
9020 
9021   Label L_last_x;
9022   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9023   subl(xstart, 1);       // i = xstart-1;
9024   jcc(Assembler::negative, L_last_x);
9025 
9026   if (UseBMI2Instructions) {
9027     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9028     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9029   } else {
9030     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9031     rorq(x_xstart, 32);  // convert big-endian to little-endian
9032   }
9033 
9034   Label L_third_loop_prologue;
9035   bind(L_third_loop_prologue);
9036 
9037   push (x);
9038   push (xstart);
9039   push (ylen);
9040 
9041 
9042   if (UseBMI2Instructions) {
9043     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9044   } else { // !UseBMI2Instructions
9045     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9046   }
9047 
9048   pop(ylen);
9049   pop(xlen);
9050   pop(x);
9051   pop(z);
9052 
9053   movl(tmp3, xlen);
9054   addl(tmp3, 1);
9055   movl(Address(z, tmp3, Address::times_4,  0), carry);
9056   subl(tmp3, 1);
9057   jccb(Assembler::negative, L_done);
9058 
9059   shrq(carry, 32);
9060   movl(Address(z, tmp3, Address::times_4,  0), carry);
9061   jmp(L_second_loop);
9062 
9063   // Next infrequent code is moved outside loops.
9064   bind(L_last_x);
9065   if (UseBMI2Instructions) {
9066     movl(rdx, Address(x,  0));
9067   } else {
9068     movl(x_xstart, Address(x,  0));
9069   }
9070   jmp(L_third_loop_prologue);
9071 
9072   bind(L_done);
9073 
9074   pop(zlen);
9075   pop(xlen);
9076 
9077   pop(tmp5);
9078   pop(tmp4);
9079   pop(tmp3);
9080   pop(tmp2);
9081   pop(tmp1);
9082 }
9083 
9084 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9085   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9086   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9087   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9088   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9089   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9090   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9091   Label SAME_TILL_END, DONE;
9092   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9093 
9094   //scale is in rcx in both Win64 and Unix
9095   ShortBranchVerifier sbv(this);
9096 
9097   shlq(length);
9098   xorq(result, result);
9099 
9100   if ((UseAVX > 2) &&
9101       VM_Version::supports_avx512vlbw()) {
9102     set_vector_masking();  // opening of the stub context for programming mask registers
9103     cmpq(length, 64);
9104     jcc(Assembler::less, VECTOR32_TAIL);
9105     movq(tmp1, length);
9106     andq(tmp1, 0x3F);      // tail count
9107     andq(length, ~(0x3F)); //vector count
9108 
9109     bind(VECTOR64_LOOP);
9110     // AVX512 code to compare 64 byte vectors.
9111     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9112     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9113     kortestql(k7, k7);
9114     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9115     addq(result, 64);
9116     subq(length, 64);
9117     jccb(Assembler::notZero, VECTOR64_LOOP);
9118 
9119     //bind(VECTOR64_TAIL);
9120     testq(tmp1, tmp1);
9121     jcc(Assembler::zero, SAME_TILL_END);
9122 
9123     bind(VECTOR64_TAIL);
9124     // AVX512 code to compare upto 63 byte vectors.
9125     // Save k1
9126     kmovql(k3, k1);
9127     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9128     shlxq(tmp2, tmp2, tmp1);
9129     notq(tmp2);
9130     kmovql(k1, tmp2);
9131 
9132     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9133     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9134 
9135     ktestql(k7, k1);
9136     // Restore k1
9137     kmovql(k1, k3);
9138     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9139 
9140     bind(VECTOR64_NOT_EQUAL);
9141     kmovql(tmp1, k7);
9142     notq(tmp1);
9143     tzcntq(tmp1, tmp1);
9144     addq(result, tmp1);
9145     shrq(result);
9146     jmp(DONE);
9147     bind(VECTOR32_TAIL);
9148     clear_vector_masking();   // closing of the stub context for programming mask registers
9149   }
9150 
9151   cmpq(length, 8);
9152   jcc(Assembler::equal, VECTOR8_LOOP);
9153   jcc(Assembler::less, VECTOR4_TAIL);
9154 
9155   if (UseAVX >= 2) {
9156 
9157     cmpq(length, 16);
9158     jcc(Assembler::equal, VECTOR16_LOOP);
9159     jcc(Assembler::less, VECTOR8_LOOP);
9160 
9161     cmpq(length, 32);
9162     jccb(Assembler::less, VECTOR16_TAIL);
9163 
9164     subq(length, 32);
9165     bind(VECTOR32_LOOP);
9166     vmovdqu(rymm0, Address(obja, result));
9167     vmovdqu(rymm1, Address(objb, result));
9168     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9169     vptest(rymm2, rymm2);
9170     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9171     addq(result, 32);
9172     subq(length, 32);
9173     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9174     addq(length, 32);
9175     jcc(Assembler::equal, SAME_TILL_END);
9176     //falling through if less than 32 bytes left //close the branch here.
9177 
9178     bind(VECTOR16_TAIL);
9179     cmpq(length, 16);
9180     jccb(Assembler::less, VECTOR8_TAIL);
9181     bind(VECTOR16_LOOP);
9182     movdqu(rymm0, Address(obja, result));
9183     movdqu(rymm1, Address(objb, result));
9184     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9185     ptest(rymm2, rymm2);
9186     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9187     addq(result, 16);
9188     subq(length, 16);
9189     jcc(Assembler::equal, SAME_TILL_END);
9190     //falling through if less than 16 bytes left
9191   } else {//regular intrinsics
9192 
9193     cmpq(length, 16);
9194     jccb(Assembler::less, VECTOR8_TAIL);
9195 
9196     subq(length, 16);
9197     bind(VECTOR16_LOOP);
9198     movdqu(rymm0, Address(obja, result));
9199     movdqu(rymm1, Address(objb, result));
9200     pxor(rymm0, rymm1);
9201     ptest(rymm0, rymm0);
9202     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9203     addq(result, 16);
9204     subq(length, 16);
9205     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9206     addq(length, 16);
9207     jcc(Assembler::equal, SAME_TILL_END);
9208     //falling through if less than 16 bytes left
9209   }
9210 
9211   bind(VECTOR8_TAIL);
9212   cmpq(length, 8);
9213   jccb(Assembler::less, VECTOR4_TAIL);
9214   bind(VECTOR8_LOOP);
9215   movq(tmp1, Address(obja, result));
9216   movq(tmp2, Address(objb, result));
9217   xorq(tmp1, tmp2);
9218   testq(tmp1, tmp1);
9219   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9220   addq(result, 8);
9221   subq(length, 8);
9222   jcc(Assembler::equal, SAME_TILL_END);
9223   //falling through if less than 8 bytes left
9224 
9225   bind(VECTOR4_TAIL);
9226   cmpq(length, 4);
9227   jccb(Assembler::less, BYTES_TAIL);
9228   bind(VECTOR4_LOOP);
9229   movl(tmp1, Address(obja, result));
9230   xorl(tmp1, Address(objb, result));
9231   testl(tmp1, tmp1);
9232   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9233   addq(result, 4);
9234   subq(length, 4);
9235   jcc(Assembler::equal, SAME_TILL_END);
9236   //falling through if less than 4 bytes left
9237 
9238   bind(BYTES_TAIL);
9239   bind(BYTES_LOOP);
9240   load_unsigned_byte(tmp1, Address(obja, result));
9241   load_unsigned_byte(tmp2, Address(objb, result));
9242   xorl(tmp1, tmp2);
9243   testl(tmp1, tmp1);
9244   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9245   decq(length);
9246   jccb(Assembler::zero, SAME_TILL_END);
9247   incq(result);
9248   load_unsigned_byte(tmp1, Address(obja, result));
9249   load_unsigned_byte(tmp2, Address(objb, result));
9250   xorl(tmp1, tmp2);
9251   testl(tmp1, tmp1);
9252   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9253   decq(length);
9254   jccb(Assembler::zero, SAME_TILL_END);
9255   incq(result);
9256   load_unsigned_byte(tmp1, Address(obja, result));
9257   load_unsigned_byte(tmp2, Address(objb, result));
9258   xorl(tmp1, tmp2);
9259   testl(tmp1, tmp1);
9260   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9261   jmpb(SAME_TILL_END);
9262 
9263   if (UseAVX >= 2) {
9264     bind(VECTOR32_NOT_EQUAL);
9265     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9266     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9267     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9268     vpmovmskb(tmp1, rymm0);
9269     bsfq(tmp1, tmp1);
9270     addq(result, tmp1);
9271     shrq(result);
9272     jmpb(DONE);
9273   }
9274 
9275   bind(VECTOR16_NOT_EQUAL);
9276   if (UseAVX >= 2) {
9277     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9278     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9279     pxor(rymm0, rymm2);
9280   } else {
9281     pcmpeqb(rymm2, rymm2);
9282     pxor(rymm0, rymm1);
9283     pcmpeqb(rymm0, rymm1);
9284     pxor(rymm0, rymm2);
9285   }
9286   pmovmskb(tmp1, rymm0);
9287   bsfq(tmp1, tmp1);
9288   addq(result, tmp1);
9289   shrq(result);
9290   jmpb(DONE);
9291 
9292   bind(VECTOR8_NOT_EQUAL);
9293   bind(VECTOR4_NOT_EQUAL);
9294   bsfq(tmp1, tmp1);
9295   shrq(tmp1, 3);
9296   addq(result, tmp1);
9297   bind(BYTES_NOT_EQUAL);
9298   shrq(result);
9299   jmpb(DONE);
9300 
9301   bind(SAME_TILL_END);
9302   mov64(result, -1);
9303 
9304   bind(DONE);
9305 }
9306 
9307 //Helper functions for square_to_len()
9308 
9309 /**
9310  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9311  * Preserves x and z and modifies rest of the registers.
9312  */
9313 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9314   // Perform square and right shift by 1
9315   // Handle odd xlen case first, then for even xlen do the following
9316   // jlong carry = 0;
9317   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9318   //     huge_128 product = x[j:j+1] * x[j:j+1];
9319   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9320   //     z[i+2:i+3] = (jlong)(product >>> 1);
9321   //     carry = (jlong)product;
9322   // }
9323 
9324   xorq(tmp5, tmp5);     // carry
9325   xorq(rdxReg, rdxReg);
9326   xorl(tmp1, tmp1);     // index for x
9327   xorl(tmp4, tmp4);     // index for z
9328 
9329   Label L_first_loop, L_first_loop_exit;
9330 
9331   testl(xlen, 1);
9332   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9333 
9334   // Square and right shift by 1 the odd element using 32 bit multiply
9335   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9336   imulq(raxReg, raxReg);
9337   shrq(raxReg, 1);
9338   adcq(tmp5, 0);
9339   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9340   incrementl(tmp1);
9341   addl(tmp4, 2);
9342 
9343   // Square and  right shift by 1 the rest using 64 bit multiply
9344   bind(L_first_loop);
9345   cmpptr(tmp1, xlen);
9346   jccb(Assembler::equal, L_first_loop_exit);
9347 
9348   // Square
9349   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9350   rorq(raxReg, 32);    // convert big-endian to little-endian
9351   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9352 
9353   // Right shift by 1 and save carry
9354   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9355   rcrq(rdxReg, 1);
9356   rcrq(raxReg, 1);
9357   adcq(tmp5, 0);
9358 
9359   // Store result in z
9360   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9361   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9362 
9363   // Update indices for x and z
9364   addl(tmp1, 2);
9365   addl(tmp4, 4);
9366   jmp(L_first_loop);
9367 
9368   bind(L_first_loop_exit);
9369 }
9370 
9371 
9372 /**
9373  * Perform the following multiply add operation using BMI2 instructions
9374  * carry:sum = sum + op1*op2 + carry
9375  * op2 should be in rdx
9376  * op2 is preserved, all other registers are modified
9377  */
9378 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9379   // assert op2 is rdx
9380   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9381   addq(sum, carry);
9382   adcq(tmp2, 0);
9383   addq(sum, op1);
9384   adcq(tmp2, 0);
9385   movq(carry, tmp2);
9386 }
9387 
9388 /**
9389  * Perform the following multiply add operation:
9390  * carry:sum = sum + op1*op2 + carry
9391  * Preserves op1, op2 and modifies rest of registers
9392  */
9393 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9394   // rdx:rax = op1 * op2
9395   movq(raxReg, op2);
9396   mulq(op1);
9397 
9398   //  rdx:rax = sum + carry + rdx:rax
9399   addq(sum, carry);
9400   adcq(rdxReg, 0);
9401   addq(sum, raxReg);
9402   adcq(rdxReg, 0);
9403 
9404   // carry:sum = rdx:sum
9405   movq(carry, rdxReg);
9406 }
9407 
9408 /**
9409  * Add 64 bit long carry into z[] with carry propogation.
9410  * Preserves z and carry register values and modifies rest of registers.
9411  *
9412  */
9413 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9414   Label L_fourth_loop, L_fourth_loop_exit;
9415 
9416   movl(tmp1, 1);
9417   subl(zlen, 2);
9418   addq(Address(z, zlen, Address::times_4, 0), carry);
9419 
9420   bind(L_fourth_loop);
9421   jccb(Assembler::carryClear, L_fourth_loop_exit);
9422   subl(zlen, 2);
9423   jccb(Assembler::negative, L_fourth_loop_exit);
9424   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9425   jmp(L_fourth_loop);
9426   bind(L_fourth_loop_exit);
9427 }
9428 
9429 /**
9430  * Shift z[] left by 1 bit.
9431  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9432  *
9433  */
9434 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9435 
9436   Label L_fifth_loop, L_fifth_loop_exit;
9437 
9438   // Fifth loop
9439   // Perform primitiveLeftShift(z, zlen, 1)
9440 
9441   const Register prev_carry = tmp1;
9442   const Register new_carry = tmp4;
9443   const Register value = tmp2;
9444   const Register zidx = tmp3;
9445 
9446   // int zidx, carry;
9447   // long value;
9448   // carry = 0;
9449   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9450   //    (carry:value)  = (z[i] << 1) | carry ;
9451   //    z[i] = value;
9452   // }
9453 
9454   movl(zidx, zlen);
9455   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9456 
9457   bind(L_fifth_loop);
9458   decl(zidx);  // Use decl to preserve carry flag
9459   decl(zidx);
9460   jccb(Assembler::negative, L_fifth_loop_exit);
9461 
9462   if (UseBMI2Instructions) {
9463      movq(value, Address(z, zidx, Address::times_4, 0));
9464      rclq(value, 1);
9465      rorxq(value, value, 32);
9466      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9467   }
9468   else {
9469     // clear new_carry
9470     xorl(new_carry, new_carry);
9471 
9472     // Shift z[i] by 1, or in previous carry and save new carry
9473     movq(value, Address(z, zidx, Address::times_4, 0));
9474     shlq(value, 1);
9475     adcl(new_carry, 0);
9476 
9477     orq(value, prev_carry);
9478     rorq(value, 0x20);
9479     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9480 
9481     // Set previous carry = new carry
9482     movl(prev_carry, new_carry);
9483   }
9484   jmp(L_fifth_loop);
9485 
9486   bind(L_fifth_loop_exit);
9487 }
9488 
9489 
9490 /**
9491  * Code for BigInteger::squareToLen() intrinsic
9492  *
9493  * rdi: x
9494  * rsi: len
9495  * r8:  z
9496  * rcx: zlen
9497  * r12: tmp1
9498  * r13: tmp2
9499  * r14: tmp3
9500  * r15: tmp4
9501  * rbx: tmp5
9502  *
9503  */
9504 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) {
9505 
9506   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;
9507   push(tmp1);
9508   push(tmp2);
9509   push(tmp3);
9510   push(tmp4);
9511   push(tmp5);
9512 
9513   // First loop
9514   // Store the squares, right shifted one bit (i.e., divided by 2).
9515   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9516 
9517   // Add in off-diagonal sums.
9518   //
9519   // Second, third (nested) and fourth loops.
9520   // zlen +=2;
9521   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9522   //    carry = 0;
9523   //    long op2 = x[xidx:xidx+1];
9524   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9525   //       k -= 2;
9526   //       long op1 = x[j:j+1];
9527   //       long sum = z[k:k+1];
9528   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9529   //       z[k:k+1] = sum;
9530   //    }
9531   //    add_one_64(z, k, carry, tmp_regs);
9532   // }
9533 
9534   const Register carry = tmp5;
9535   const Register sum = tmp3;
9536   const Register op1 = tmp4;
9537   Register op2 = tmp2;
9538 
9539   push(zlen);
9540   push(len);
9541   addl(zlen,2);
9542   bind(L_second_loop);
9543   xorq(carry, carry);
9544   subl(zlen, 4);
9545   subl(len, 2);
9546   push(zlen);
9547   push(len);
9548   cmpl(len, 0);
9549   jccb(Assembler::lessEqual, L_second_loop_exit);
9550 
9551   // Multiply an array by one 64 bit long.
9552   if (UseBMI2Instructions) {
9553     op2 = rdxReg;
9554     movq(op2, Address(x, len, Address::times_4,  0));
9555     rorxq(op2, op2, 32);
9556   }
9557   else {
9558     movq(op2, Address(x, len, Address::times_4,  0));
9559     rorq(op2, 32);
9560   }
9561 
9562   bind(L_third_loop);
9563   decrementl(len);
9564   jccb(Assembler::negative, L_third_loop_exit);
9565   decrementl(len);
9566   jccb(Assembler::negative, L_last_x);
9567 
9568   movq(op1, Address(x, len, Address::times_4,  0));
9569   rorq(op1, 32);
9570 
9571   bind(L_multiply);
9572   subl(zlen, 2);
9573   movq(sum, Address(z, zlen, Address::times_4,  0));
9574 
9575   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9576   if (UseBMI2Instructions) {
9577     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9578   }
9579   else {
9580     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9581   }
9582 
9583   movq(Address(z, zlen, Address::times_4, 0), sum);
9584 
9585   jmp(L_third_loop);
9586   bind(L_third_loop_exit);
9587 
9588   // Fourth loop
9589   // Add 64 bit long carry into z with carry propogation.
9590   // Uses offsetted zlen.
9591   add_one_64(z, zlen, carry, tmp1);
9592 
9593   pop(len);
9594   pop(zlen);
9595   jmp(L_second_loop);
9596 
9597   // Next infrequent code is moved outside loops.
9598   bind(L_last_x);
9599   movl(op1, Address(x, 0));
9600   jmp(L_multiply);
9601 
9602   bind(L_second_loop_exit);
9603   pop(len);
9604   pop(zlen);
9605   pop(len);
9606   pop(zlen);
9607 
9608   // Fifth loop
9609   // Shift z left 1 bit.
9610   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9611 
9612   // z[zlen-1] |= x[len-1] & 1;
9613   movl(tmp3, Address(x, len, Address::times_4, -4));
9614   andl(tmp3, 1);
9615   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9616 
9617   pop(tmp5);
9618   pop(tmp4);
9619   pop(tmp3);
9620   pop(tmp2);
9621   pop(tmp1);
9622 }
9623 
9624 /**
9625  * Helper function for mul_add()
9626  * Multiply the in[] by int k and add to out[] starting at offset offs using
9627  * 128 bit by 32 bit multiply and return the carry in tmp5.
9628  * Only quad int aligned length of in[] is operated on in this function.
9629  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9630  * This function preserves out, in and k registers.
9631  * len and offset point to the appropriate index in "in" & "out" correspondingly
9632  * tmp5 has the carry.
9633  * other registers are temporary and are modified.
9634  *
9635  */
9636 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9637   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9638   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9639 
9640   Label L_first_loop, L_first_loop_exit;
9641 
9642   movl(tmp1, len);
9643   shrl(tmp1, 2);
9644 
9645   bind(L_first_loop);
9646   subl(tmp1, 1);
9647   jccb(Assembler::negative, L_first_loop_exit);
9648 
9649   subl(len, 4);
9650   subl(offset, 4);
9651 
9652   Register op2 = tmp2;
9653   const Register sum = tmp3;
9654   const Register op1 = tmp4;
9655   const Register carry = tmp5;
9656 
9657   if (UseBMI2Instructions) {
9658     op2 = rdxReg;
9659   }
9660 
9661   movq(op1, Address(in, len, Address::times_4,  8));
9662   rorq(op1, 32);
9663   movq(sum, Address(out, offset, Address::times_4,  8));
9664   rorq(sum, 32);
9665   if (UseBMI2Instructions) {
9666     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9667   }
9668   else {
9669     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9670   }
9671   // Store back in big endian from little endian
9672   rorq(sum, 0x20);
9673   movq(Address(out, offset, Address::times_4,  8), sum);
9674 
9675   movq(op1, Address(in, len, Address::times_4,  0));
9676   rorq(op1, 32);
9677   movq(sum, Address(out, offset, Address::times_4,  0));
9678   rorq(sum, 32);
9679   if (UseBMI2Instructions) {
9680     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9681   }
9682   else {
9683     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9684   }
9685   // Store back in big endian from little endian
9686   rorq(sum, 0x20);
9687   movq(Address(out, offset, Address::times_4,  0), sum);
9688 
9689   jmp(L_first_loop);
9690   bind(L_first_loop_exit);
9691 }
9692 
9693 /**
9694  * Code for BigInteger::mulAdd() intrinsic
9695  *
9696  * rdi: out
9697  * rsi: in
9698  * r11: offs (out.length - offset)
9699  * rcx: len
9700  * r8:  k
9701  * r12: tmp1
9702  * r13: tmp2
9703  * r14: tmp3
9704  * r15: tmp4
9705  * rbx: tmp5
9706  * Multiply the in[] by word k and add to out[], return the carry in rax
9707  */
9708 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9709    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9710    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9711 
9712   Label L_carry, L_last_in, L_done;
9713 
9714 // carry = 0;
9715 // for (int j=len-1; j >= 0; j--) {
9716 //    long product = (in[j] & LONG_MASK) * kLong +
9717 //                   (out[offs] & LONG_MASK) + carry;
9718 //    out[offs--] = (int)product;
9719 //    carry = product >>> 32;
9720 // }
9721 //
9722   push(tmp1);
9723   push(tmp2);
9724   push(tmp3);
9725   push(tmp4);
9726   push(tmp5);
9727 
9728   Register op2 = tmp2;
9729   const Register sum = tmp3;
9730   const Register op1 = tmp4;
9731   const Register carry =  tmp5;
9732 
9733   if (UseBMI2Instructions) {
9734     op2 = rdxReg;
9735     movl(op2, k);
9736   }
9737   else {
9738     movl(op2, k);
9739   }
9740 
9741   xorq(carry, carry);
9742 
9743   //First loop
9744 
9745   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9746   //The carry is in tmp5
9747   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9748 
9749   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9750   decrementl(len);
9751   jccb(Assembler::negative, L_carry);
9752   decrementl(len);
9753   jccb(Assembler::negative, L_last_in);
9754 
9755   movq(op1, Address(in, len, Address::times_4,  0));
9756   rorq(op1, 32);
9757 
9758   subl(offs, 2);
9759   movq(sum, Address(out, offs, Address::times_4,  0));
9760   rorq(sum, 32);
9761 
9762   if (UseBMI2Instructions) {
9763     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9764   }
9765   else {
9766     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9767   }
9768 
9769   // Store back in big endian from little endian
9770   rorq(sum, 0x20);
9771   movq(Address(out, offs, Address::times_4,  0), sum);
9772 
9773   testl(len, len);
9774   jccb(Assembler::zero, L_carry);
9775 
9776   //Multiply the last in[] entry, if any
9777   bind(L_last_in);
9778   movl(op1, Address(in, 0));
9779   movl(sum, Address(out, offs, Address::times_4,  -4));
9780 
9781   movl(raxReg, k);
9782   mull(op1); //tmp4 * eax -> edx:eax
9783   addl(sum, carry);
9784   adcl(rdxReg, 0);
9785   addl(sum, raxReg);
9786   adcl(rdxReg, 0);
9787   movl(carry, rdxReg);
9788 
9789   movl(Address(out, offs, Address::times_4,  -4), sum);
9790 
9791   bind(L_carry);
9792   //return tmp5/carry as carry in rax
9793   movl(rax, carry);
9794 
9795   bind(L_done);
9796   pop(tmp5);
9797   pop(tmp4);
9798   pop(tmp3);
9799   pop(tmp2);
9800   pop(tmp1);
9801 }
9802 #endif
9803 
9804 /**
9805  * Emits code to update CRC-32 with a byte value according to constants in table
9806  *
9807  * @param [in,out]crc   Register containing the crc.
9808  * @param [in]val       Register containing the byte to fold into the CRC.
9809  * @param [in]table     Register containing the table of crc constants.
9810  *
9811  * uint32_t crc;
9812  * val = crc_table[(val ^ crc) & 0xFF];
9813  * crc = val ^ (crc >> 8);
9814  *
9815  */
9816 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9817   xorl(val, crc);
9818   andl(val, 0xFF);
9819   shrl(crc, 8); // unsigned shift
9820   xorl(crc, Address(table, val, Address::times_4, 0));
9821 }
9822 
9823 /**
9824 * Fold four 128-bit data chunks
9825 */
9826 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9827   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9828   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9829   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9830   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9831 }
9832 
9833 /**
9834  * Fold 128-bit data chunk
9835  */
9836 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9837   if (UseAVX > 0) {
9838     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9839     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9840     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9841     pxor(xcrc, xtmp);
9842   } else {
9843     movdqa(xtmp, xcrc);
9844     pclmulhdq(xtmp, xK);   // [123:64]
9845     pclmulldq(xcrc, xK);   // [63:0]
9846     pxor(xcrc, xtmp);
9847     movdqu(xtmp, Address(buf, offset));
9848     pxor(xcrc, xtmp);
9849   }
9850 }
9851 
9852 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9853   if (UseAVX > 0) {
9854     vpclmulhdq(xtmp, xK, xcrc);
9855     vpclmulldq(xcrc, xK, xcrc);
9856     pxor(xcrc, xbuf);
9857     pxor(xcrc, xtmp);
9858   } else {
9859     movdqa(xtmp, xcrc);
9860     pclmulhdq(xtmp, xK);
9861     pclmulldq(xcrc, xK);
9862     pxor(xcrc, xbuf);
9863     pxor(xcrc, xtmp);
9864   }
9865 }
9866 
9867 /**
9868  * 8-bit folds to compute 32-bit CRC
9869  *
9870  * uint64_t xcrc;
9871  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9872  */
9873 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9874   movdl(tmp, xcrc);
9875   andl(tmp, 0xFF);
9876   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9877   psrldq(xcrc, 1); // unsigned shift one byte
9878   pxor(xcrc, xtmp);
9879 }
9880 
9881 /**
9882  * uint32_t crc;
9883  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9884  */
9885 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9886   movl(tmp, crc);
9887   andl(tmp, 0xFF);
9888   shrl(crc, 8);
9889   xorl(crc, Address(table, tmp, Address::times_4, 0));
9890 }
9891 
9892 /**
9893  * @param crc   register containing existing CRC (32-bit)
9894  * @param buf   register pointing to input byte buffer (byte*)
9895  * @param len   register containing number of bytes
9896  * @param table register that will contain address of CRC table
9897  * @param tmp   scratch register
9898  */
9899 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9900   assert_different_registers(crc, buf, len, table, tmp, rax);
9901 
9902   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9903   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9904 
9905   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9906   // context for the registers used, where all instructions below are using 128-bit mode
9907   // On EVEX without VL and BW, these instructions will all be AVX.
9908   if (VM_Version::supports_avx512vlbw()) {
9909     movl(tmp, 0xffff);
9910     kmovwl(k1, tmp);
9911   }
9912 
9913   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9914   notl(crc); // ~crc
9915   cmpl(len, 16);
9916   jcc(Assembler::less, L_tail);
9917 
9918   // Align buffer to 16 bytes
9919   movl(tmp, buf);
9920   andl(tmp, 0xF);
9921   jccb(Assembler::zero, L_aligned);
9922   subl(tmp,  16);
9923   addl(len, tmp);
9924 
9925   align(4);
9926   BIND(L_align_loop);
9927   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9928   update_byte_crc32(crc, rax, table);
9929   increment(buf);
9930   incrementl(tmp);
9931   jccb(Assembler::less, L_align_loop);
9932 
9933   BIND(L_aligned);
9934   movl(tmp, len); // save
9935   shrl(len, 4);
9936   jcc(Assembler::zero, L_tail_restore);
9937 
9938   // Fold total 512 bits of polynomial on each iteration
9939   if (VM_Version::supports_vpclmulqdq()) {
9940     Label Parallel_loop, L_No_Parallel;
9941 
9942     cmpl(len, 8);
9943     jccb(Assembler::less, L_No_Parallel);
9944 
9945     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9946     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
9947     movdl(xmm5, crc);
9948     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
9949     addptr(buf, 64);
9950     subl(len, 7);
9951     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
9952 
9953     BIND(Parallel_loop);
9954     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
9955     addptr(buf, 64);
9956     subl(len, 4);
9957     jcc(Assembler::greater, Parallel_loop);
9958 
9959     vextracti64x2(xmm2, xmm1, 0x01);
9960     vextracti64x2(xmm3, xmm1, 0x02);
9961     vextracti64x2(xmm4, xmm1, 0x03);
9962     jmp(L_fold_512b);
9963 
9964     BIND(L_No_Parallel);
9965   }
9966   // Fold crc into first bytes of vector
9967   movdqa(xmm1, Address(buf, 0));
9968   movdl(rax, xmm1);
9969   xorl(crc, rax);
9970   if (VM_Version::supports_sse4_1()) {
9971     pinsrd(xmm1, crc, 0);
9972   } else {
9973     pinsrw(xmm1, crc, 0);
9974     shrl(crc, 16);
9975     pinsrw(xmm1, crc, 1);
9976   }
9977   addptr(buf, 16);
9978   subl(len, 4); // len > 0
9979   jcc(Assembler::less, L_fold_tail);
9980 
9981   movdqa(xmm2, Address(buf,  0));
9982   movdqa(xmm3, Address(buf, 16));
9983   movdqa(xmm4, Address(buf, 32));
9984   addptr(buf, 48);
9985   subl(len, 3);
9986   jcc(Assembler::lessEqual, L_fold_512b);
9987 
9988   // Fold total 512 bits of polynomial on each iteration,
9989   // 128 bits per each of 4 parallel streams.
9990   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9991 
9992   align(32);
9993   BIND(L_fold_512b_loop);
9994   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9995   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9996   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9997   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9998   addptr(buf, 64);
9999   subl(len, 4);
10000   jcc(Assembler::greater, L_fold_512b_loop);
10001 
10002   // Fold 512 bits to 128 bits.
10003   BIND(L_fold_512b);
10004   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10005   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10006   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10007   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10008 
10009   // Fold the rest of 128 bits data chunks
10010   BIND(L_fold_tail);
10011   addl(len, 3);
10012   jccb(Assembler::lessEqual, L_fold_128b);
10013   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10014 
10015   BIND(L_fold_tail_loop);
10016   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10017   addptr(buf, 16);
10018   decrementl(len);
10019   jccb(Assembler::greater, L_fold_tail_loop);
10020 
10021   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10022   BIND(L_fold_128b);
10023   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10024   if (UseAVX > 0) {
10025     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10026     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10027     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10028   } else {
10029     movdqa(xmm2, xmm0);
10030     pclmulqdq(xmm2, xmm1, 0x1);
10031     movdqa(xmm3, xmm0);
10032     pand(xmm3, xmm2);
10033     pclmulqdq(xmm0, xmm3, 0x1);
10034   }
10035   psrldq(xmm1, 8);
10036   psrldq(xmm2, 4);
10037   pxor(xmm0, xmm1);
10038   pxor(xmm0, xmm2);
10039 
10040   // 8 8-bit folds to compute 32-bit CRC.
10041   for (int j = 0; j < 4; j++) {
10042     fold_8bit_crc32(xmm0, table, xmm1, rax);
10043   }
10044   movdl(crc, xmm0); // mov 32 bits to general register
10045   for (int j = 0; j < 4; j++) {
10046     fold_8bit_crc32(crc, table, rax);
10047   }
10048 
10049   BIND(L_tail_restore);
10050   movl(len, tmp); // restore
10051   BIND(L_tail);
10052   andl(len, 0xf);
10053   jccb(Assembler::zero, L_exit);
10054 
10055   // Fold the rest of bytes
10056   align(4);
10057   BIND(L_tail_loop);
10058   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10059   update_byte_crc32(crc, rax, table);
10060   increment(buf);
10061   decrementl(len);
10062   jccb(Assembler::greater, L_tail_loop);
10063 
10064   BIND(L_exit);
10065   notl(crc); // ~c
10066 }
10067 
10068 #ifdef _LP64
10069 // S. Gueron / Information Processing Letters 112 (2012) 184
10070 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10071 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10072 // Output: the 64-bit carry-less product of B * CONST
10073 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10074                                      Register tmp1, Register tmp2, Register tmp3) {
10075   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10076   if (n > 0) {
10077     addq(tmp3, n * 256 * 8);
10078   }
10079   //    Q1 = TABLEExt[n][B & 0xFF];
10080   movl(tmp1, in);
10081   andl(tmp1, 0x000000FF);
10082   shll(tmp1, 3);
10083   addq(tmp1, tmp3);
10084   movq(tmp1, Address(tmp1, 0));
10085 
10086   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10087   movl(tmp2, in);
10088   shrl(tmp2, 8);
10089   andl(tmp2, 0x000000FF);
10090   shll(tmp2, 3);
10091   addq(tmp2, tmp3);
10092   movq(tmp2, Address(tmp2, 0));
10093 
10094   shlq(tmp2, 8);
10095   xorq(tmp1, tmp2);
10096 
10097   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10098   movl(tmp2, in);
10099   shrl(tmp2, 16);
10100   andl(tmp2, 0x000000FF);
10101   shll(tmp2, 3);
10102   addq(tmp2, tmp3);
10103   movq(tmp2, Address(tmp2, 0));
10104 
10105   shlq(tmp2, 16);
10106   xorq(tmp1, tmp2);
10107 
10108   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10109   shrl(in, 24);
10110   andl(in, 0x000000FF);
10111   shll(in, 3);
10112   addq(in, tmp3);
10113   movq(in, Address(in, 0));
10114 
10115   shlq(in, 24);
10116   xorq(in, tmp1);
10117   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10118 }
10119 
10120 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10121                                       Register in_out,
10122                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10123                                       XMMRegister w_xtmp2,
10124                                       Register tmp1,
10125                                       Register n_tmp2, Register n_tmp3) {
10126   if (is_pclmulqdq_supported) {
10127     movdl(w_xtmp1, in_out); // modified blindly
10128 
10129     movl(tmp1, const_or_pre_comp_const_index);
10130     movdl(w_xtmp2, tmp1);
10131     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10132 
10133     movdq(in_out, w_xtmp1);
10134   } else {
10135     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10136   }
10137 }
10138 
10139 // Recombination Alternative 2: No bit-reflections
10140 // T1 = (CRC_A * U1) << 1
10141 // T2 = (CRC_B * U2) << 1
10142 // C1 = T1 >> 32
10143 // C2 = T2 >> 32
10144 // T1 = T1 & 0xFFFFFFFF
10145 // T2 = T2 & 0xFFFFFFFF
10146 // T1 = CRC32(0, T1)
10147 // T2 = CRC32(0, T2)
10148 // C1 = C1 ^ T1
10149 // C2 = C2 ^ T2
10150 // CRC = C1 ^ C2 ^ CRC_C
10151 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,
10152                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10153                                      Register tmp1, Register tmp2,
10154                                      Register n_tmp3) {
10155   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10156   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10157   shlq(in_out, 1);
10158   movl(tmp1, in_out);
10159   shrq(in_out, 32);
10160   xorl(tmp2, tmp2);
10161   crc32(tmp2, tmp1, 4);
10162   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10163   shlq(in1, 1);
10164   movl(tmp1, in1);
10165   shrq(in1, 32);
10166   xorl(tmp2, tmp2);
10167   crc32(tmp2, tmp1, 4);
10168   xorl(in1, tmp2);
10169   xorl(in_out, in1);
10170   xorl(in_out, in2);
10171 }
10172 
10173 // Set N to predefined value
10174 // Subtract from a lenght of a buffer
10175 // execute in a loop:
10176 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10177 // for i = 1 to N do
10178 //  CRC_A = CRC32(CRC_A, A[i])
10179 //  CRC_B = CRC32(CRC_B, B[i])
10180 //  CRC_C = CRC32(CRC_C, C[i])
10181 // end for
10182 // Recombine
10183 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,
10184                                        Register in_out1, Register in_out2, Register in_out3,
10185                                        Register tmp1, Register tmp2, Register tmp3,
10186                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10187                                        Register tmp4, Register tmp5,
10188                                        Register n_tmp6) {
10189   Label L_processPartitions;
10190   Label L_processPartition;
10191   Label L_exit;
10192 
10193   bind(L_processPartitions);
10194   cmpl(in_out1, 3 * size);
10195   jcc(Assembler::less, L_exit);
10196     xorl(tmp1, tmp1);
10197     xorl(tmp2, tmp2);
10198     movq(tmp3, in_out2);
10199     addq(tmp3, size);
10200 
10201     bind(L_processPartition);
10202       crc32(in_out3, Address(in_out2, 0), 8);
10203       crc32(tmp1, Address(in_out2, size), 8);
10204       crc32(tmp2, Address(in_out2, size * 2), 8);
10205       addq(in_out2, 8);
10206       cmpq(in_out2, tmp3);
10207       jcc(Assembler::less, L_processPartition);
10208     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10209             w_xtmp1, w_xtmp2, w_xtmp3,
10210             tmp4, tmp5,
10211             n_tmp6);
10212     addq(in_out2, 2 * size);
10213     subl(in_out1, 3 * size);
10214     jmp(L_processPartitions);
10215 
10216   bind(L_exit);
10217 }
10218 #else
10219 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10220                                      Register tmp1, Register tmp2, Register tmp3,
10221                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10222   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10223   if (n > 0) {
10224     addl(tmp3, n * 256 * 8);
10225   }
10226   //    Q1 = TABLEExt[n][B & 0xFF];
10227   movl(tmp1, in_out);
10228   andl(tmp1, 0x000000FF);
10229   shll(tmp1, 3);
10230   addl(tmp1, tmp3);
10231   movq(xtmp1, Address(tmp1, 0));
10232 
10233   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10234   movl(tmp2, in_out);
10235   shrl(tmp2, 8);
10236   andl(tmp2, 0x000000FF);
10237   shll(tmp2, 3);
10238   addl(tmp2, tmp3);
10239   movq(xtmp2, Address(tmp2, 0));
10240 
10241   psllq(xtmp2, 8);
10242   pxor(xtmp1, xtmp2);
10243 
10244   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10245   movl(tmp2, in_out);
10246   shrl(tmp2, 16);
10247   andl(tmp2, 0x000000FF);
10248   shll(tmp2, 3);
10249   addl(tmp2, tmp3);
10250   movq(xtmp2, Address(tmp2, 0));
10251 
10252   psllq(xtmp2, 16);
10253   pxor(xtmp1, xtmp2);
10254 
10255   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10256   shrl(in_out, 24);
10257   andl(in_out, 0x000000FF);
10258   shll(in_out, 3);
10259   addl(in_out, tmp3);
10260   movq(xtmp2, Address(in_out, 0));
10261 
10262   psllq(xtmp2, 24);
10263   pxor(xtmp1, xtmp2); // Result in CXMM
10264   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10265 }
10266 
10267 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10268                                       Register in_out,
10269                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10270                                       XMMRegister w_xtmp2,
10271                                       Register tmp1,
10272                                       Register n_tmp2, Register n_tmp3) {
10273   if (is_pclmulqdq_supported) {
10274     movdl(w_xtmp1, in_out);
10275 
10276     movl(tmp1, const_or_pre_comp_const_index);
10277     movdl(w_xtmp2, tmp1);
10278     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10279     // Keep result in XMM since GPR is 32 bit in length
10280   } else {
10281     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10282   }
10283 }
10284 
10285 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,
10286                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10287                                      Register tmp1, Register tmp2,
10288                                      Register n_tmp3) {
10289   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10290   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10291 
10292   psllq(w_xtmp1, 1);
10293   movdl(tmp1, w_xtmp1);
10294   psrlq(w_xtmp1, 32);
10295   movdl(in_out, w_xtmp1);
10296 
10297   xorl(tmp2, tmp2);
10298   crc32(tmp2, tmp1, 4);
10299   xorl(in_out, tmp2);
10300 
10301   psllq(w_xtmp2, 1);
10302   movdl(tmp1, w_xtmp2);
10303   psrlq(w_xtmp2, 32);
10304   movdl(in1, w_xtmp2);
10305 
10306   xorl(tmp2, tmp2);
10307   crc32(tmp2, tmp1, 4);
10308   xorl(in1, tmp2);
10309   xorl(in_out, in1);
10310   xorl(in_out, in2);
10311 }
10312 
10313 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,
10314                                        Register in_out1, Register in_out2, Register in_out3,
10315                                        Register tmp1, Register tmp2, Register tmp3,
10316                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10317                                        Register tmp4, Register tmp5,
10318                                        Register n_tmp6) {
10319   Label L_processPartitions;
10320   Label L_processPartition;
10321   Label L_exit;
10322 
10323   bind(L_processPartitions);
10324   cmpl(in_out1, 3 * size);
10325   jcc(Assembler::less, L_exit);
10326     xorl(tmp1, tmp1);
10327     xorl(tmp2, tmp2);
10328     movl(tmp3, in_out2);
10329     addl(tmp3, size);
10330 
10331     bind(L_processPartition);
10332       crc32(in_out3, Address(in_out2, 0), 4);
10333       crc32(tmp1, Address(in_out2, size), 4);
10334       crc32(tmp2, Address(in_out2, size*2), 4);
10335       crc32(in_out3, Address(in_out2, 0+4), 4);
10336       crc32(tmp1, Address(in_out2, size+4), 4);
10337       crc32(tmp2, Address(in_out2, size*2+4), 4);
10338       addl(in_out2, 8);
10339       cmpl(in_out2, tmp3);
10340       jcc(Assembler::less, L_processPartition);
10341 
10342         push(tmp3);
10343         push(in_out1);
10344         push(in_out2);
10345         tmp4 = tmp3;
10346         tmp5 = in_out1;
10347         n_tmp6 = in_out2;
10348 
10349       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10350             w_xtmp1, w_xtmp2, w_xtmp3,
10351             tmp4, tmp5,
10352             n_tmp6);
10353 
10354         pop(in_out2);
10355         pop(in_out1);
10356         pop(tmp3);
10357 
10358     addl(in_out2, 2 * size);
10359     subl(in_out1, 3 * size);
10360     jmp(L_processPartitions);
10361 
10362   bind(L_exit);
10363 }
10364 #endif //LP64
10365 
10366 #ifdef _LP64
10367 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10368 // Input: A buffer I of L bytes.
10369 // Output: the CRC32C value of the buffer.
10370 // Notations:
10371 // Write L = 24N + r, with N = floor (L/24).
10372 // r = L mod 24 (0 <= r < 24).
10373 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10374 // N quadwords, and R consists of r bytes.
10375 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10376 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10377 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10378 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10379 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10380                                           Register tmp1, Register tmp2, Register tmp3,
10381                                           Register tmp4, Register tmp5, Register tmp6,
10382                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10383                                           bool is_pclmulqdq_supported) {
10384   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10385   Label L_wordByWord;
10386   Label L_byteByByteProlog;
10387   Label L_byteByByte;
10388   Label L_exit;
10389 
10390   if (is_pclmulqdq_supported ) {
10391     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10392     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10393 
10394     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10395     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10396 
10397     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10398     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10399     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10400   } else {
10401     const_or_pre_comp_const_index[0] = 1;
10402     const_or_pre_comp_const_index[1] = 0;
10403 
10404     const_or_pre_comp_const_index[2] = 3;
10405     const_or_pre_comp_const_index[3] = 2;
10406 
10407     const_or_pre_comp_const_index[4] = 5;
10408     const_or_pre_comp_const_index[5] = 4;
10409    }
10410   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10411                     in2, in1, in_out,
10412                     tmp1, tmp2, tmp3,
10413                     w_xtmp1, w_xtmp2, w_xtmp3,
10414                     tmp4, tmp5,
10415                     tmp6);
10416   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10417                     in2, in1, in_out,
10418                     tmp1, tmp2, tmp3,
10419                     w_xtmp1, w_xtmp2, w_xtmp3,
10420                     tmp4, tmp5,
10421                     tmp6);
10422   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10423                     in2, in1, in_out,
10424                     tmp1, tmp2, tmp3,
10425                     w_xtmp1, w_xtmp2, w_xtmp3,
10426                     tmp4, tmp5,
10427                     tmp6);
10428   movl(tmp1, in2);
10429   andl(tmp1, 0x00000007);
10430   negl(tmp1);
10431   addl(tmp1, in2);
10432   addq(tmp1, in1);
10433 
10434   BIND(L_wordByWord);
10435   cmpq(in1, tmp1);
10436   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10437     crc32(in_out, Address(in1, 0), 4);
10438     addq(in1, 4);
10439     jmp(L_wordByWord);
10440 
10441   BIND(L_byteByByteProlog);
10442   andl(in2, 0x00000007);
10443   movl(tmp2, 1);
10444 
10445   BIND(L_byteByByte);
10446   cmpl(tmp2, in2);
10447   jccb(Assembler::greater, L_exit);
10448     crc32(in_out, Address(in1, 0), 1);
10449     incq(in1);
10450     incl(tmp2);
10451     jmp(L_byteByByte);
10452 
10453   BIND(L_exit);
10454 }
10455 #else
10456 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10457                                           Register tmp1, Register  tmp2, Register tmp3,
10458                                           Register tmp4, Register  tmp5, Register tmp6,
10459                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10460                                           bool is_pclmulqdq_supported) {
10461   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10462   Label L_wordByWord;
10463   Label L_byteByByteProlog;
10464   Label L_byteByByte;
10465   Label L_exit;
10466 
10467   if (is_pclmulqdq_supported) {
10468     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10469     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10470 
10471     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10472     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10473 
10474     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10475     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10476   } else {
10477     const_or_pre_comp_const_index[0] = 1;
10478     const_or_pre_comp_const_index[1] = 0;
10479 
10480     const_or_pre_comp_const_index[2] = 3;
10481     const_or_pre_comp_const_index[3] = 2;
10482 
10483     const_or_pre_comp_const_index[4] = 5;
10484     const_or_pre_comp_const_index[5] = 4;
10485   }
10486   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10487                     in2, in1, in_out,
10488                     tmp1, tmp2, tmp3,
10489                     w_xtmp1, w_xtmp2, w_xtmp3,
10490                     tmp4, tmp5,
10491                     tmp6);
10492   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10493                     in2, in1, in_out,
10494                     tmp1, tmp2, tmp3,
10495                     w_xtmp1, w_xtmp2, w_xtmp3,
10496                     tmp4, tmp5,
10497                     tmp6);
10498   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10499                     in2, in1, in_out,
10500                     tmp1, tmp2, tmp3,
10501                     w_xtmp1, w_xtmp2, w_xtmp3,
10502                     tmp4, tmp5,
10503                     tmp6);
10504   movl(tmp1, in2);
10505   andl(tmp1, 0x00000007);
10506   negl(tmp1);
10507   addl(tmp1, in2);
10508   addl(tmp1, in1);
10509 
10510   BIND(L_wordByWord);
10511   cmpl(in1, tmp1);
10512   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10513     crc32(in_out, Address(in1,0), 4);
10514     addl(in1, 4);
10515     jmp(L_wordByWord);
10516 
10517   BIND(L_byteByByteProlog);
10518   andl(in2, 0x00000007);
10519   movl(tmp2, 1);
10520 
10521   BIND(L_byteByByte);
10522   cmpl(tmp2, in2);
10523   jccb(Assembler::greater, L_exit);
10524     movb(tmp1, Address(in1, 0));
10525     crc32(in_out, tmp1, 1);
10526     incl(in1);
10527     incl(tmp2);
10528     jmp(L_byteByByte);
10529 
10530   BIND(L_exit);
10531 }
10532 #endif // LP64
10533 #undef BIND
10534 #undef BLOCK_COMMENT
10535 
10536 // Compress char[] array to byte[].
10537 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10538 //   @HotSpotIntrinsicCandidate
10539 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10540 //     for (int i = 0; i < len; i++) {
10541 //       int c = src[srcOff++];
10542 //       if (c >>> 8 != 0) {
10543 //         return 0;
10544 //       }
10545 //       dst[dstOff++] = (byte)c;
10546 //     }
10547 //     return len;
10548 //   }
10549 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10550   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10551   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10552   Register tmp5, Register result) {
10553   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10554 
10555   // rsi: src
10556   // rdi: dst
10557   // rdx: len
10558   // rcx: tmp5
10559   // rax: result
10560 
10561   // rsi holds start addr of source char[] to be compressed
10562   // rdi holds start addr of destination byte[]
10563   // rdx holds length
10564 
10565   assert(len != result, "");
10566 
10567   // save length for return
10568   push(len);
10569 
10570   if ((UseAVX > 2) && // AVX512
10571     VM_Version::supports_avx512vlbw() &&
10572     VM_Version::supports_bmi2()) {
10573 
10574     set_vector_masking();  // opening of the stub context for programming mask registers
10575 
10576     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10577 
10578     // alignement
10579     Label post_alignement;
10580 
10581     // if length of the string is less than 16, handle it in an old fashioned
10582     // way
10583     testl(len, -32);
10584     jcc(Assembler::zero, below_threshold);
10585 
10586     // First check whether a character is compressable ( <= 0xFF).
10587     // Create mask to test for Unicode chars inside zmm vector
10588     movl(result, 0x00FF);
10589     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10590 
10591     // Save k1
10592     kmovql(k3, k1);
10593 
10594     testl(len, -64);
10595     jcc(Assembler::zero, post_alignement);
10596 
10597     movl(tmp5, dst);
10598     andl(tmp5, (32 - 1));
10599     negl(tmp5);
10600     andl(tmp5, (32 - 1));
10601 
10602     // bail out when there is nothing to be done
10603     testl(tmp5, 0xFFFFFFFF);
10604     jcc(Assembler::zero, post_alignement);
10605 
10606     // ~(~0 << len), where len is the # of remaining elements to process
10607     movl(result, 0xFFFFFFFF);
10608     shlxl(result, result, tmp5);
10609     notl(result);
10610     kmovdl(k1, result);
10611 
10612     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10613     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10614     ktestd(k2, k1);
10615     jcc(Assembler::carryClear, restore_k1_return_zero);
10616 
10617     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10618 
10619     addptr(src, tmp5);
10620     addptr(src, tmp5);
10621     addptr(dst, tmp5);
10622     subl(len, tmp5);
10623 
10624     bind(post_alignement);
10625     // end of alignement
10626 
10627     movl(tmp5, len);
10628     andl(tmp5, (32 - 1));    // tail count (in chars)
10629     andl(len, ~(32 - 1));    // vector count (in chars)
10630     jcc(Assembler::zero, copy_loop_tail);
10631 
10632     lea(src, Address(src, len, Address::times_2));
10633     lea(dst, Address(dst, len, Address::times_1));
10634     negptr(len);
10635 
10636     bind(copy_32_loop);
10637     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10638     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10639     kortestdl(k2, k2);
10640     jcc(Assembler::carryClear, restore_k1_return_zero);
10641 
10642     // All elements in current processed chunk are valid candidates for
10643     // compression. Write a truncated byte elements to the memory.
10644     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10645     addptr(len, 32);
10646     jcc(Assembler::notZero, copy_32_loop);
10647 
10648     bind(copy_loop_tail);
10649     // bail out when there is nothing to be done
10650     testl(tmp5, 0xFFFFFFFF);
10651     // Restore k1
10652     kmovql(k1, k3);
10653     jcc(Assembler::zero, return_length);
10654 
10655     movl(len, tmp5);
10656 
10657     // ~(~0 << len), where len is the # of remaining elements to process
10658     movl(result, 0xFFFFFFFF);
10659     shlxl(result, result, len);
10660     notl(result);
10661 
10662     kmovdl(k1, result);
10663 
10664     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10665     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10666     ktestd(k2, k1);
10667     jcc(Assembler::carryClear, restore_k1_return_zero);
10668 
10669     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10670     // Restore k1
10671     kmovql(k1, k3);
10672     jmp(return_length);
10673 
10674     bind(restore_k1_return_zero);
10675     // Restore k1
10676     kmovql(k1, k3);
10677     jmp(return_zero);
10678 
10679     clear_vector_masking();   // closing of the stub context for programming mask registers
10680   }
10681   if (UseSSE42Intrinsics) {
10682     Label copy_32_loop, copy_16, copy_tail;
10683 
10684     bind(below_threshold);
10685 
10686     movl(result, len);
10687 
10688     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10689 
10690     // vectored compression
10691     andl(len, 0xfffffff0);    // vector count (in chars)
10692     andl(result, 0x0000000f);    // tail count (in chars)
10693     testl(len, len);
10694     jccb(Assembler::zero, copy_16);
10695 
10696     // compress 16 chars per iter
10697     movdl(tmp1Reg, tmp5);
10698     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10699     pxor(tmp4Reg, tmp4Reg);
10700 
10701     lea(src, Address(src, len, Address::times_2));
10702     lea(dst, Address(dst, len, Address::times_1));
10703     negptr(len);
10704 
10705     bind(copy_32_loop);
10706     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10707     por(tmp4Reg, tmp2Reg);
10708     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10709     por(tmp4Reg, tmp3Reg);
10710     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10711     jcc(Assembler::notZero, return_zero);
10712     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10713     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10714     addptr(len, 16);
10715     jcc(Assembler::notZero, copy_32_loop);
10716 
10717     // compress next vector of 8 chars (if any)
10718     bind(copy_16);
10719     movl(len, result);
10720     andl(len, 0xfffffff8);    // vector count (in chars)
10721     andl(result, 0x00000007);    // tail count (in chars)
10722     testl(len, len);
10723     jccb(Assembler::zero, copy_tail);
10724 
10725     movdl(tmp1Reg, tmp5);
10726     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10727     pxor(tmp3Reg, tmp3Reg);
10728 
10729     movdqu(tmp2Reg, Address(src, 0));
10730     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10731     jccb(Assembler::notZero, return_zero);
10732     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10733     movq(Address(dst, 0), tmp2Reg);
10734     addptr(src, 16);
10735     addptr(dst, 8);
10736 
10737     bind(copy_tail);
10738     movl(len, result);
10739   }
10740   // compress 1 char per iter
10741   testl(len, len);
10742   jccb(Assembler::zero, return_length);
10743   lea(src, Address(src, len, Address::times_2));
10744   lea(dst, Address(dst, len, Address::times_1));
10745   negptr(len);
10746 
10747   bind(copy_chars_loop);
10748   load_unsigned_short(result, Address(src, len, Address::times_2));
10749   testl(result, 0xff00);      // check if Unicode char
10750   jccb(Assembler::notZero, return_zero);
10751   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10752   increment(len);
10753   jcc(Assembler::notZero, copy_chars_loop);
10754 
10755   // if compression succeeded, return length
10756   bind(return_length);
10757   pop(result);
10758   jmpb(done);
10759 
10760   // if compression failed, return 0
10761   bind(return_zero);
10762   xorl(result, result);
10763   addptr(rsp, wordSize);
10764 
10765   bind(done);
10766 }
10767 
10768 // Inflate byte[] array to char[].
10769 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10770 //   @HotSpotIntrinsicCandidate
10771 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10772 //     for (int i = 0; i < len; i++) {
10773 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10774 //     }
10775 //   }
10776 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10777   XMMRegister tmp1, Register tmp2) {
10778   Label copy_chars_loop, done, below_threshold;
10779   // rsi: src
10780   // rdi: dst
10781   // rdx: len
10782   // rcx: tmp2
10783 
10784   // rsi holds start addr of source byte[] to be inflated
10785   // rdi holds start addr of destination char[]
10786   // rdx holds length
10787   assert_different_registers(src, dst, len, tmp2);
10788 
10789   if ((UseAVX > 2) && // AVX512
10790     VM_Version::supports_avx512vlbw() &&
10791     VM_Version::supports_bmi2()) {
10792 
10793     set_vector_masking();  // opening of the stub context for programming mask registers
10794 
10795     Label copy_32_loop, copy_tail;
10796     Register tmp3_aliased = len;
10797 
10798     // if length of the string is less than 16, handle it in an old fashioned
10799     // way
10800     testl(len, -16);
10801     jcc(Assembler::zero, below_threshold);
10802 
10803     // In order to use only one arithmetic operation for the main loop we use
10804     // this pre-calculation
10805     movl(tmp2, len);
10806     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10807     andl(len, -32);     // vector count
10808     jccb(Assembler::zero, copy_tail);
10809 
10810     lea(src, Address(src, len, Address::times_1));
10811     lea(dst, Address(dst, len, Address::times_2));
10812     negptr(len);
10813 
10814 
10815     // inflate 32 chars per iter
10816     bind(copy_32_loop);
10817     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10818     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10819     addptr(len, 32);
10820     jcc(Assembler::notZero, copy_32_loop);
10821 
10822     bind(copy_tail);
10823     // bail out when there is nothing to be done
10824     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10825     jcc(Assembler::zero, done);
10826 
10827     // Save k1
10828     kmovql(k2, k1);
10829 
10830     // ~(~0 << length), where length is the # of remaining elements to process
10831     movl(tmp3_aliased, -1);
10832     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10833     notl(tmp3_aliased);
10834     kmovdl(k1, tmp3_aliased);
10835     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10836     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10837 
10838     // Restore k1
10839     kmovql(k1, k2);
10840     jmp(done);
10841 
10842     clear_vector_masking();   // closing of the stub context for programming mask registers
10843   }
10844   if (UseSSE42Intrinsics) {
10845     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10846 
10847     movl(tmp2, len);
10848 
10849     if (UseAVX > 1) {
10850       andl(tmp2, (16 - 1));
10851       andl(len, -16);
10852       jccb(Assembler::zero, copy_new_tail);
10853     } else {
10854       andl(tmp2, 0x00000007);   // tail count (in chars)
10855       andl(len, 0xfffffff8);    // vector count (in chars)
10856       jccb(Assembler::zero, copy_tail);
10857     }
10858 
10859     // vectored inflation
10860     lea(src, Address(src, len, Address::times_1));
10861     lea(dst, Address(dst, len, Address::times_2));
10862     negptr(len);
10863 
10864     if (UseAVX > 1) {
10865       bind(copy_16_loop);
10866       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10867       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10868       addptr(len, 16);
10869       jcc(Assembler::notZero, copy_16_loop);
10870 
10871       bind(below_threshold);
10872       bind(copy_new_tail);
10873       if ((UseAVX > 2) &&
10874         VM_Version::supports_avx512vlbw() &&
10875         VM_Version::supports_bmi2()) {
10876         movl(tmp2, len);
10877       } else {
10878         movl(len, tmp2);
10879       }
10880       andl(tmp2, 0x00000007);
10881       andl(len, 0xFFFFFFF8);
10882       jccb(Assembler::zero, copy_tail);
10883 
10884       pmovzxbw(tmp1, Address(src, 0));
10885       movdqu(Address(dst, 0), tmp1);
10886       addptr(src, 8);
10887       addptr(dst, 2 * 8);
10888 
10889       jmp(copy_tail, true);
10890     }
10891 
10892     // inflate 8 chars per iter
10893     bind(copy_8_loop);
10894     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10895     movdqu(Address(dst, len, Address::times_2), tmp1);
10896     addptr(len, 8);
10897     jcc(Assembler::notZero, copy_8_loop);
10898 
10899     bind(copy_tail);
10900     movl(len, tmp2);
10901 
10902     cmpl(len, 4);
10903     jccb(Assembler::less, copy_bytes);
10904 
10905     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10906     pmovzxbw(tmp1, tmp1);
10907     movq(Address(dst, 0), tmp1);
10908     subptr(len, 4);
10909     addptr(src, 4);
10910     addptr(dst, 8);
10911 
10912     bind(copy_bytes);
10913   }
10914   testl(len, len);
10915   jccb(Assembler::zero, done);
10916   lea(src, Address(src, len, Address::times_1));
10917   lea(dst, Address(dst, len, Address::times_2));
10918   negptr(len);
10919 
10920   // inflate 1 char per iter
10921   bind(copy_chars_loop);
10922   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
10923   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
10924   increment(len);
10925   jcc(Assembler::notZero, copy_chars_loop);
10926 
10927   bind(done);
10928 }
10929 
10930 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
10931   switch (cond) {
10932     // Note some conditions are synonyms for others
10933     case Assembler::zero:         return Assembler::notZero;
10934     case Assembler::notZero:      return Assembler::zero;
10935     case Assembler::less:         return Assembler::greaterEqual;
10936     case Assembler::lessEqual:    return Assembler::greater;
10937     case Assembler::greater:      return Assembler::lessEqual;
10938     case Assembler::greaterEqual: return Assembler::less;
10939     case Assembler::below:        return Assembler::aboveEqual;
10940     case Assembler::belowEqual:   return Assembler::above;
10941     case Assembler::above:        return Assembler::belowEqual;
10942     case Assembler::aboveEqual:   return Assembler::below;
10943     case Assembler::overflow:     return Assembler::noOverflow;
10944     case Assembler::noOverflow:   return Assembler::overflow;
10945     case Assembler::negative:     return Assembler::positive;
10946     case Assembler::positive:     return Assembler::negative;
10947     case Assembler::parity:       return Assembler::noParity;
10948     case Assembler::noParity:     return Assembler::parity;
10949   }
10950   ShouldNotReachHere(); return Assembler::overflow;
10951 }
10952 
10953 SkipIfEqual::SkipIfEqual(
10954     MacroAssembler* masm, const bool* flag_addr, bool value) {
10955   _masm = masm;
10956   _masm->cmp8(ExternalAddress((address)flag_addr), value);
10957   _masm->jcc(Assembler::equal, _label);
10958 }
10959 
10960 SkipIfEqual::~SkipIfEqual() {
10961   _masm->bind(_label);
10962 }
10963 
10964 // 32-bit Windows has its own fast-path implementation
10965 // of get_thread
10966 #if !defined(WIN32) || defined(_LP64)
10967 
10968 // This is simply a call to Thread::current()
10969 void MacroAssembler::get_thread(Register thread) {
10970   if (thread != rax) {
10971     push(rax);
10972   }
10973   LP64_ONLY(push(rdi);)
10974   LP64_ONLY(push(rsi);)
10975   push(rdx);
10976   push(rcx);
10977 #ifdef _LP64
10978   push(r8);
10979   push(r9);
10980   push(r10);
10981   push(r11);
10982 #endif
10983 
10984   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
10985 
10986 #ifdef _LP64
10987   pop(r11);
10988   pop(r10);
10989   pop(r9);
10990   pop(r8);
10991 #endif
10992   pop(rcx);
10993   pop(rdx);
10994   LP64_ONLY(pop(rsi);)
10995   LP64_ONLY(pop(rdi);)
10996   if (thread != rax) {
10997     mov(thread, rax);
10998     pop(rax);
10999   }
11000 }
11001 
11002 #endif